问:
Jupyter Labs: "RuntimeError: npm dependencies failed to install" When Building
I'm new to using Anaconda and recently installed jupyter labs on my computer. However, any time I try to build on my local Jupyter Labs instance I get the following error:

Code run in jupyter labs terminal:

```<code>PS C:\Users\briakeit> jupyter lab build
</code>```

Output:

```<code>[LabBuildApp] JupyterLab 1.2.5
[LabBuildApp] Building in C:\Users\briakeit\AnacondaFiles\share\jupyter\lab
[LabBuildApp] Building jupyterlab assets (build:prod:minimize)
An error occured.
RuntimeError: npm dependencies failed to install
See the log file for details:  C:\Users\briakeit\AppData\Local\Temp\jupyterlab-debug-0b5ejkfm.log
</code>```

Log file:

```<code>[LabBuildApp] Building in C:\Users\briakeit\AnacondaFiles\share\jupyter\lab
[LabBuildApp] Yarn configuration loaded.
[LabBuildApp] Node v13.7.0

[LabBuildApp] Building jupyterlab assets (build:prod:minimize)
[LabBuildApp] > node C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\staging\yarn.js install --non-interactive
[LabBuildApp] yarn install v1.15.2
[1/5] Validating package.json...
[2/5] Resolving packages...
[3/5] Fetching packages...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
error An unexpected error occurred: "https://registry.yarnpkg.com/@jupyterlab/application-extension/-/application-extension-1.2.1.tgz: read ECONNRESET".
info If you think this is a bug, please open a bug report with the information provided in "C:\\Users\\briakeit\\AnacondaFiles\\share\\jupyter\\lab\\staging\\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

[LabBuildApp] npm dependencies failed to install
[LabBuildApp] Traceback (most recent call last):

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\debuglog.py", line 47, in debug_logging
    yield

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\labapp.py", line 98, in start
    command=command, app_options=app_options)

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\commands.py", line 459, in build
    command=command, clean_staging=clean_staging)

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\commands.py", line 660, in build
    raise RuntimeError(msg)

[LabBuildApp] RuntimeError: npm dependencies failed to install

[LabBuildApp] Exiting application: JupyterLab
</code>```

This happens anytime I try using this command (e.g. after installing anew extension). I have npm v6.4.1, nodejs v10.13.0, and yarn v1.22.0 installed in this environment according to conda. I'm running Jupyter lab 1.2.6.

Any feedback, suggestions or help would be greatly appreciated.

答:
I believe I have found the problem. I consult for a company and I was using the computer they provided me (I'm an admin on the computer). When I followed the same steps on my personal computer, it worked with no issues.

I then switched over to a different, more open network at work and the build was able to complete without errors. Clearly there is something in the firewall or something that was preventing me from doing the build.

Body:
I'm new to using Anaconda and recently installed jupyter labs on my computer. However, any time I try to build on my local Jupyter Labs instance I get the following error:

Code run in jupyter labs terminal:

PS C:\Users\briakeit> jupyter lab build

Output:

[LabBuildApp] JupyterLab 1.2.5
[LabBuildApp] Building in C:\Users\briakeit\AnacondaFiles\share\jupyter\lab
[LabBuildApp] Building jupyterlab assets (build:prod:minimize)
An error occured.
RuntimeError: npm dependencies failed to install
See the log file for details:  C:\Users\briakeit\AppData\Local\Temp\jupyterlab-debug-0b5ejkfm.log

Log file:

[LabBuildApp] Building in C:\Users\briakeit\AnacondaFiles\share\jupyter\lab
[LabBuildApp] Yarn configuration loaded.
[LabBuildApp] Node v13.7.0

[LabBuildApp] Building jupyterlab assets (build:prod:minimize)
[LabBuildApp] > node C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\staging\yarn.js install --non-interactive
[LabBuildApp] yarn install v1.15.2
[1/5] Validating package.json...
[2/5] Resolving packages...
[3/5] Fetching packages...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
error An unexpected error occurred: "https://registry.yarnpkg.com/@jupyterlab/application-extension/-/application-extension-1.2.1.tgz: read ECONNRESET".
info If you think this is a bug, please open a bug report with the information provided in "C:\\Users\\briakeit\\AnacondaFiles\\share\\jupyter\\lab\\staging\\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

[LabBuildApp] npm dependencies failed to install
[LabBuildApp] Traceback (most recent call last):

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\debuglog.py", line 47, in debug_logging
    yield

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\labapp.py", line 98, in start
    command=command, app_options=app_options)

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\commands.py", line 459, in build
    command=command, clean_staging=clean_staging)

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\commands.py", line 660, in build
    raise RuntimeError(msg)

[LabBuildApp] RuntimeError: npm dependencies failed to install

[LabBuildApp] Exiting application: JupyterLab

This happens anytime I try using this command (e.g. after installing anew extension). I have npm v6.4.1, nodejs v10.13.0, and yarn v1.22.0 installed in this environment according to conda. I'm running Jupyter lab 1.2.6.

Any feedback, suggestions or help would be greatly appreciated.


来源: stackexchange

问:
Russian characters are not getting decoded when accessing url directly
The nuxt-link works fine, but when I reload, it can't find the route.
The translated routes are informed like this:

nuxtI18n: { paths: { en: "/for-sale/", es: "/en-venta/", ru: "/для-продажи/", } }

I have observed that if I go directly to the encoded path, it will work, but if I use the russian characters it won't.
So if I go to http://localhost:3000/ru/для-продажи won't work, but going to http://localhost:3000/ru/%D0%B4%D0%BB%D1%8F-%D0%BF%D1%80%D0%BE%D0%B4%D0%B0%D0%B6%D0%B8 will.

How can I make it so it will encode russian characters when looking for route?

答:
My problem disappeared by adding</p>

```<code>// nuxt.config.js

['nuxt-i18n', {
  encodePaths: false
}]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My problem disappeared by adding

// nuxt.config.js

['nuxt-i18n', {
  encodePaths: false
}]


问:
Having host filesystem visible to singularity container
I use singularity images that do not require any binding of the desired host path, i.e.

```<code>singularity exec image.simg IMAGE_COMMAND -i $PWD/input_file -o ./output_dir
</code>```

simply works like any other command on the "input_file" in my host system, also using relative paths as in "-o".

I'm not comfortable enough with Singularity and its jargon to understand how this is made.

Is a configuration done in singularity.conf?

How is this feature called? (is it "MOUNT HOSTFS"?)

答:
By default, both your home and current directories are mounted/bound into the image for you. You can modify this in singularity.conf. Details on the settings are available in the admin documentation.

The MOUNT HOSTFS in the config is a toggle to automatically mount all host filesystems into the image. MOUNT HOME is the corresponding setting for auto-mounting the user's HOME directory.

You can see which files/directories are currently being mounted by using the --verbose option with your singularity command.

Body:
I use singularity images that do not require any binding of the desired host path, i.e.

singularity exec image.simg IMAGE_COMMAND -i $PWD/input_file -o ./output_dir

simply works like any other command on the "input_file" in my host system, also using relative paths as in "-o".

I'm not comfortable enough with Singularity and its jargon to understand how this is made.

Is a configuration done in singularity.conf?

How is this feature called? (is it "MOUNT HOSTFS"?)


问:
Howto use external plugins via config file (runtime configuration) with Autofac 5
I'm trying to setup a simple .NET Core 3.1 project that uses Autofac 5 IoC Container.

I've added a reference to latest Autofac.Configuration 5.0.0 package.

I've created interface, implementation and test app with a simple JSON config (following this guide):

```<code>{
  "components": [
    {
      "type": "Implementations.ImplementationN, Implementations",
      "services": [
        {
          "type": "Interfaces.InterfaceN, Interfaces"
        }
      ]
    }
  ]
}
</code>```

I use the following code (according to the same guide):

```<code>using Interfaces;
using Autofac;
using Autofac.Configuration;
using Microsoft.Extensions.Configuration;
using System;

------------------------
var config = new ConfigurationBuilder();
config.AddJsonFile("config.json");

var module = new ConfigurationModule(config.Build());

var builder = new ContainerBuilder();
builder.RegisterModule(module);

var container = builder.Build();
------------------------
</code>```

But I'm getting System.InvalidOperationException:

The type 'Implementations.ImplementationN, Implementations'
  could not be found. It may require assembly qualification,
  e.g. "MyType, MyAssembly"

I've uploaded my code to GitHub. Any help is appreciated.

P.S. Visual Studio 2019 16.4.5 Enterprise, Windows 10 1909 x64 Professional

UPDATE: To clarify more - my final goal is to have Interfaces.dll with no special references, Implementations.dll with reference to ONLY Interfaces.dll and Test.exe with reference to ONLY Interfaces.dll (and Autofac package of course). I expect Autofac to load specific class from a specific assembly (that are specified in config.json) via Reflection. That was possible with Unity Container and I expected to achieve the same with Autofac IoC.

Once again: I need an upproach without ANY project referencing Implementations.dll, I should be able to change specific implementation (via changing config.json) without recompilation.

答:
I've found out this more a ".NET Core assembly loading" problem than an Autofac problem.

To cut a long story short, if the assembly isn't specifically referenced by your app, you need to tell .NET Core assembly loader where to get it EVEN IF IT'S IN YOUR BIN FOLDER.

So if you (like me) don't want to have a bootstrap library that references all implementation libraries that you need but you want to have runtime configuration via config file - you should do the following.

From Autofac examples:

```<code>// THIS IS THE MAGIC!
// .NET Core assembly loading is confusing. Things that happen to be in your bin folder don't just suddenly
// qualify with the assembly loader. If the assembly isn't specifically referenced by your app, you need to
// tell .NET Core where to get it EVEN IF IT'S IN YOUR BIN FOLDER.
// https://stackoverflow.com/questions/43918837/net-core-1-1-type-gettype-from-external-assembly-returns-null
//
// The documentation says that any .dll in the application base folder should work, but that doesn't seem
// to be entirely true. You always have to set up additional handlers if you AREN'T referencing the plugin assembly.
// https://github.com/dotnet/core-setup/blob/master/Documentation/design-docs/corehost.md
//
// To verify, try commenting this out and you'll see that the config system can't load the external plugin type.
var executionFolder = Path.GetDirectoryName(typeof(Program).Assembly.Location);
AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext context, AssemblyName assembly) =>
{
     // DISCLAIMER: NO PROMISES THIS IS SECURE. You may or may not want this strategy. It's up to
     // you to determine if allowing any assembly in the directory to be loaded is acceptable. This
     // is for demo purposes only.
     return context.LoadFromAssemblyPath(Path.Combine(executionFolder, $"{assembly.Name}.dll"));
 };
</code>```

And after that the following code:

```<code> var config = new ConfigurationBuilder()
     .AddJsonFile("autofac.json")
     .Build();
 var configModule = new ConfigurationModule(config);
 var builder = new ContainerBuilder();
 builder.RegisterModule(configModule);
 var container = builder.Build();
</code>```

is working like a charm.

P.S. Some more info from Microsoft

Body:
I'm trying to setup a simple .NET Core 3.1 project that uses Autofac 5 IoC Container.

I've added a reference to latest Autofac.Configuration 5.0.0 package.

I've created interface, implementation and test app with a simple JSON config (following this guide):

{
  "components": [
    {
      "type": "Implementations.ImplementationN, Implementations",
      "services": [
        {
          "type": "Interfaces.InterfaceN, Interfaces"
        }
      ]
    }
  ]
}

I use the following code (according to the same guide):

using Interfaces;
using Autofac;
using Autofac.Configuration;
using Microsoft.Extensions.Configuration;
using System;

------------------------
var config = new ConfigurationBuilder();
config.AddJsonFile("config.json");

var module = new ConfigurationModule(config.Build());

var builder = new ContainerBuilder();
builder.RegisterModule(module);

var container = builder.Build();
------------------------

But I'm getting System.InvalidOperationException:

The type 'Implementations.ImplementationN, Implementations'
  could not be found. It may require assembly qualification,
  e.g. "MyType, MyAssembly"

I've uploaded my code to GitHub. Any help is appreciated.

P.S. Visual Studio 2019 16.4.5 Enterprise, Windows 10 1909 x64 Professional

UPDATE: To clarify more - my final goal is to have Interfaces.dll with no special references, Implementations.dll with reference to ONLY Interfaces.dll and Test.exe with reference to ONLY Interfaces.dll (and Autofac package of course). I expect Autofac to load specific class from a specific assembly (that are specified in config.json) via Reflection. That was possible with Unity Container and I expected to achieve the same with Autofac IoC.

Once again: I need an upproach without ANY project referencing Implementations.dll, I should be able to change specific implementation (via changing config.json) without recompilation.

Body:
I've found out this more a ".NET Core assembly loading" problem than an Autofac problem.

To cut a long story short, if the assembly isn't specifically referenced by your app, you need to tell .NET Core assembly loader where to get it EVEN IF IT'S IN YOUR BIN FOLDER.

So if you (like me) don't want to have a bootstrap library that references all implementation libraries that you need but you want to have runtime configuration via config file - you should do the following.

From Autofac examples:

// THIS IS THE MAGIC!
// .NET Core assembly loading is confusing. Things that happen to be in your bin folder don't just suddenly
// qualify with the assembly loader. If the assembly isn't specifically referenced by your app, you need to
// tell .NET Core where to get it EVEN IF IT'S IN YOUR BIN FOLDER.
// https://stackoverflow.com/questions/43918837/net-core-1-1-type-gettype-from-external-assembly-returns-null
//
// The documentation says that any .dll in the application base folder should work, but that doesn't seem
// to be entirely true. You always have to set up additional handlers if you AREN'T referencing the plugin assembly.
// https://github.com/dotnet/core-setup/blob/master/Documentation/design-docs/corehost.md
//
// To verify, try commenting this out and you'll see that the config system can't load the external plugin type.
var executionFolder = Path.GetDirectoryName(typeof(Program).Assembly.Location);
AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext context, AssemblyName assembly) =>
{
     // DISCLAIMER: NO PROMISES THIS IS SECURE. You may or may not want this strategy. It's up to
     // you to determine if allowing any assembly in the directory to be loaded is acceptable. This
     // is for demo purposes only.
     return context.LoadFromAssemblyPath(Path.Combine(executionFolder, $"{assembly.Name}.dll"));
 };

And after that the following code:

 var config = new ConfigurationBuilder()
     .AddJsonFile("autofac.json")
     .Build();
 var configModule = new ConfigurationModule(config);
 var builder = new ContainerBuilder();
 builder.RegisterModule(configModule);
 var container = builder.Build();

is working like a charm.

P.S. Some more info from Microsoft


问:
Change Karnaugh Map simplifier from SOP to POS result
It's my program to simplify Karnough map. I need to change it from SOP to POS for university project. I changed already signs from + to * and from * to +. All i have to do now is to make it read zero-s from text file instead of one's. i tried everything to solve that problem, but i have no idea. I have got two txt files, one with input and one with output. At this moment i need to put in input 0's instead of 1's and in the other side to, to make it work. Please help me, my life depends of that</p>

```<code>#include <iostream>
#include <fstream>
#include <cmath>
#include <windows.h>

using namespace std;
//?????
int pow2(int n) // ??2?????,2^n
{
    int result=1
    ;
    while(n>0)
        result*=2,n--;
    return result;
}
int combination(int n,int r) // ?????C_n^r,? n! / ((n-r)!*(r)!)
{
    int fm=1,fz=1;
    for(int i=1;i<=r;i++,n--)
    {
        fm*=i;
        fz*=n;
    }
    return fz/fm;
}
void d2b(int d,char* b,int n) // ???????,??????d???????????b?
{
    for(n--;n>=0;n--)
    {
        b[n]='0'+d%2;
        d/=2;
    }
}
int ispair(char* a1,char* a2,int n) // ????????????????
{
    int x,y=0;
    for(int i=0;i<n;i++)
        if(a1[i]!=a2[i])
            x=i,y++;
    if(y==1) return x;
    else return-1;
}
bool issame(char* a1,char* a2,int n) // ????
{
    for(int i=0;i<n;i++)
        if(a1[i]!=a2[i])
            return 0;
    return 1;
}
int left1(char* a,int N) // ???????????,??????1,??????
{
    for(int i=0;i<N;i++)
        if(a[i]=='1')
            return i;
    return -1;
}
void copy(char* a1,char* a2,int n) // ??????
{
    for(int i=0;i<n;i++)
        a2[i]=a1[i];
}
bool isinside(int x,char* a,int n) // ???x????????a?
{
    for(n--;n>=0;n--)
    {
        if(a[n]!='x' && a[n]!=(char)('0'+x%2))
            return 0;
        x/=2;
    }
    return 1;
}
void output(fstream& file,char* a,int n)
{

    for(int i=0;i<n;i++)

    {

        if(i==0)file<<'(';
        if(a[i]=='0'||a[i]=='1')

        {

            if(a[i]=='0') file<<'¬'<<(char)('a'+i);
            if(a[i]=='1') file<<(char)('a'+i);
            if(a[i+1]=='0'||a[i+1]=='1'||a[i+2]=='0'||a[i+2]=='1'||a[i+3]=='0'||a[i+3]=='1')
            {
            file<<'+';
            }
            else{
            file<<')';
            }
        }
        else{}

        ;
    }
    file<<'*';
}
int count(char* table,char* a,int n,int N) // ??,????????1???????????a?
{
    int counter=0;
    for(int i=0;i<N;i++)
    {
        if(table[i]!='1') continue;
        if(isinside(i,a,n)) counter++;
    }
    return counter;
}
void clean(char* table,char* a,int n,int N) // ??????????????????1,???x
{
    for(int j=0;j<N;j++)
        if(isinside(j,a,n))
            table[j]='x';
}
int main()
{
    SetConsoleTitle("???-???????????");
    system("color 06");
    //????
    fstream inputFile("input.txt",ios::in); //??????????input.txt
    int valNum; //???
    inputFile >> valNum; // ???????????
    cout<<"\n ????????: "<<valNum;
    cout<<"\n ?????????:\n";
    int minTermLength=pow2(valNum); // ??????????2^valNum?
    char* minTermExpression=new char[minTermLength]; // ???????????????
    int lineOff = pow2(ceil(double(valNum)/2));
    // ???????
    if (inputFile.is_open())
    {
        for(int i=0;i<minTermLength;i++) // ?????
        {
            inputFile>>minTermExpression[i];
            if(i%lineOff == 0&&(i!=0))
                cout<<"\n";
            cout<<"\t"<<minTermExpression[i];
        }
        inputFile.close();
    }
    // ??????
    else{
        cout<<"\n ??input.txt??,???????";
        return 0;
    }
    // ?implication????????
    char*** implication=new char**[valNum]; // ????

    int nonZeroNum=1;
    for(int i=0;i<minTermLength;i++)
        if(minTermExpression[i]!='0') // ?????ON???DC?????????
            nonZeroNum++;
    for(int i=0;i<valNum;i++) // i-??,???????3?,i=0???????,i=1???,i=2???
    {
        if(pow2(i)>nonZeroNum)break;
        int x=pow2(i-1)*combination(nonZeroNum,pow2(i));

        implication[i]=new char*[x];
        for(int j=0;j<x;j++)
            implication[i][j]=new char[valNum];
    }
    //?????????
    int* countNum=new int[valNum+1];
    countNum[0]=0;
    for(int i=0;i<minTermLength;i++)
        if(minTermExpression[i]!='0') // ???0?
        {
            d2b(i,implication[0][countNum[0]],valNum); // ??????????implication[0]???
            countNum[0]++;
        }
    int isOptimal=0;
    while(countNum[isOptimal]>0) // ??????????
    {
        countNum[isOptimal+1]=0;
        for(int i=0;i<countNum[isOptimal]-1;i++)
            for(int j=i+1;j<countNum[isOptimal];j++)
            {
                int x=ispair(implication[isOptimal][i],implication[isOptimal][j],valNum); // ??????????
                if(x==-1) continue;
                copy(implication[isOptimal][i],implication[isOptimal+1][countNum[isOptimal+1]],valNum);// ???implication??
                implication[isOptimal+1][countNum[isOptimal+1]][x]='x'; // ??????????,?????????x,???????????
                countNum[isOptimal+1]++;
            }
        for(int i=0;i<countNum[isOptimal+1]-1;i++)
            for(int j=i+1;j<countNum[isOptimal+1];j++)
                if(issame(implication[isOptimal+1][i],implication[isOptimal+1][j],valNum)) // ??????
                {
                    for(int k=j;k<countNum[isOptimal+1]-1;k++)
                        copy(implication[isOptimal+1][k+1],implication[isOptimal+1][k],valNum);
                    countNum[isOptimal+1]--;
                }
        isOptimal++;
    }
    isOptimal--;
    //???????
    fstream outputFile("output.txt",ios::out);
    outputFile<<"F=";
    while(left1(minTermExpression,minTermLength)>=0) //?minTermExpression???1
    {
        bool flag=0; // ???,????
        for(int i=0;i<minTermLength&&flag==0;i++)
        {
            if(minTermExpression[i]!='1') continue;
            int counter=0,recorder;
            for(int j=0;j<countNum[isOptimal];j++)
                if(isinside(i,implication[isOptimal][j],valNum))
                    counter++,recorder=j;
            if(counter!=1) continue;
            output(outputFile,implication[isOptimal][recorder],valNum);
            clean(minTermExpression,implication[isOptimal][recorder],valNum,minTermLength);
            flag=1;
        }
        if(flag==1) continue;
        int termMaxInclude=0;
        int recorder=0;
        for(int i=0;i<countNum[isOptimal];i++) // ??????????,???????????1???,??????
            if(count(minTermExpression,implication[isOptimal][i],valNum,minTermLength)>termMaxInclude)
                termMaxInclude=count(minTermExpression,implication[isOptimal][i],valNum,minTermLength),recorder=i;
        if(termMaxInclude==0) {isOptimal--; continue;}
        output(outputFile,implication[isOptimal][recorder],valNum);
        clean(minTermExpression,implication[isOptimal][recorder],valNum,minTermLength);
    }
    outputFile.close();
    // ?????
    outputFile.open("output.txt",ios::in);
    char finalExpression[201];
    outputFile.getline(finalExpression,200);
    outputFile.close();
    int termMaxInclude=0;
    for(;finalExpression[termMaxInclude]!='\0';termMaxInclude++);
        finalExpression[termMaxInclude-1]='\0';
    outputFile.open("output.txt",ios::out);
    outputFile<<finalExpression;
    outputFile.close();
    cout<<"\n??????????????";

    cout<<"\n ??????,??????!";
    cin.get();
    return 0;
}
</code>```

答: The zeros are simply those not in the ones list.</p>

Body:
It's my program to simplify Karnough map. I need to change it from SOP to POS for university project. I changed already signs from + to * and from * to +. All i have to do now is to make it read zero-s from text file instead of one's. i tried everything to solve that problem, but i have no idea. I have got two txt files, one with input and one with output. At this moment i need to put in input 0's instead of 1's and in the other side to, to make it work. Please help me, my life depends of that

#include <iostream>
#include <fstream>
#include <cmath>
#include <windows.h>

using namespace std;
//?????
int pow2(int n) // ??2?????,2^n
{
    int result=1
    ;
    while(n>0)
        result*=2,n--;
    return result;
}
int combination(int n,int r) // ?????C_n^r,? n! / ((n-r)!*(r)!)
{
    int fm=1,fz=1;
    for(int i=1;i<=r;i++,n--)
    {
        fm*=i;
        fz*=n;
    }
    return fz/fm;
}
void d2b(int d,char* b,int n) // ???????,??????d???????????b?
{
    for(n--;n>=0;n--)
    {
        b[n]='0'+d%2;
        d/=2;
    }
}
int ispair(char* a1,char* a2,int n) // ????????????????
{
    int x,y=0;
    for(int i=0;i<n;i++)
        if(a1[i]!=a2[i])
            x=i,y++;
    if(y==1) return x;
    else return-1;
}
bool issame(char* a1,char* a2,int n) // ????
{
    for(int i=0;i<n;i++)
        if(a1[i]!=a2[i])
            return 0;
    return 1;
}
int left1(char* a,int N) // ???????????,??????1,??????
{
    for(int i=0;i<N;i++)
        if(a[i]=='1')
            return i;
    return -1;
}
void copy(char* a1,char* a2,int n) // ??????
{
    for(int i=0;i<n;i++)
        a2[i]=a1[i];
}
bool isinside(int x,char* a,int n) // ???x????????a?
{
    for(n--;n>=0;n--)
    {
        if(a[n]!='x' && a[n]!=(char)('0'+x%2))
            return 0;
        x/=2;
    }
    return 1;
}
void output(fstream& file,char* a,int n)
{

    for(int i=0;i<n;i++)

    {

        if(i==0)file<<'(';
        if(a[i]=='0'||a[i]=='1')

        {

            if(a[i]=='0') file<<'¬'<<(char)('a'+i);
            if(a[i]=='1') file<<(char)('a'+i);
            if(a[i+1]=='0'||a[i+1]=='1'||a[i+2]=='0'||a[i+2]=='1'||a[i+3]=='0'||a[i+3]=='1')
            {
            file<<'+';
            }
            else{
            file<<')';
            }
        }
        else{}

        ;
    }
    file<<'*';
}
int count(char* table,char* a,int n,int N) // ??,????????1???????????a?
{
    int counter=0;
    for(int i=0;i<N;i++)
    {
        if(table[i]!='1') continue;
        if(isinside(i,a,n)) counter++;
    }
    return counter;
}
void clean(char* table,char* a,int n,int N) // ??????????????????1,???x
{
    for(int j=0;j<N;j++)
        if(isinside(j,a,n))
            table[j]='x';
}
int main()
{
    SetConsoleTitle("???-???????????");
    system("color 06");
    //????
    fstream inputFile("input.txt",ios::in); //??????????input.txt
    int valNum; //???
    inputFile >> valNum; // ???????????
    cout<<"\n ????????: "<<valNum;
    cout<<"\n ?????????:\n";
    int minTermLength=pow2(valNum); // ??????????2^valNum?
    char* minTermExpression=new char[minTermLength]; // ???????????????
    int lineOff = pow2(ceil(double(valNum)/2));
    // ???????
    if (inputFile.is_open())
    {
        for(int i=0;i<minTermLength;i++) // ?????
        {
            inputFile>>minTermExpression[i];
            if(i%lineOff == 0&&(i!=0))
                cout<<"\n";
            cout<<"\t"<<minTermExpression[i];
        }
        inputFile.close();
    }
    // ??????
    else{
        cout<<"\n ??input.txt??,???????";
        return 0;
    }
    // ?implication????????
    char*** implication=new char**[valNum]; // ????

    int nonZeroNum=1;
    for(int i=0;i<minTermLength;i++)
        if(minTermExpression[i]!='0') // ?????ON???DC?????????
            nonZeroNum++;
    for(int i=0;i<valNum;i++) // i-??,???????3?,i=0???????,i=1???,i=2???
    {
        if(pow2(i)>nonZeroNum)break;
        int x=pow2(i-1)*combination(nonZeroNum,pow2(i));

        implication[i]=new char*[x];
        for(int j=0;j<x;j++)
            implication[i][j]=new char[valNum];
    }
    //?????????
    int* countNum=new int[valNum+1];
    countNum[0]=0;
    for(int i=0;i<minTermLength;i++)
        if(minTermExpression[i]!='0') // ???0?
        {
            d2b(i,implication[0][countNum[0]],valNum); // ??????????implication[0]???
            countNum[0]++;
        }
    int isOptimal=0;
    while(countNum[isOptimal]>0) // ??????????
    {
        countNum[isOptimal+1]=0;
        for(int i=0;i<countNum[isOptimal]-1;i++)
            for(int j=i+1;j<countNum[isOptimal];j++)
            {
                int x=ispair(implication[isOptimal][i],implication[isOptimal][j],valNum); // ??????????
                if(x==-1) continue;
                copy(implication[isOptimal][i],implication[isOptimal+1][countNum[isOptimal+1]],valNum);// ???implication??
                implication[isOptimal+1][countNum[isOptimal+1]][x]='x'; // ??????????,?????????x,???????????
                countNum[isOptimal+1]++;
            }
        for(int i=0;i<countNum[isOptimal+1]-1;i++)
            for(int j=i+1;j<countNum[isOptimal+1];j++)
                if(issame(implication[isOptimal+1][i],implication[isOptimal+1][j],valNum)) // ??????
                {
                    for(int k=j;k<countNum[isOptimal+1]-1;k++)
                        copy(implication[isOptimal+1][k+1],implication[isOptimal+1][k],valNum);
                    countNum[isOptimal+1]--;
                }
        isOptimal++;
    }
    isOptimal--;
    //???????
    fstream outputFile("output.txt",ios::out);
    outputFile<<"F=";
    while(left1(minTermExpression,minTermLength)>=0) //?minTermExpression???1
    {
        bool flag=0; // ???,????
        for(int i=0;i<minTermLength&&flag==0;i++)
        {
            if(minTermExpression[i]!='1') continue;
            int counter=0,recorder;
            for(int j=0;j<countNum[isOptimal];j++)
                if(isinside(i,implication[isOptimal][j],valNum))
                    counter++,recorder=j;
            if(counter!=1) continue;
            output(outputFile,implication[isOptimal][recorder],valNum);
            clean(minTermExpression,implication[isOptimal][recorder],valNum,minTermLength);
            flag=1;
        }
        if(flag==1) continue;
        int termMaxInclude=0;
        int recorder=0;
        for(int i=0;i<countNum[isOptimal];i++) // ??????????,???????????1???,??????
            if(count(minTermExpression,implication[isOptimal][i],valNum,minTermLength)>termMaxInclude)
                termMaxInclude=count(minTermExpression,implication[isOptimal][i],valNum,minTermLength),recorder=i;
        if(termMaxInclude==0) {isOptimal--; continue;}
        output(outputFile,implication[isOptimal][recorder],valNum);
        clean(minTermExpression,implication[isOptimal][recorder],valNum,minTermLength);
    }
    outputFile.close();
    // ?????
    outputFile.open("output.txt",ios::in);
    char finalExpression[201];
    outputFile.getline(finalExpression,200);
    outputFile.close();
    int termMaxInclude=0;
    for(;finalExpression[termMaxInclude]!='\0';termMaxInclude++);
        finalExpression[termMaxInclude-1]='\0';
    outputFile.open("output.txt",ios::out);
    outputFile<<finalExpression;
    outputFile.close();
    cout<<"\n??????????????";

    cout<<"\n ??????,??????!";
    cin.get();
    return 0;
}


问:
Tkinter - Display contents of entry on pressing enter
In Python TKinter - How do I display the contents of an entry box immedietly after the user has typed in the box and pressed enter?

All of the examples I can see on the web only ever display the contents when a button is clicked.

I want my user to type their name into an entry box, click enter and THEN have a label display their name.

This isn't doing what I want:

```<code>entername = Entry(window,width=30)
entername.pack()

text3text = entername.get()
text3 = Label(window, text= "hello" + text3text)
text3.pack()
</code>```

答:
This should work for you:

```<code>window= Tk()

entername = Entry(window,width=30)
entername.pack()

text3 = Label(window, text= "hello")
text3.pack()

def grab_entry(event):
    text3.configure(text = text3['text'] + entername.get())

entername.bind('<Return>', grab_entry) #binds 'enter' to the confirm function

window.mainloop()
</code>```

If you want the label to be displayed after the Entry is given do it like that:

```<code>def grab_entry(event):
    text3 = Label(window, text= "hello" + entername.get())
    text3.pack()
</code>```

I would suggest using the first version, but instead of displaying hello use some instructions, like Enter your Name here or something like that. And then, when the Name is entered show the Hello-Message...

Body:
In Python TKinter - How do I display the contents of an entry box immedietly after the user has typed in the box and pressed enter?

All of the examples I can see on the web only ever display the contents when a button is clicked.

I want my user to type their name into an entry box, click enter and THEN have a label display their name.

This isn't doing what I want:

entername = Entry(window,width=30)
entername.pack()

text3text = entername.get()
text3 = Label(window, text= "hello" + text3text)
text3.pack()

Body:
This should work for you:

window= Tk()

entername = Entry(window,width=30)
entername.pack()

text3 = Label(window, text= "hello")
text3.pack()

def grab_entry(event):
    text3.configure(text = text3['text'] + entername.get())

entername.bind('<Return>', grab_entry) #binds 'enter' to the confirm function

window.mainloop()

If you want the label to be displayed after the Entry is given do it like that:

def grab_entry(event):
    text3 = Label(window, text= "hello" + entername.get())
    text3.pack()

I would suggest using the first version, but instead of displaying hello use some instructions, like Enter your Name here or something like that. And then, when the Name is entered show the Hello-Message...


问:
Using case statements with IsDate in a SQL where clause
I am trying to clean up the where clause statement in the following code:

```<code>SELECT
    CONVERT(datetime, [UTC_Time_Stamp], 127) AS TimeStamp
FROM
    Table
WHERE
    CASE
       WHEN ISDATE([UTC_Time_Stamp]) = 1
       THEN CONVERT(datetime, [UTC_Time_Stamp], 127)
       ELSE CAST('1/1/1900' AS datetime)
    END > CAST('11/09/2012' AS datetime)
    AND
       CASE
          WHEN ISDATE([UTC_Time_Stamp]) = 1
          THEN CONVERT(datetime, [UTC_Time_Stamp], 127)
          ELSE CAST('1/1/3000' AS datetime)
       END < CAST('11/10/2012' as datetime)
ORDER BY
    TimeStamp;
</code>```

UTC_Time_Stamp is stored as a string and is sometimes null. I was previously running into a conversion error inside my where clause. I fixed the error following advice from this question here, but I feel like there has to be a simpler way to achieve the same result.

答:
In this time for me this solves the problem of working with temporary table alias
or sub queries that can slow down the selection of millions of records.

```<code>select your_column
from your_table
where case when ISDATE(your_column) = 1
           then Cast(your_column as date)
      end Between '01/01/2016' and '01/01/2017'
order by your_column
</code>```

Regards

ContentLicense: CC BY-SA 3.0

Body:
I am trying to clean up the where clause statement in the following code:

SELECT
    CONVERT(datetime, [UTC_Time_Stamp], 127) AS TimeStamp
FROM
    Table
WHERE
    CASE
       WHEN ISDATE([UTC_Time_Stamp]) = 1
       THEN CONVERT(datetime, [UTC_Time_Stamp], 127)
       ELSE CAST('1/1/1900' AS datetime)
    END > CAST('11/09/2012' AS datetime)
    AND
       CASE
          WHEN ISDATE([UTC_Time_Stamp]) = 1
          THEN CONVERT(datetime, [UTC_Time_Stamp], 127)
          ELSE CAST('1/1/3000' AS datetime)
       END < CAST('11/10/2012' as datetime)
ORDER BY
    TimeStamp;

UTC_Time_Stamp is stored as a string and is sometimes null. I was previously running into a conversion error inside my where clause. I fixed the error following advice from this question here, but I feel like there has to be a simpler way to achieve the same result.

Body:
In this time for me this solves the problem of working with temporary table alias
or sub queries that can slow down the selection of millions of records.

select your_column
from your_table
where case when ISDATE(your_column) = 1
           then Cast(your_column as date)
      end Between '01/01/2016' and '01/01/2017'
order by your_column

Regards


问:
CATextLayer cannot align to center horizontally with UILabel text in swift
When i use CATextLayer in swift 5, i align it to center by using Horizontal alignment modes follow here
but it cannot align to center. Here is some of my code

```<code>myLabel.textAlignment = .center

textLayer.frame = myLabel.bounds;
textLayer.alignmentMode = CATextLayerAlignmentMode.center
</code>```

But when i run on ipad pro, i set position x to 500 and it moved to center

```<code>textLayer.position = CGPoint(500,20)
</code>```

But it's not exact and i don't know the reason why it is. So how can i align the CATextLayer exactly to the center as the center Label text?

答:
I don't know what is textLayer in your code but if you want use CATextLayerAlignmentMode you can set it to your label</p>

```<code>  myLabel.textAlignment = CATextLayerAlignmentMode.center
</code>```

Body:
When i use CATextLayer in swift 5, i align it to center by using Horizontal alignment modes follow here
but it cannot align to center. Here is some of my code

myLabel.textAlignment = .center

textLayer.frame = myLabel.bounds;
textLayer.alignmentMode = CATextLayerAlignmentMode.center

But when i run on ipad pro, i set position x to 500 and it moved to center

textLayer.position = CGPoint(500,20)

But it's not exact and i don't know the reason why it is. So how can i align the CATextLayer exactly to the center as the center Label text?

Body:
I don't know what is textLayer in your code but if you want use CATextLayerAlignmentMode you can set it to your label

  myLabel.textAlignment = CATextLayerAlignmentMode.center


问:
R help - why can't I download the nortest package on my work computer?
I need to use R to do some stats at work. The problem is, when I try and download the nortest package, using the following function:

```<code>install.packages("nortest")
</code>```

Or by selecting 'install packages' from the R menu (NB.: I am using a UK CRAN mirror), I get the following error message:

```<code>Error in read.dcf(file = tmpf) :
  Line starting '<head><title> ...' is malformed!
</code>```

I spoke to the IT dept at work and they mentioned that because R is open source, there are blocks on downloading certain things - and we ran a check and the system was blocking my download of nortest, for security reasons. The IT guy did say he wouldn't mind lowering the block just once, if I could then save the (zip?) file so I didn't need to access the internet every time I loaded up the package.

The problem is, I have no idea how to get a copy of 'nortest' as a zip file. And then once I have it, I don't know how to save it so that it loads from a saved file rather than selecting 'install package' from the R menu.

Any help would be very much appreciated.

Thanks,

Kate

答:
At first, you should know, that if you have installed the package you don't need to download it again (unless you delete it purposefully from your R folder). just load it with require(nortest) and it will fetch it from your hard drive. So you could go with the just once solution provided by your IT guys.

However, there will always be other interesting packages, e.g. (for me): stringr, reshape, ez, ...

So you will need a permanent solution.

If it does not work with setInternet2 as Richie Cotton suggested there is another way of getting packages.

You can download the zip files directly from the web page on cran. For nortest the direct link to the zip is the following: http://cran.r-project.org/bin/windows/contrib/r-release/nortest_1.0.zip

Then, you need to change the working directory of r (see ?getwd ans ?setwd) to the directory that contains the zip file and install it directly from your harddrive within R with:

```<code>install.packages("nortest_1.0.zip", repos = NULL)
</code>```

This works for any package with the correct file name.

Body:
I need to use R to do some stats at work. The problem is, when I try and download the nortest package, using the following function:

install.packages("nortest")

Or by selecting 'install packages' from the R menu (NB.: I am using a UK CRAN mirror), I get the following error message:

Error in read.dcf(file = tmpf) :
  Line starting '<title> ...' is malformed!

I spoke to the IT dept at work and they mentioned that because R is open source, there are blocks on downloading certain things - and we ran a check and the system was blocking my download of nortest, for security reasons. The IT guy did say he wouldn't mind lowering the block just once, if I could then save the (zip?) file so I didn't need to access the internet every time I loaded up the package.

The problem is, I have no idea how to get a copy of 'nortest' as a zip file. And then once I have it, I don't know how to save it so that it loads from a saved file rather than selecting 'install package' from the R menu.

Any help would be very much appreciated.

Thanks,

Kate

Body:
At first, you should know, that if you have installed the package you don't need to download it again (unless you delete it purposefully from your R folder). just load it with require(nortest) and it will fetch it from your hard drive. So you could go with the just once solution provided by your IT guys.

However, there will always be other interesting packages, e.g. (for me): stringr, reshape, ez, ...

So you will need a permanent solution.

If it does not work with setInternet2 as Richie Cotton suggested there is another way of getting packages.

You can download the zip files directly from the web page on cran. For nortest the direct link to the zip is the following: http://cran.r-project.org/bin/windows/contrib/r-release/nortest_1.0.zip

Then, you need to change the working directory of r (see ?getwd ans ?setwd) to the directory that contains the zip file and install it directly from your harddrive within R with:

install.packages("nortest_1.0.zip", repos = NULL)

This works for any package with the correct file name.


问:
How to exclude a field when its id is empty in mapStruct?
i am new at mapStruct and i don't know how to exclude a field when it's empty.

The Classes look like these:

```<code>public class MyClass {
    String reference;
    Info info;
    ...
}

public class Info{
    Long id;
    List<String> parts = new ArrayList<>();
    ...
}
</code>```

And this is the mapper:

```<code>@Mapping(target = "info.id", source = "infoId")
public abstract MyClass toMyClass(RequestProto.line Line);
</code>```

So when the info.id comes empty i get MyClass instantiated with the parameter info with an empty list of parts.

```<code>MYCLASS(current)
{
    reference: "aa",
     info: {
       parts: []
     }
}
</code>```

What i want is that when the info.id is empty the info parameter is null.

```<code>MYCLASS(expected)
{
    reference: "aa"
    info: null
}
</code>```

I have no idea how to achieve this.

I hope i explained my self. If someone can bring me some light with this would be much appreciated

答:
You could use your own logic for it:

```<code>@Mapping(target = "info", source = "Line", qualifiedByName = "info")
public abstract MyClass toMyClass(RequestProto.line Line);

@Named("info")
public Info mapInfo(RequestProto.line Line) {
   if(infoId.isEmpty()) {
      return null;
   }
   Info info = new Info();
   info.setId(infoId);
   return info;
}
</code>```

or you could create new class for it:

```<code>@Mapper(uses = {InfoMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public MyClassMapper {

   @Mapping(target = "info", source = "Line", qualifiedByName = "info")
   public abstract MyClass toMyClass(RequestProto.line Line);
}
public class InfoMapper implements Function<Info, RequestProto.line> {

   @Override
   @Named("info")
   public Info apply(RequestProto.line Line) {
   //pseudo code, make it better based on your request object
      if(infoId.isEmpty()) {
          return null;
      }
      Info info = new Info();
      info.setId(infoId);
      return info;
   }
</code>```

Body:
i am new at mapStruct and i don't know how to exclude a field when it's empty.

The Classes look like these:

public class MyClass {
    String reference;
    Info info;
    ...
}

public class Info{
    Long id;
    List<String> parts = new ArrayList<>();
    ...
}

And this is the mapper:

@Mapping(target = "info.id", source = "infoId")
public abstract MyClass toMyClass(RequestProto.line Line);

So when the info.id comes empty i get MyClass instantiated with the parameter info with an empty list of parts.

MYCLASS(current)
{
    reference: "aa",
     info: {
       parts: []
     }
}

What i want is that when the info.id is empty the info parameter is null.

MYCLASS(expected)
{
    reference: "aa"
    info: null
}

I have no idea how to achieve this.

I hope i explained my self. If someone can bring me some light with this would be much appreciated

Body:
You could use your own logic for it:

@Mapping(target = "info", source = "Line", qualifiedByName = "info")
public abstract MyClass toMyClass(RequestProto.line Line);

@Named("info")
public Info mapInfo(RequestProto.line Line) {
   if(infoId.isEmpty()) {
      return null;
   }
   Info info = new Info();
   info.setId(infoId);
   return info;
}

or you could create new class for it:

@Mapper(uses = {InfoMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public MyClassMapper {

   @Mapping(target = "info", source = "Line", qualifiedByName = "info")
   public abstract MyClass toMyClass(RequestProto.line Line);
}
public class InfoMapper implements Function<Info, RequestProto.line> {

   @Override
   @Named("info")
   public Info apply(RequestProto.line Line) {
   //pseudo code, make it better based on your request object
      if(infoId.isEmpty()) {
          return null;
      }
      Info info = new Info();
      info.setId(infoId);
      return info;
   }


问:
In a bitfiled structure does the controller read whole value or the particular byte
```<code>struct abc
{
    uint32 total;
    union
    {
        uint32 a:8;
        uint32 b:8;
        uint32 c:16;
    }
}
</code>```

If i update or read "abc.b" then controller will read whole 32bits and update particular byte or does it directly read the byte and update it?

答:
The C standard does not control how memory is accessed, except that declaring objects to be atomic imposes some constraints. Whether memory accesses of bytes, words, or other sizes are used to access bit-fields, or objects in general, is entirely dependent on the C implementation (primarily the compiler) and the target machine. If you have concerns about a particular system, you would need to identify it specifically, including the target hardware, the target operating system, and the C implementation being used.

If you have tried the code shown in the question and are not seeing the results you expect, it is likely because you have declared the bit-fields in a union instead of a struct. Declaring members in a union causes them to overlap in memory; uint32 a:8 and uint32 b:8 will refer to the same eight bits, and uint32 c:16 will overlap them. To lay them out separately, instead of overlapping, change union to struct.

Body:
struct abc
{
    uint32 total;
    union
    {
        uint32 a:8;
        uint32 b:8;
        uint32 c:16;
    }
}

If i update or read "abc.b" then controller will read whole 32bits and update particular byte or does it directly read the byte and update it?


问:
gphoto2 how to handle Out of Focus warning
Here is how I capture image with my camera

```<code>import logging
import gphoto2 as gp
def main():
    def callback(level, domain, string, data=None):
        print('Callback: level =', level, ', domain =', domain, ', string =', string)
        if data:
            print('Callback data:', data)

    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())

    camera = gp.Camera()
    camera.init()
    try:
        camera_file_path = gp.check_result(camera.capture(gp.GP_CAPTURE_IMAGE))
    except gp.GPhoto2Error as ex:
        print("callback: ", ex, ex.code, ex.message, ex.string)
    camera.exit()

if __name__ == "__main__" : exit(main())
</code>```

If the camera is not able to focus it generates following error

```<code>...
WARNING: gphoto2: (ptp_usb_getresp [usb.c:466]) PTP_OC 0x90c8 receiving resp failed: Out of Focus (0xa002)
WARNING: gphoto2: (camera_nikon_capture [library.c:3153]) 'ret' failed: 'Out of Focus' (0xa002)
WARNING: gphoto2: (gp_context_error) Out of Focus
WARNING: gphoto2: (gp_camera_capture [gphoto2-camera.c:1340]) 'camera->functions->capture (camera, type, path, context)' failed: -1
('callback: ', GPhoto2Error('[-1] Unspecified error',), -1, '[-1] Unspecified error', 'Unspecified error')
</code>```

The exception error code is -1 but how can I capture Out of Focus warning?

UPDATE

Filtered out unnecessary errors from logs

```<code>import logging
import gphoto2 as gp
from datetime import datetime
def main():
    def callback(level, domain, string, data=None):
        err_codes = ("(0x2005)", "(0x2019)")
        if not string.decode().endswith(err_codes):
            print("[{0}] {1}: {2}".format(datetime.utcnow(), domain.decode(), string.decode()))
        if data:
            print('Callback data:', data)

    callback_obj = gp.check_result(gp.gp_log_add_func(gp.GP_LOG_ERROR, callback))
    camera = gp.Camera()
    try:
        camera.init()
    except gp.GPhoto2Error as err:
        exit(err.code)

    try:
        camera_file_path = camera.capture(gp.GP_CAPTURE_IMAGE)
    except gp.GPhoto2Error as err:
        exit(err.code)
    camera.exit()

if __name__ == "__main__" : exit(main())
</code>```

答:
You've defined a callback function, in which you could parse the error string to detect out of focus, but you haven't installed your callback so libgphoto2 isn't using it. Use gp_log_add_func to install your callback.

Also, you're passing the return value of camera.capture to gp.check_result. This is incorrect as camera.capture already checks the result and raises an exception if there's an error.

Body:
Here is how I capture image with my camera

import logging
import gphoto2 as gp
def main():
    def callback(level, domain, string, data=None):
        print('Callback: level =', level, ', domain =', domain, ', string =', string)
        if data:
            print('Callback data:', data)

    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())

    camera = gp.Camera()
    camera.init()
    try:
        camera_file_path = gp.check_result(camera.capture(gp.GP_CAPTURE_IMAGE))
    except gp.GPhoto2Error as ex:
        print("callback: ", ex, ex.code, ex.message, ex.string)
    camera.exit()

if __name__ == "__main__" : exit(main())

If the camera is not able to focus it generates following error

...
WARNING: gphoto2: (ptp_usb_getresp [usb.c:466]) PTP_OC 0x90c8 receiving resp failed: Out of Focus (0xa002)
WARNING: gphoto2: (camera_nikon_capture [library.c:3153]) 'ret' failed: 'Out of Focus' (0xa002)
WARNING: gphoto2: (gp_context_error) Out of Focus
WARNING: gphoto2: (gp_camera_capture [gphoto2-camera.c:1340]) 'camera->functions->capture (camera, type, path, context)' failed: -1
('callback: ', GPhoto2Error('[-1] Unspecified error',), -1, '[-1] Unspecified error', 'Unspecified error')

The exception error code is -1 but how can I capture Out of Focus warning?

UPDATE

Filtered out unnecessary errors from logs

import logging
import gphoto2 as gp
from datetime import datetime
def main():
    def callback(level, domain, string, data=None):
        err_codes = ("(0x2005)", "(0x2019)")
        if not string.decode().endswith(err_codes):
            print("[{0}] {1}: {2}".format(datetime.utcnow(), domain.decode(), string.decode()))
        if data:
            print('Callback data:', data)

    callback_obj = gp.check_result(gp.gp_log_add_func(gp.GP_LOG_ERROR, callback))
    camera = gp.Camera()
    try:
        camera.init()
    except gp.GPhoto2Error as err:
        exit(err.code)

    try:
        camera_file_path = camera.capture(gp.GP_CAPTURE_IMAGE)
    except gp.GPhoto2Error as err:
        exit(err.code)
    camera.exit()

if __name__ == "__main__" : exit(main())


问:
Create file in Memory, add content and convert to Base64
There is a Web Service that is running in an external system. The Web Service expects an XML file which is Base64 encoded.

In my ABAP program, I have the XML that I want to post to the Web Service in a XSTRING variable.

The issue here is that the Base64 version of a string and a file which contains the the same string is inherently different.

The most direct solution that I know is to write the string to a file and then convert the file into Base64 and post it to the Web Service. The problem here is that the XML string that I have to too sensitive to be stored in the file system even temporarily.

So my question:

Is there a way to create a file during runtime in memory, add the XML that I have into that file in memory and finally convert it to a Base64 string, all during the runtime without ever using the actual file system.

```<code>DATA: lv_xstring TYPE xstring.
xstring = '<document>some xml data</document>'.
</code>```

xstring --> into a file in memory --> convert to a Base64 string

答:
You can directly convert string or xstring to base64 in ABAP. Check SCMS_BASE64_ENCODE_STR FM for xtsring to base64 string conversition.

On the other hand, generally binary data (xstring) transport as base64 encoded string in SOAP body. So may be you don't need to convert it to base64, just convert xml to xstring then assign it to method parameter.

Body:
There is a Web Service that is running in an external system. The Web Service expects an XML file which is Base64 encoded.

In my ABAP program, I have the XML that I want to post to the Web Service in a XSTRING variable.

The issue here is that the Base64 version of a string and a file which contains the the same string is inherently different.

The most direct solution that I know is to write the string to a file and then convert the file into Base64 and post it to the Web Service. The problem here is that the XML string that I have to too sensitive to be stored in the file system even temporarily.

So my question:

Is there a way to create a file during runtime in memory, add the XML that I have into that file in memory and finally convert it to a Base64 string, all during the runtime without ever using the actual file system.

DATA: lv_xstring TYPE xstring.
xstring = '<document>some xml data</document>'.

xstring --> into a file in memory --> convert to a Base64 string


问:
Is there a better way in C# to reserve long variable name?
```<code>var test = Class1.Subclass1.Subclass2.PropertyNameWhichIsBigName
</code>```

I have to use above in many places. How to avoid typing or save few key stroke? is there any shortcut in C#

答:
Yes, you can use Namespace aliases:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/using-namespaces

using ShortName = Class1.Subclass1.Subclass2;

And then

var test = ShortName.PropertyNameWhichIsBigName;

Body:
var test = Class1.Subclass1.Subclass2.PropertyNameWhichIsBigName

I have to use above in many places. How to avoid typing or save few key stroke? is there any shortcut in C#


问:
How to find a sum of even numbers in range recursively?
How can I write this function recursively?

```<code>def sum_even(n):
    total = 0
    for i in range(2, n+1,2):
        total = total + i
    return total
</code>```

I've tried to write it recursively but failed since I just took the lesson.

答:
You can do:

```<code>def sum_even(n):
    if n%2 == 1:
        n = n-1
    if n == 0:
        return 0
    return n + sum_even(n-2)
</code>```

Or,

```<code>def sum_even(n):
    if n%2 == 1:
        n = n-1
    return n + (n and sum_even(n-2))
</code>```

and checks the first expression, if it finds 0 or False it does not evaluate the second expression, if first value is non-zero, in other words, not False, it returns whatever the second expression is.

Body:
How can I write this function recursively?

def sum_even(n):
    total = 0
    for i in range(2, n+1,2):
        total = total + i
    return total

I've tried to write it recursively but failed since I just took the lesson.

Body:
You can do:

def sum_even(n):
    if n%2 == 1:
        n = n-1
    if n == 0:
        return 0
    return n + sum_even(n-2)

Or,

def sum_even(n):
    if n%2 == 1:
        n = n-1
    return n + (n and sum_even(n-2))

and checks the first expression, if it finds 0 or False it does not evaluate the second expression, if first value is non-zero, in other words, not False, it returns whatever the second expression is.


问:
Pass a variable into CURSOR's SELECT Query (MySQL)
I'm trying the stored procedure below. However, when i pass the actual column name in 'DECLARE cur1' line, the SP returns correct value but when I pass variable name i.e. input parameter (colName), it returns 0. I've added comments in my code below. Is the code correct?</p>

```<code>DROP PROCEDURE IF EXISTS test1.checkHardcodedField;
CREATE PROCEDURE test1.checkHardcodedField(IN textValue CHAR(10), colName CHAR(10), OUT counter VARCHAR(100))
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE temp CHAR(16);
  DECLARE i INT DEFAULT 0;

  -- Issue with this statement, returns incorrect value.
  DECLARE cur1 CURSOR FOR SELECT colName FROM data1;

  -- This statement works. MSH3 is actual column name
  -- DECLARE cur1 CURSOR FOR SELECT MSH3 FROM data1;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

  read_loop: LOOP
    FETCH cur1 INTO temp;

    IF done THEN
      LEAVE read_loop;
    END IF;
    IF temp = textValue THEN
      SET i = i + 1;
    END IF;
  END LOOP;

  SET counter = i;

  CLOSE cur1;
END;
</code>```

答:
```<code>CREATE PROCEDURE procedure_name (..., fieldname VARCHAR, ...)
BEGIN
    CREATE TEMPORARY TABLE tmp (field VARCHAR(10));
    SET @sql := CONCAT('INSERT INTO tmp SELECT ', fieldname, ' FROM tablename;');
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DROP PREPARE stmt;
    BEGIN
        DECLARE cur CURSOR FOR SELECT field FROM tmp;
        ...
    END;
    DROP TABLE tmp;
END
</code>```

Body:
I'm trying the stored procedure below. However, when i pass the actual column name in 'DECLARE cur1' line, the SP returns correct value but when I pass variable name i.e. input parameter (colName), it returns 0. I've added comments in my code below. Is the code correct?

DROP PROCEDURE IF EXISTS test1.checkHardcodedField;
CREATE PROCEDURE test1.checkHardcodedField(IN textValue CHAR(10), colName CHAR(10), OUT counter VARCHAR(100))
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE temp CHAR(16);
  DECLARE i INT DEFAULT 0;

  -- Issue with this statement, returns incorrect value.
  DECLARE cur1 CURSOR FOR SELECT colName FROM data1;

  -- This statement works. MSH3 is actual column name
  -- DECLARE cur1 CURSOR FOR SELECT MSH3 FROM data1;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

  read_loop: LOOP
    FETCH cur1 INTO temp;

    IF done THEN
      LEAVE read_loop;
    END IF;
    IF temp = textValue THEN
      SET i = i + 1;
    END IF;
  END LOOP;

  SET counter = i;

  CLOSE cur1;
END;


问:
Count for Member Posts in Ghost 3.x
Does anyone know how to get a total count for the number of posts that are for members.paid only in Ghost 3.x?

So far I have the following. But I cant seem to find the correct filter to only show the members.paid articles.

```<code>{{#get "posts" limit="all" }}
    {{posts.length}}
{{/get}}
</code>```

Thanks,

答:
Solution posted over on the Ghost forum:
https://forum.ghost.org/t/get-total-count-of-member-paid-posts/12117</p>

```<code>{{#get "posts" limit="all" filter="visibility:paid"}}
    {{posts.length}}
{{/get}}
</code>```

Title: Count for Member Posts in Ghost 3.x

Body:
Does anyone know how to get a total count for the number of posts that are for members.paid only in Ghost 3.x?

So far I have the following. But I cant seem to find the correct filter to only show the members.paid articles.

{{#get "posts" limit="all" }}
    {{posts.length}}
{{/get}}

Thanks,

Body:
Solution posted over on the Ghost forum:
https://forum.ghost.org/t/get-total-count-of-member-paid-posts/12117

{{#get "posts" limit="all" filter="visibility:paid"}}
    {{posts.length}}
{{/get}}


问:
How to input coordinates values from a multi-value hashmap into javafx point2d?
Currently, I am trying to create a heatmap using JavaFX, and I have stored the country name and its coordinates into a HashMap. My idea was to call the HashMap and get the coordinates value of the countries into Point2D. Such that I could maybe loop the line events = new Point2D[], rather than writing the new points individually. I'm not sure if my thoughts of coding are correct. However, there was an error (as shown in the code below).

The constructor Point2D(List) is undefined

How can I get the coordinates value in the HashMap and input into Point2D, rather then inserting the value itself into Point2D (as shown in the code below) ?

```<code>@Override public void init() {
    //Setting country coordinates on the map
    HashMap<String, List<Integer>> countryCoordinates = new HashMap<>();
    Integer[] coordinates = {};
    countryCoordinates.put("china", Arrays.asList(700, 180));
    countryCoordinates.put("Diamond Princess", Arrays.asList(810, 170));
    countryCoordinates.put("Singapore", Arrays.asList(726, 310));
    countryCoordinates.put("Japan", Arrays.asList(810, 170));
    countryCoordinates.put("Hong Kong", Arrays.asList(755, 225));
    countryCoordinates.put("Thailand", Arrays.asList(720, 250));
    .
    .
    .
    .
    pane = new StackPane();
    heatMap = new SimpleHeatMap(1000, 600, ColorMapping.LIME_YELLOW_RED, 40);
    heatMap.setOpacityDistribution(OpacityDistribution.EXPONENTIAL);
    heatMap.setHeatMapOpacity(1);
    events  = new Point2D[] {
        new Point2D(countryCoordinates.get("china")), //The constructor Point2D(List<Integer>) is undefined
        new Point2D(810, 170),
</code>```

答:
Assuming each list is size 2 (which appears to be true from the code you posted), all you would need to do to convert a single element of your map to a Point2D is extract the two elements from the list and pass them to the Point2D constructor:

```<code>List<Integer> chinaCoords = countryCoordinates.get("china");
Point2D chinaPoint = new Point2D(chinaCoords.get(0), chinaCoords.get(1));
</code>```

Since you're doing this repeatedly, instead of writing this code repeatedly, it's probably more convenient to define a utility method to do it:

```<code>private Point2D asPoint2D(List<Integer> coordList) {
    return new Point2D(coordList.get(0), coordList.get(1));
}
</code>```

And then the code in your init() method just looks like

```<code>events = new Point2D[] {
    asPoint2D(countryCoordinates.get("china")),
    ...
};
</code>```

More advanced (but cleaner) option:

If you're familiar with the Streams API and lambda expressions, you can even do this without defining an explicit function (or explicit loops, etc):

```<code>events = countryCoordinates().values().stream()
    .map(list -> new Point2D(list.get(0), list.get(1)))
    .collect(Collectors.toList())
    .toArray(new Point2D[countryCoordinates.size()]);
</code>```

Body:
Currently, I am trying to create a heatmap using JavaFX, and I have stored the country name and its coordinates into a HashMap. My idea was to call the HashMap and get the coordinates value of the countries into Point2D. Such that I could maybe loop the line events = new Point2D[], rather than writing the new points individually. I'm not sure if my thoughts of coding are correct. However, there was an error (as shown in the code below).

The constructor Point2D(List) is undefined

How can I get the coordinates value in the HashMap and input into Point2D, rather then inserting the value itself into Point2D (as shown in the code below) ?

@Override public void init() {
    //Setting country coordinates on the map
    HashMap<String, List<Integer>> countryCoordinates = new HashMap<>();
    Integer[] coordinates = {};
    countryCoordinates.put("china", Arrays.asList(700, 180));
    countryCoordinates.put("Diamond Princess", Arrays.asList(810, 170));
    countryCoordinates.put("Singapore", Arrays.asList(726, 310));
    countryCoordinates.put("Japan", Arrays.asList(810, 170));
    countryCoordinates.put("Hong Kong", Arrays.asList(755, 225));
    countryCoordinates.put("Thailand", Arrays.asList(720, 250));
    .
    .
    .
    .
    pane = new StackPane();
    heatMap = new SimpleHeatMap(1000, 600, ColorMapping.LIME_YELLOW_RED, 40);
    heatMap.setOpacityDistribution(OpacityDistribution.EXPONENTIAL);
    heatMap.setHeatMapOpacity(1);
    events  = new Point2D[] {
        new Point2D(countryCoordinates.get("china")), //The constructor Point2D(List<Integer>) is undefined
        new Point2D(810, 170),

Body:
Assuming each list is size 2 (which appears to be true from the code you posted), all you would need to do to convert a single element of your map to a Point2D is extract the two elements from the list and pass them to the Point2D constructor:

List<Integer> chinaCoords = countryCoordinates.get("china");
Point2D chinaPoint = new Point2D(chinaCoords.get(0), chinaCoords.get(1));

Since you're doing this repeatedly, instead of writing this code repeatedly, it's probably more convenient to define a utility method to do it:

private Point2D asPoint2D(List<Integer> coordList) {
    return new Point2D(coordList.get(0), coordList.get(1));
}

And then the code in your init() method just looks like

events = new Point2D[] {
    asPoint2D(countryCoordinates.get("china")),
    ...
};

More advanced (but cleaner) option:

If you're familiar with the Streams API and lambda expressions, you can even do this without defining an explicit function (or explicit loops, etc):

events = countryCoordinates().values().stream()
    .map(list -> new Point2D(list.get(0), list.get(1)))
    .collect(Collectors.toList())
    .toArray(new Point2D[countryCoordinates.size()]);


问:
When a variable goes out of scope does that mean it doesn't exist?
I'm not sure I understand scope - does an out-of-scope variable (I'm using Ruby) exist in memory somewhere or does it stop existing (I know you can't access it). Would it be inaccurate to say that an out-of-scope variable does not exist any more?

Maybe this is a philosophical question.

答: When it goes out of scope it still exists (in the sense that it has some memory allocated to it) for some time, until garbage collection cleans it up.    But as you imply, it's lost it's name and is unreachable.</p>

OwnerDisplayName: Mark

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Charlie Martin


答:
This is my solution, but i had to create a new hole data frame with random numbers:

```<code>ggplot()+
  geom_point(data=N,aes(x=Prob,y=AS))+
  scale_x_log10(breaks=c(0.1,1,5,20,50,80,95,99,99.9))+
  scale_y_log10(expand=c(0,0),
breaks=c(seq(0.01,0.1,0.01),seq(0.2,1,0.1),seq(2,10,1)))+
  ylab(paste("As(","\U00B5","g/l)"))+ xlab("Cummulative probability (%)")+
 theme_bw()+annotation_logticks()
</code>```

For the lines you should add segments and text in other layer for example.

Title: How can I make a graph like this in R?

Body:
I need to make a probability plot for a geochemical analysis (cumulative vs element concentration in log scale), like in the picture:

.

I have tried with ppPlot in the 'qualityTools' package with the 'log-normal' argument but for some elements it does not work. It says I need positive values for a log-normal distributions but they are all positive, I've checked. I think the command uses the 'density' function in base R, and its density model inadvertently produces negative concentration values.
The 'qqnorm' command in base R produces a different kind of plot.

How can I go around this?

Edit: Here's part of my magnesium data (I need to generate a similar graph with them):

    mg <- c(51.400, 149.000, 276.000, 135.000, 179.000,  81.000, 116.000,   8.150,   7.770,   7.870,   8.840,  15.600,  13.400,
  57.400,   7.440,  14.800,  40.800,  15.100,  21.400,   5.550,   3.390,  18.800,  20.100,  19.600,  11.600,  11.700,
  12.200,  12.500,  11.700,  12.100,  13.000,  12.300,  13.300,  13.200,  12.600,  29.700,  25.400,  21.000,  11.100,
  11.500,  11.000,  32.600,  17.500,  16.500,  18.100,  27.200,  21.200,  26.400,  18.800,  19.900,  32.000,  28.600,
  29.400,  30.700,   2.370,   2.070,   1.850,   1.970,  24.900,  19.100,  17.400,  23.100,  50.100,  48.800,  18.000,
   15.800,  27.100,  43.500,   4.820,  13.400,  14.600,  24.100,  22.700,  22.500,  43.500,  41.300,  43.700,  41.100,
    40.800,  63.700,   7.700,   8.360,  60.000,  58.400,  63.100,  65.100, 219.000,  25.800,   4.940,   3.670,  13.800,
   5.190,  14.700,  15.000,  13.100,  12.300,  10.700,  10.700,  11.100,  10.100,  10.600,  63.200,  19.800,  22.200,
  17.600,  11.500,  10.600,   9.380,   3.190,   9.180,  10.800, 189.000, 190.000, 152.000, 119.000, 194.000,  56.100)

Body:
This is my solution, but i had to create a new hole data frame with random numbers:

ggplot()+
  geom_point(data=N,aes(x=Prob,y=AS))+
  scale_x_log10(breaks=c(0.1,1,5,20,50,80,95,99,99.9))+
  scale_y_log10(expand=c(0,0),
breaks=c(seq(0.01,0.1,0.01),seq(0.2,1,0.1),seq(2,10,1)))+
  ylab(paste("As(","\U00B5","g/l)"))+ xlab("Cummulative probability (%)")+
 theme_bw()+annotation_logticks()

For the lines you should add segments and text in other layer for example.


问:
How do i create the rails 3.1 application using mysql
How to create a rails 3.1 application using mysql. The following command used to create the project with sqlite database.

```<code>rails new depot
</code>```

I'd like to use mysql then sqlite. So can anyone tell me how to create a project with mysql.

Thanks

答:
See help for rails new command

```<code>rails new --help
</code>```

-d, [--database=DATABASE]

Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db)
                              # Default: sqlite3

Body:
How to create a rails 3.1 application using mysql. The following command used to create the project with sqlite database.

rails new depot

I'd like to use mysql then sqlite. So can anyone tell me how to create a project with mysql.

Thanks

Body:
See help for rails new command

rails new --help

-d, [--database=DATABASE]

Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db)
                              # Default: sqlite3


问:
How do you insert images into table using Javascript?
I would like to insert images to "choicesDiv". How can I do so without editing HTML & CSS? Table code below:</p>

```<code><table id="choices">
  <tr>
    <td><div class="choicesDiv" value="1"></div></td>
    <td><div class="choicesDiv" value="2"></div></td>
    <td><div class="choicesDiv" value="3"></div></td>
    <td><div class="choicesDiv" value="4"></div></td>
    <td><div class="choicesDiv" value="5"></div></td>
  </tr>
  <tr>
    <td><div class="choicesDiv" value="6"></div></td>
    <td><div class="choicesDiv" value="7"></div></td>
    <td><div class="choicesDiv" value="8"></div></td>
    <td><div class="choicesDiv" value="9"></div></td>
    <td><div class="choicesDiv" value="10"></div></td>
  </tr>
</table>
</code>```

答:
$(document).ready(function(){
  $(".choicesDiv").append("" )
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="choices">
  <tr>
    <td><div class="choicesDiv" value="1"></div></td>
    <td><div class="choicesDiv" value="2"></div></td>
    <td><div class="choicesDiv" value="3"></div></td>
    <td><div class="choicesDiv" value="4"></div></td>
    <td><div class="choicesDiv" value="5"></div></td>
  </tr>
  <tr>
    <td><div class="choicesDiv" value="6"></div></td>
    <td><div class="choicesDiv" value="7"></div></td>
    <td><div class="choicesDiv" value="8"></div></td>
    <td><div class="choicesDiv" value="9"></div></td>
    <td><div class="choicesDiv" value="10"></div></td>
  </tr>
</table></code>```

Body:
$(document).ready(function(){
  $(".choicesDiv").append("<img src='your-image-src'/>" )
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="choices">
  <tr>
    <td><div class="choicesDiv" value="1"></div></td>
    <td><div class="choicesDiv" value="2"></div></td>
    <td><div class="choicesDiv" value="3"></div></td>
    <td><div class="choicesDiv" value="4"></div></td>
    <td><div class="choicesDiv" value="5"></div></td>
  </tr>
  <tr>
    <td><div class="choicesDiv" value="6"></div></td>
    <td><div class="choicesDiv" value="7"></div></td>
    <td><div class="choicesDiv" value="8"></div></td>
    <td><div class="choicesDiv" value="9"></div></td>
    <td><div class="choicesDiv" value="10"></div></td>
  </tr>
</table>


问:
In Intellij, right click on a test does not present a "Run" option
In IntelliJ when I right click on a test I dont see a "Run ClassX or MethodY" anymore. In fact there is no "run" window and when I right click I cannot run any class.

It was all working fine about 3 hours ago so I am not quite sure what has changed.

IntelliJ 10.5.1 (Licensed and NOT community edition)

Java 1.6.0_24

This happens for all projects.

Update 1

I installed IDEA 11 and imported settings from 10 and then saw that it was not a free upgrade close IDEA 11 and started using IDEA 10. I am fairly certain things stopped working from that point but not sure. Is that a problem? Can I somehow delete IntelliJ configuration directory somehow and restart?

Adding a screenshot when I don't get Run option on right click:

答:
In my case, my project is using Bazel.

The solution was to sync Bazel from Bazel plugin.


问:
I want a Report based of this 2 tables
```<code>   create table label_table(
   label_id number not null,
   label_name varchar2(50),
   no_months number not null,
   no_of_mobile_sims number not null,
   no_of_services number not null,
   delayed number not null,
   value_of_client number(6,2),
   constraint pk PRIMARY KEY(label_id)
   );

   create table client(
   customer_id number not null,
   customer_name varchar2(50) not null,
   no_months number not null,
   no_of_mobile_sims number not null,
   no_of_services number not null,
   delayed number not null,
  value_of_client number(6,2),
  constraint pk_key PRIMARY KEY(customer_id)
  ) ;

  SELECT
   l.label_id,
   l.label_name,
   k.customer_id,
   k.customer_name
   FROM
   label_table   l
   inner JOIN client k ON k.value_of_client>l.value_of_client
   ORDER BY 1;
</code>```

If we do a select * from client we have this output:

```<code>13 x_name        3                 4              2           0           74.38
</code>```

And if we do a select * from label_table we this output:

```<code>1 Diamond                  2                 2              2          0              70
2 Gold                     2                 1              2          2              50
</code>```

We have our client x_name who join our phone company let s say and i want to have a report where
it will say that x_name is a diamond client based on a comparison between the common columns of these 2 tables and i want an output like this:

13 x_name Diamond

And i want to this with a join but the problem is every time i try my client will be identified with both labels because he respect the conditions(>,<,!=,=) of both labels.
The idea is i have 16 clients that have different values and i want to put every one of them in a unique label not in more based on this 2 tables.
For example client.no_of_months>label.table.no_of_months,client.value_of_client>label.client.value_of_client then a label but how i said upper i need every client to be in his first choice label if a client is a diamond the output will be diamond not diamond,gold,silver,bronze even if he can be in that labels too.

答:
```<code>  SELECT
  k.customer_id,
  k.customer_name,
  l.label_name
  FROM
  label_table   l
  right JOIN client k ON k.value_of_client != l.value_of_client
where l.label_id=(case when k.value_of_client>(select value_of_client from label_table where label_id=1)
                   and  k.delayed=(select delayed from label_table where label_id=1)
                   and k.no_months >(select no_months from label_table where label_id=1)
                   and k.no_of_services>=(select no_of_services from label_table where label_id=1)
                   and k.no_of_mobile_sims>=(select no_of_mobile_sims from label_table where label_id=1)
                   then 1

                   when k.value_of_client > (select value_of_client from label_table where label_id=2)
                   and  k.delayed<(select delayed from label_table where label_id=2)
                   and k.no_months >=(select no_months from label_table where label_id=2)
                   and k.no_of_services>=(select no_of_services from label_table where label_id=2)
                   and k.no_of_mobile_sims>(select no_of_mobile_sims from label_table where label_id=2)
                   then 2

                   when k.value_of_client>(select value_of_client from label_table where label_id=3)
                   and  k.delayed<(select delayed from label_table where label_id=3)
                   and  k.no_months >(select no_months from label_table where label_id=3)
                   and  k.no_of_services>(select no_of_services from label_table where label_id=3)
                   and  k.no_of_mobile_sims>(select no_of_mobile_sims from label_table where label_id=3)
                   then 3
                   else 4
                   end)
ORDER BY 1;
</code>```

Title: I want a Report based of this 2 tables

Body:
   create table label_table(
   label_id number not null,
   label_name varchar2(50),
   no_months number not null,
   no_of_mobile_sims number not null,
   no_of_services number not null,
   delayed number not null,
   value_of_client number(6,2),
   constraint pk PRIMARY KEY(label_id)
   );

   create table client(
   customer_id number not null,
   customer_name varchar2(50) not null,
   no_months number not null,
   no_of_mobile_sims number not null,
   no_of_services number not null,
   delayed number not null,
  value_of_client number(6,2),
  constraint pk_key PRIMARY KEY(customer_id)
  ) ;

  SELECT
   l.label_id,
   l.label_name,
   k.customer_id,
   k.customer_name
   FROM
   label_table   l
   inner JOIN client k ON k.value_of_client>l.value_of_client
   ORDER BY 1;

If we do a select * from client we have this output:

13 x_name        3                 4              2           0           74.38

And if we do a select * from label_table we this output:

1 Diamond                  2                 2              2          0              70
2 Gold                     2                 1              2          2              50

We have our client x_name who join our phone company let s say and i want to have a report where
it will say that x_name is a diamond client based on a comparison between the common columns of these 2 tables and i want an output like this:

13 x_name Diamond

And i want to this with a join but the problem is every time i try my client will be identified with both labels because he respect the conditions(>,<,!=,=) of both labels.
The idea is i have 16 clients that have different values and i want to put every one of them in a unique label not in more based on this 2 tables.
For example client.no_of_months>label.table.no_of_months,client.value_of_client>label.client.value_of_client then a label but how i said upper i need every client to be in his first choice label if a client is a diamond the output will be diamond not diamond,gold,silver,bronze even if he can be in that labels too.


问:
CURL not working in Docker Image [Unable to access the host in Docker image]
Docker File

```<code># Start from the latest golang base image
FROM golang:latest

# Add Maintainer Info
LABEL maintainer="Sumit Thakur <sumitthakur@yahoo.com>"

# Set the Current Working Directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the Working Directory inside the container
COPY . .

# Build the Go app
RUN go build -o testapp myapplication.go testapp.go

# Expose port 50051 / for internal comunication

ENV PORT 50051
RUN echo $PORT

EXPOSE ${PORT}

# Command to run the executable
CMD ["./testapp"]
</code>```

Build Docker file with

```<code>docker build -t testapp  -f Dockerfile .
</code>```

that's perfect working

Run Docker file

```<code>docker run -d -p 50051:50051 testapp
</code>```

that's will also working fine

I check with the running container

docker ps
```

<p>this will give me</p>

<pre class="lang-sh prettyprint-override"><code>CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                      NAMES
57cd3c01bcda        testapp           "./testapp"       2 seconds ago       Up 2 seconds        0.0.0.0:50051->50051/tcp   gracious_bhaskara
</code>```

and when i check the network inspect with

docker network inspect bridge
```

<p>this will give me</p>

```[
    {
        "Name": "bridge",
        "Id": "30850a823d3040e7d8eaf804c122ce3d26b35650f6f792cf1f4ce77d66167eeb",
        "Created": "2020-02-19T07:34:24.993299775Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "57cd3c01bcda3fbf7d0bf67136ebbb8afb312c4f6ca70eeee15cda6e10fff4e2": {
                "Name": "gracious_bhaskara",
                "EndpointID": "2a42056609e8140d190f1efde41320138867d3905053e7f381bd91b1f053c251",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]
```

<p>Everthing works fine
Except when i trying to connect the docker host</p>

<pre class="lang-sh prettyprint-override"><code>curl -H "Content-type:application/json" -X GET 'https://localhost:50051/testapp/v1/order'
or
curl -H "Content-type:application/json" -X GET 'https://172.17.0.2:50051/testapp/v1/order'
</code>```

it gives me

Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 0.0.0.0...
* TCP_NODELAY set
* Connected to 0.0.0.0 (127.0.0.1) port 50051 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number
* stopped the pause stream!
* Closing connection 0
curl: (35) error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number
```

<p>Test openssl:</p>

```openssl s_client https://localhost:50051/testapp/v1/order -connect localhost:50051
```

<p>Result:</p>

```CONNECTED(00000005)
4488771180:error:140040E5:SSL routines:CONNECT_CR_SRVR_HELLO:ssl handshake failure:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22.200.4/l
ibressl-2.6/ssl/ssl_pkt.c:585:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 0 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Start Time: 1582109828
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
---
```

<p>Application Code</p>

```package main

import (
    "io"
    "net/http"
    "github.com/gorilla/handlers"
)
func main() {
    http.HandleFunc("/testapp/v1/order", testHandler)
    headersOk := handlers.AllowedHeaders([]string{""})
    http.ListenAndServe(":50051", headersOk)
}
func testHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Heyyy!")
}
```

Anyone Help I'm stuck here 1-2 days don't know what to do ?

答:
From inside the container, you need to listen on all interfaces, not localhost or the loopback interface. Networking is namespaced in docker, so you get not only a new private ip, but also a separate loopback interface inside the container that cannot be reached externally. To do this, change:

```<code>http.ListenAndServe("localhost:50051", headersOk)
</code>```

To:

```<code>http.ListenAndServe(":50051", headersOk)
</code>```

Body:
Docker File

# Start from the latest golang base image
FROM golang:latest

# Add Maintainer Info
LABEL maintainer="Sumit Thakur <sumitthakur@yahoo.com>"

# Set the Current Working Directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the Working Directory inside the container
COPY . .

# Build the Go app
RUN go build -o testapp myapplication.go testapp.go

# Expose port 50051 / for internal comunication

ENV PORT 50051
RUN echo $PORT

EXPOSE ${PORT}

# Command to run the executable
CMD ["./testapp"]

Build Docker file with

docker build -t testapp  -f Dockerfile .

that's perfect working

Run Docker file

docker run -d -p 50051:50051 testapp

that's will also working fine

I check with the running container

docker ps

this will give me

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                      NAMES
57cd3c01bcda        testapp           "./testapp"       2 seconds ago       Up 2 seconds        0.0.0.0:50051->50051/tcp   gracious_bhaskara

and when i check the network inspect with

docker network inspect bridge

this will give me

[
    {
        "Name": "bridge",
        "Id": "30850a823d3040e7d8eaf804c122ce3d26b35650f6f792cf1f4ce77d66167eeb",
        "Created": "2020-02-19T07:34:24.993299775Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "57cd3c01bcda3fbf7d0bf67136ebbb8afb312c4f6ca70eeee15cda6e10fff4e2": {
                "Name": "gracious_bhaskara",
                "EndpointID": "2a42056609e8140d190f1efde41320138867d3905053e7f381bd91b1f053c251",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]

Everthing works fine
Except when i trying to connect the docker host

curl -H "Content-type:application/json" -X GET 'https://localhost:50051/testapp/v1/order'
or
curl -H "Content-type:application/json" -X GET 'https://172.17.0.2:50051/testapp/v1/order'

it gives me

Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 0.0.0.0...
* TCP_NODELAY set
* Connected to 0.0.0.0 (127.0.0.1) port 50051 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number
* stopped the pause stream!
* Closing connection 0
curl: (35) error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number

Test openssl:

openssl s_client https://localhost:50051/testapp/v1/order -connect localhost:50051

Result:

CONNECTED(00000005)
4488771180:error:140040E5:SSL routines:CONNECT_CR_SRVR_HELLO:ssl handshake failure:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22.200.4/l
ibressl-2.6/ssl/ssl_pkt.c:585:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 0 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Start Time: 1582109828
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
---

Application Code

package main

import (
    "io"
    "net/http"
    "github.com/gorilla/handlers"
)
func main() {
    http.HandleFunc("/testapp/v1/order", testHandler)
    headersOk := handlers.AllowedHeaders([]string{""})
    http.ListenAndServe(":50051", headersOk)
}
func testHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Heyyy!")
}

Anyone Help I'm stuck here 1-2 days don't know what to do ?

Body:
From inside the container, you need to listen on all interfaces, not localhost or the loopback interface. Networking is namespaced in docker, so you get not only a new private ip, but also a separate loopback interface inside the container that cannot be reached externally. To do this, change:

http.ListenAndServe("localhost:50051", headersOk)

To:

http.ListenAndServe(":50051", headersOk)


问:
Angular project not getting past preloader, until hard reload
when i try redirecting to the home page, the url path changes but the preloader keeps loading and doesnt render the home page till i hard reload the page.
when i take out the preloader, it doesnt render the page also till i hard reload the page

My html file

```<code><div class="kt-grid__item">
                    <a (click)="home()" class="kt-login__logo">
                        <img src="./assets/media/logos/bbc.png" alt="">
                    </a>
                </div>
</code>```

my controller

```<code> home(){
            this.router.navigateByUrl('home');
        }
</code>```

答:
you can directly redirect your page with the anchor tag then why are you make a function like...

```<code><a class="nav-link" routerLink="/home" routerLinkActive="active">
            <i class="menu-icon mdi mdi-television"></i>
            <span class="menu-title">Home</span>
        </a>
</code>```

you have to give anchor tag like this.

or

if you want to make a function and wish to redirect from there then you have to give a correct route like...

```<code>home(){
        this.router.navigateByUrl('/home');
    }
</code>```

hope you get your answer.

Body:
when i try redirecting to the home page, the url path changes but the preloader keeps loading and doesnt render the home page till i hard reload the page.
when i take out the preloader, it doesnt render the page also till i hard reload the page

My html file

my controller

 home(){
            this.router.navigateByUrl('home');
        }

Body:
you can directly redirect your page with the anchor tag then why are you make a function like...

<a class="nav-link" routerLink="/home" routerLinkActive="active">
            <i class="menu-icon mdi mdi-television"></i>
            <span class="menu-title">Home</span>
        </a>

you have to give anchor tag like this.

or

if you want to make a function and wish to redirect from there then you have to give a correct route like...

home(){
        this.router.navigateByUrl('/home');
    }

hope you get your answer.