问:
Nancy Self-Host 404 Errors
I'm trying to build a simple Nancy self host. I got it working if I send in the proper path, but if I send empty path after port #, I get is error 404. If I send an invalid path I get error 500. What I want is to have a catch-all Get which is used whenever a request is sent with an invalid path.

Here is my program.cs

```<code>using System.Diagnostics;
using Nancy;
using Nancy.Hosting.Self;

namespace NancyDataService
{
    class Program
    {
        static void Main(string[] args)
        {
            var uri = new Uri("http://localhost:8080");
            var hostConfig = new HostConfiguration();
            hostConfig.UrlReservations.CreateAutomatically = true;
            hostConfig.RewriteLocalhost = false;
            using (var nancyHost = new NancyHost(uri, new DefaultNancyBootstrapper(), hostConfig))
            {
                nancyHost.Start();

                Console.WriteLine("Nancy now listening on http://localhost:8080. Press enter to stop");
                try
                {
                    Process.Start("http://localhost:8080");
                }
                catch (Exception)
                {
                }
                Console.ReadKey();
            }

            Console.WriteLine("Stopped. Good bye!");
        }
    }
}
</code>```

Here is my main module:

```<code>using Nancy;

namespace NancyDataService
{
    public class MainModule: NancyModule
    {
        public MainModule()
        {
            string json_error = @"{""status"":""fail"",""reason"":""{0}""}";
            string json;

            Get("test", parms =>
            {
                return "test";
            });

            // this is default if desired path not sent
            Get("{parm1}", parms =>
            {
                json = string.Format(json_error, "Invalid method name supplied");
                //return (Response)json;
                return json;
            });
        }
    }
}
</code>```

I've changed the Get syntax to match the Nancy 2.0 way. I was expecting that the last Get in the above code would be processed, and give me a default error message. If I enter http://localhost:8080/ in browser, I get error 404 response. If I enter http://localhost:8080/test it works fine. If I enter http://localhost:8080/anythingElse I get Error 500, Internal Server Error.

What I would like is to have a "default" get section so any unexpected path entered (including no path at all) after port #, it would take that branch.

BTW, this is targeting .Net Core 3.0, which Nancy says may not work. The warning in my Nancy.Hosting.Self package has a warning which says it was restored using .Net Framework (4.6.1 - 4.8). Could that be the issue?

Any ideas how to make that work? Thanks...

答: Solved most issues. Need Get("/", ... for empty path, and Get("/{parm}",... for bad path. Seems string.Format causes error 500 but json_error.Replace("{0}", "new text") works fine. What's up with that?

Title: Nancy Self-Host 404 Errors

Body:
I'm trying to build a simple Nancy self host. I got it working if I send in the proper path, but if I send empty path after port #, I get is error 404. If I send an invalid path I get error 500. What I want is to have a catch-all Get which is used whenever a request is sent with an invalid path.

Here is my program.cs

using System.Diagnostics;
using Nancy;
using Nancy.Hosting.Self;

namespace NancyDataService
{
    class Program
    {
        static void Main(string[] args)
        {
            var uri = new Uri("http://localhost:8080");
            var hostConfig = new HostConfiguration();
            hostConfig.UrlReservations.CreateAutomatically = true;
            hostConfig.RewriteLocalhost = false;
            using (var nancyHost = new NancyHost(uri, new DefaultNancyBootstrapper(), hostConfig))
            {
                nancyHost.Start();

                Console.WriteLine("Nancy now listening on http://localhost:8080. Press enter to stop");
                try
                {
                    Process.Start("http://localhost:8080");
                }
                catch (Exception)
                {
                }
                Console.ReadKey();
            }

            Console.WriteLine("Stopped. Good bye!");
        }
    }
}

Here is my main module:

using Nancy;

namespace NancyDataService
{
    public class MainModule: NancyModule
    {
        public MainModule()
        {
            string json_error = @"{""status"":""fail"",""reason"":""{0}""}";
            string json;

            Get("test", parms =>
            {
                return "test";
            });

            // this is default if desired path not sent
            Get("{parm1}", parms =>
            {
                json = string.Format(json_error, "Invalid method name supplied");
                //return (Response)json;
                return json;
            });
        }
    }
}

I've changed the Get syntax to match the Nancy 2.0 way. I was expecting that the last Get in the above code would be processed, and give me a default error message. If I enter http://localhost:8080/ in browser, I get error 404 response. If I enter http://localhost:8080/test it works fine. If I enter http://localhost:8080/anythingElse I get Error 500, Internal Server Error.

What I would like is to have a "default" get section so any unexpected path entered (including no path at all) after port #, it would take that branch.

BTW, this is targeting .Net Core 3.0, which Nancy says may not work. The warning in my Nancy.Hosting.Self package has a warning which says it was restored using .Net Framework (4.6.1 - 4.8). Could that be the issue?

Any ideas how to make that work? Thanks...


来源: stackexchange

问:
Scrolling 2 textview in same time with Android Studio
I wouldlike to scroll 2 textview in same time:

Code :

```<code>TextView text_A;
TextView text_B;

A=(TextView)findViewById(R.id.t1);
B=(TextView)findViewById(R.id.t2);

A.setMouvementMethod(new ScrollingMovementMethod());
B.setMouvementMethod(new ScrollingMovementMethod());
</code>```

How can I change this code for works ?

Thanks for your help !

答:
Clean Solution but it requires Api level 23.</p>

```<code> textView1.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->

                textView2.scrollX=scrollX
                textView2.scrollY=scrollY
            }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wouldlike to scroll 2 textview in same time:

Code :

TextView text_A;
TextView text_B;

A=(TextView)findViewById(R.id.t1);
B=(TextView)findViewById(R.id.t2);

A.setMouvementMethod(new ScrollingMovementMethod());
B.setMouvementMethod(new ScrollingMovementMethod());

How can I change this code for works ?

Thanks for your help !

Body:
Clean Solution but it requires Api level 23.

 textView1.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->

                textView2.scrollX=scrollX
                textView2.scrollY=scrollY
            }

ContentLicense: CC BY-SA 4.0


问:
Convert Pandas DF of Floats to Str, Keep trailing zeros
I am attempting to convert a DataFrame of Floats, to Strings, while keeping trailing zeros at the hundredth decimal point.  Here is my function:

```<code>def df_formatter(df):

    cols = df.columns

    for x in cols:
        for index,cell in enumerate(df[x]):
            df.loc[:,x][index] = str('{:.2f}'.format(Decimal(df[x][index])))

    return df
</code>```

The issue is that my dataframe is still in float format, even after applying the function. when i apply .astype(str) method to convert to strings, I lose the hundredth decimal point, if that hundredth decimal is a 0.  For example, 0.00 --> 0.0, or 0.50 --> 0.5.  This is currency and percentage data, so important to keep trailing zeros.

What is my issue?

答:
I am not sure if i understood correctly but I think this is a solution:

df = pd.DataFrame({'floats': [0.5, 0.66, 0.]})

df['floats'] = df['floats'].apply(lambda x: "{:.2f}".format(x))
print(df)

>>>
  floats
0   0.50
1   0.66
2   0.00
```

Body:
I am attempting to convert a DataFrame of Floats, to Strings, while keeping trailing zeros at the hundredth decimal point.  Here is my function:

def df_formatter(df):

    cols = df.columns

    for x in cols:
        for index,cell in enumerate(df[x]):
            df.loc[:,x][index] = str('{:.2f}'.format(Decimal(df[x][index])))

    return df

The issue is that my dataframe is still in float format, even after applying the function. when i apply .astype(str) method to convert to strings, I lose the hundredth decimal point, if that hundredth decimal is a 0.  For example, 0.00 --> 0.0, or 0.50 --> 0.5.  This is currency and percentage data, so important to keep trailing zeros.

What is my issue?


问:
RecyclerView cannot be found
I just started to try to use the RecyclerView. I added some lines into the build.grandle but I always get many error messages telling me:
' error: cannot find symbol'
' error: package androidx.recyclerview.widget does not exist'
and I do not understand why I am getting these error messages. Here you see the code of my grandle:

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

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.td.barapp"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        viewBinding {
            enabled = true
        }

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.0.0'
    implementation 'com.android.support:cardview-v7:27.0.0'
}
</code>```

I'd appreciate every comment and would be quite thankful.

Update: I think I have a problem with AndroidX. I migrated to it by using Refactor-->Migrate to AndroidX in Android studio but I do not know how I should change my posted grandle.build file. At the moment in my grandle file I have some libararies like " implementation 'com.android.support:design:27.1.1' and I get the warning and error message: "This support library should not use a different version (27) than the compileSdkVersion (28) " But when I use " implementation 'com.android.support:appcompat-v7:28.0'" I also get an error message :"All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.1.1, 27.0.0. Examples include com.android.support:animated-vector-drawable..

Here you see a screenshot of the marked lines in the Build grandle file: How do I have to change these lines in order to use AndroidX? I'd be happy for your help because I am stuck on that problem.

答:
Possibly you have an issue in your layout file, try to remove the widget and add again just type 'recyclerview' and android studio will complete the reference for you.

You can use this quick-setting available in android studio, it will migrate your project to AndroidX automatically --

Title: RecyclerView cannot be found

Body:
I just started to try to use the RecyclerView. I added some lines into the build.grandle but I always get many error messages telling me:
' error: cannot find symbol'
' error: package androidx.recyclerview.widget does not exist'
and I do not understand why I am getting these error messages. Here you see the code of my grandle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.td.barapp"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        viewBinding {
            enabled = true
        }

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.0.0'
    implementation 'com.android.support:cardview-v7:27.0.0'
}

I'd appreciate every comment and would be quite thankful.

Update: I think I have a problem with AndroidX. I migrated to it by using Refactor-->Migrate to AndroidX in Android studio but I do not know how I should change my posted grandle.build file. At the moment in my grandle file I have some libararies like " implementation 'com.android.support:design:27.1.1' and I get the warning and error message: "This support library should not use a different version (27) than the compileSdkVersion (28) " But when I use " implementation 'com.android.support:appcompat-v7:28.0'" I also get an error message :"All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.1.1, 27.0.0. Examples include com.android.support:animated-vector-drawable..

Here you see a screenshot of the marked lines in the Build grandle file: How do I have to change these lines in order to use AndroidX? I'd be happy for your help because I am stuck on that problem.


问:
How can I implement this more efficiently
So I have a function (I'm writing this in a pseudo-functional language, I hope its clear):

```<code>dampen (lr : Num, x : Num) = x + lr*(1-x)
</code>```

And I wish to apply this n times to a value x.  I could implement it recursively:

```<code>dampenN (0, lr, x) = dampen(lr, x)
dampenN (n, lr, x) = dampenN(n-1, lr, dampen(x))
</code>```

But there must be a way I can do it mathematically without resorting to an iterative procedure (recursive, or a loop).

Unfortunately my algebra skills are rusty beyond belief, can anyone help?

答:
```<code>x + lr*(1-x)
= x + lr - lr*x
= x*(1-lr)+lr
</code>```

applying it twice gives

```<code>(x*(1-lr)+lr)*(1-lr)+lr
= x*(1-lr)^2 + lr*(1-lr) + lr
</code>```

and three times

```<code>(x*(1-lr)+lr)*(1-lr)^2 + lr*(1-lr) + lr
= x*(1-lr)^3 + lr*(1-lr)^2 + lr*(1-lr) + lr
</code>```

or in general, n times gives

```<code>x*(1-lr)^n + lr * ( (1-lr)^n + (1-lr)^(n-1)...+(1-lr) +1)
</code>```

Does that help?

OwnerDisplayName: sanity

ContentLicense: CC BY-SA 2.5

Body:
So I have a function (I'm writing this in a pseudo-functional language, I hope its clear):

dampen (lr : Num, x : Num) = x + lr*(1-x)

And I wish to apply this n times to a value x.  I could implement it recursively:

dampenN (0, lr, x) = dampen(lr, x)
dampenN (n, lr, x) = dampenN(n-1, lr, dampen(x))

But there must be a way I can do it mathematically without resorting to an iterative procedure (recursive, or a loop).

Unfortunately my algebra skills are rusty beyond belief, can anyone help?

Body:
x + lr*(1-x)
= x + lr - lr*x
= x*(1-lr)+lr

applying it twice gives

(x*(1-lr)+lr)*(1-lr)+lr
= x*(1-lr)^2 + lr*(1-lr) + lr

and three times

(x*(1-lr)+lr)*(1-lr)^2 + lr*(1-lr) + lr
= x*(1-lr)^3 + lr*(1-lr)^2 + lr*(1-lr) + lr

or in general, n times gives

x*(1-lr)^n + lr * ( (1-lr)^n + (1-lr)^(n-1)...+(1-lr) +1)

Does that help?

OwnerDisplayName: MarkusQ

LastEditorDisplayName: strager


问:
Is it possible to read php code from other sites?
Just a curious question. I was wondering is it possible to read a sites php/server side codes? Is there any software/method that can be used to do so? Sometimes for educational purposes, i really want to see how people form the backend infrastructure of their sites. </p>

答: No. PHP is only server-side, and the source is not passed to client.</p>


问:
generate two git patch files simultaneously without conflicts
My colleague and I both work on the same latest version of a branch and we are developing
two totally isolated features, in other words, there would no any conflict/overlapping between his change and mine.

Once we both complete our features and generate the patch file against the latest version of the branch individually.  We both handed our patches to another colleague and he also has the latest version of the latest branch. Could I assume that the colleague could just apply two patches in any order/way successfully?

In other words, we don't have to rebase/merge each other's change before we make the patch file if we know those changes could not cause any conflicts. Is that correct?

Thank you.

答:
If it's as you say and they're truly independent changes, they should apply without conflicts.

The two things which are likely to cause conflicts are when both patches add to the end of a file. Or when they both add text to the same point in the file, like adding code between the same two functions.

To ensure the best chance of success, the integrating colleague should make a separate branch for each of your patches and merge them in turn.

If there are conflicts, handle them as any other conflicts.

Simpler is to make your repository available as a remote. This can be as simple as providing them with an ssh login and path to your repository. See Setting Up the Server in Pro Git. You can also use this to establish a central repository everyone pushes and pulls from so you don't have to send patches around.


问:
How to transform list with in a list using jolt library
I am trying to transform a JSON into another using Jolt library and not getting the desired output.

Here is my input file.

{
  "maxResults": 150,
  "total": 89,
  "issues": [
    {
      "key": "1",
      "fields": {
        "fixVersions": [
          {
            "self": "FIX1-01",
            "id": "11"
          },
          {
            "self": "FIX1-02",
            "id": "12"
          }
        ]
      }
    },
    {
      "key": "2",
      "fields": {
        "fixVersions": [
          {
            "self": "FIX2-01",
            "id": "21"
          }
        ]
      }
    },
    {
      "key": "3",
      "fields": {
        "fixVersions": []
      }
    }
  ]
}
```
<p>and this is the spec file I am using for transformation.</p>
<pre class="lang-json prettyprint-override"><code>
[
  {
    "operation": "shift",
    "spec": {
      "issues": {
        "*": {
          "key": "[&1].id",
          "fields": {
            "fixVersions": {
              "*": {
                "self": "[&1].fixVersion.name"
              }
            }
          }
        }
      }
    }
  }
]
</code>```

And I am getting this output

[
  {
    "id": "1",
    "fixVersion": {
      "name": [
        "FIX1-01",
        "FIX2-01"
      ]
    }
  },
  {
    "fixVersion": {
      "name": "FIX1-02"
    },
    "id": "2"
  },
  {
    "id": "3"
  }
]
```
<p>Its not right. What it is doing is it is getting first self field value of each issue and populating it as a array in first fixVersions of the output and getting second self field value and populating it in the second fixVersions. What I want to do is keep the structure as it is in input just change self field name like this.</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "id": "1",
    "fixVersion": [
      {
        "name": "FIX1-01"
      },
      {
        "name": "FIX1-02"
      }
    ]
  },
  {
    "fixVersion": [
      {
        "name": "FIX2-01"
      }
    ],
    "id": "2"
  },
  {
    "id": "3"
  }
]
</code>```

What am I doing wrong?

答:
See if this spec is what you are looking for:

[
  {
    "operation": "shift",
    "spec": {
      "issues": {
        "*": {
          "key": "[&1].id",
          "fields": {
            "fixVersions": {
              "*": {
                "self": "[&4].fixVersion[&1].name"
              }
            }
          }
        }
      }
    }
  }
]
```
<p>Output using it against your input would result into:</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "id": "1",
    "fixVersion": [
      {
        "name": "FIX1-01"
      },
      {
        "name": "FIX1-02"
      }
    ]
  },
  {
    "id": "2",
    "fixVersion": [
      {
        "name": "FIX2-01"
      }
    ]
  },
  {
    "id": "3"
  }
]
</code>```

Please note the change on the indexes you are using to rebuild the fixVersion (needs to take into account whe issues index as well) list, you were missing this:

```<code>[&4].fixVersion[&1].name
</code>```

Body:
I am trying to transform a JSON into another using Jolt library and not getting the desired output.

Here is my input file.

{
  "maxResults": 150,
  "total": 89,
  "issues": [
    {
      "key": "1",
      "fields": {
        "fixVersions": [
          {
            "self": "FIX1-01",
            "id": "11"
          },
          {
            "self": "FIX1-02",
            "id": "12"
          }
        ]
      }
    },
    {
      "key": "2",
      "fields": {
        "fixVersions": [
          {
            "self": "FIX2-01",
            "id": "21"
          }
        ]
      }
    },
    {
      "key": "3",
      "fields": {
        "fixVersions": []
      }
    }
  ]
}

and this is the spec file I am using for transformation.

[
  {
    "operation": "shift",
    "spec": {
      "issues": {
        "*": {
          "key": "[&1].id",
          "fields": {
            "fixVersions": {
              "*": {
                "self": "[&1].fixVersion.name"
              }
            }
          }
        }
      }
    }
  }
]

And I am getting this output

[
  {
    "id": "1",
    "fixVersion": {
      "name": [
        "FIX1-01",
        "FIX2-01"
      ]
    }
  },
  {
    "fixVersion": {
      "name": "FIX1-02"
    },
    "id": "2"
  },
  {
    "id": "3"
  }
]

Its not right. What it is doing is it is getting first self field value of each issue and populating it as a array in first fixVersions of the output and getting second self field value and populating it in the second fixVersions. What I want to do is keep the structure as it is in input just change self field name like this.

[
  {
    "id": "1",
    "fixVersion": [
      {
        "name": "FIX1-01"
      },
      {
        "name": "FIX1-02"
      }
    ]
  },
  {
    "fixVersion": [
      {
        "name": "FIX2-01"
      }
    ],
    "id": "2"
  },
  {
    "id": "3"
  }
]

What am I doing wrong?

Body:
See if this spec is what you are looking for:

[
  {
    "operation": "shift",
    "spec": {
      "issues": {
        "*": {
          "key": "[&1].id",
          "fields": {
            "fixVersions": {
              "*": {
                "self": "[&4].fixVersion[&1].name"
              }
            }
          }
        }
      }
    }
  }
]

Output using it against your input would result into:

[
  {
    "id": "1",
    "fixVersion": [
      {
        "name": "FIX1-01"
      },
      {
        "name": "FIX1-02"
      }
    ]
  },
  {
    "id": "2",
    "fixVersion": [
      {
        "name": "FIX2-01"
      }
    ]
  },
  {
    "id": "3"
  }
]

Please note the change on the indexes you are using to rebuild the fixVersion (needs to take into account whe issues index as well) list, you were missing this:

[&4].fixVersion[&1].name


问:
Converting SQL command from vb .net to C#
I am trying to analyze SQL command text in vb.net and integrate it to be compatible with C#.

I am having issues converting SQL command text from vb.net to c#.

I used Telerik: http://converter.telerik.com/

and got these results (shown below). I was wondering if someone who is familiar with both VB.NET and C# could help me re-write the full SQL command text.

Original vb.net command text:

```<code>Dim r As SqlDataReader = sqlCommand.ExecuteReader()

Do While True
    If r.Read() Then
         SQL2 = "SELECT * from Invoices "
         SQL2 = SQL2 & " WHERE Num = '" & r("Num") & "'"

         conPubs2 = New SqlConnection(<ConnectionString>)
         sqlCommand2 = New SqlCommand(SQL2, conPubs2)
         conPubs2.Open()

         Dim r2 As SqlDataReader = sqlCommand2.ExecuteReader()

         Do While True
             If r2.Read() Then
                 MsgBox(RTrim(r("Num")) & ": " & RTrim(r2("ItemID")))
             Else
                 Exit Do
             End If
         Loop

    Else
        Exit Do
    End If
Loop

conPubs.Close()
conPubs2.Close()

End Sub
</code>```

Here's what I got in C# when I used Telerik's online converter:

```<code>SqlDataReader r = sqlCommand.ExecuteReader();

while (true)
{
    if (r.Read())
    {
        SQL2 = "SELECT * from Invoices ";
        SQL2 = SQL2 + " WHERE Num = '" + r("Num") + "'";
</code>```

/* Cannot convert AssignmentStatementSyntax, CONVERSION ERROR: Conversion for XmlElement not implemented, please report this issue in ')

  sql...' at character 314

at ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.NodesVisitor.DefaultVisit(SyntaxNode node)

  at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.VisitXmlElement(XmlElementSyntax node)

  at Microsoft.CodeAnalysis.VisualBasic.Syntax.XmlElementSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)

  at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.Visit(SyntaxNode node)

  at ICSharpCode.CodeConverter.CSharp.CommentConvertingNodesVisitor.DefaultVisit(SyntaxNode node)

  at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.VisitXmlElement(XmlElementSyntax node)

  at Microsoft.CodeAnalysis.VisualBasic.Syntax.XmlElementSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)

  at  ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.NodesVisitor.VisitSimpleArgument(SimpleArgumentSyntax node)

  at Microsoft.CodeAnalysis.VisualBasic.Syntax.SimpleArgumentSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)

  at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.Visit(SyntaxNode node)

  at ICSharpCode.CodeConverter.CSharp.CommentConvertingNodesVisitor.DefaultVisit(SyntaxNode node)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.VisitSimpleArgument(SimpleArgumentSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.SimpleArgumentSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.NodesVisitor.<>c__DisplayClass83_0.<ConvertArguments>b__0(ArgumentSyntax a, Int32 i)
     at System.Linq.Enumerable.<SelectIterator>d__52.MoveNext()
     at System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext()
     at Microsoft.CodeAnalysis.CSharp.SyntaxFactory.SeparatedList[TNode](IEnumerable1 nodes)
     at ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.NodesVisitor.VisitArgumentList(ArgumentListSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.ArgumentListSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.Visit(SyntaxNode node)
     at ICSharpCode.CodeConverter.CSharp.CommentConvertingNodesVisitor.DefaultVisit(SyntaxNode node)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.VisitArgumentList(ArgumentListSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.ArgumentListSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.NodesVisitor.VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.ObjectCreationExpressionSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.Visit(SyntaxNode node)
     at ICSharpCode.CodeConverter.CSharp.CommentConvertingNodesVisitor.DefaultVisit(SyntaxNode node)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.ObjectCreationExpressionSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.MethodBodyVisitor.VisitAssignmentStatement(AssignmentStatementSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.AssignmentStatementSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.Visit(SyntaxNode node)
     at ICSharpCode.CodeConverter.CSharp.CommentConvertingMethodBodyVisitor.ConvertWithTrivia(SyntaxNode node)
     at ICSharpCode.CodeConverter.CSharp.CommentConvertingMethodBodyVisitor.DefaultVisit(SyntaxNode node)

I am trying ultimately, to expand on a different query that has the following command text; the reason why is I need to expand upon it is to be able to count the total number of lines associated with the Num (lines returned, e.g. if more than 1):

```<code>dbConnection.Open();
var sqlCmd = dbConnection.CreateCommand();
sqlCmd.CommandText = @"SELECT [ItemID], [Num]
                       FROM [Test].[dbo].[Invoices]
                       WHERE Num = '" + orderNumber.ToString() + "'";
</code>```

答:
OK as for the first part concerning conversion, first of all, you did not copy the whole code of VB.Net, it was missing many parts IN ORDER TO be correctly converted to C# code, I did some implementations and converted it in the same website you used.
The VB.Net [As it should be], it doesn't mean that is written in a correct way or won't generate errors.

```<code>Sub Hello()
        Dim conPubs As SqlClient.SqlConnection = New SqlClient.SqlConnection With {.ConnectionString = "Your_ConnectionString"}
        conPubs.Open()
        Dim ThisCommand1 As New SqlClient.SqlCommand 'This line was missing from the example you copied this from.
        Dim r As SqlClient.SqlDataReader = ThisCommand1.ExecuteReader
        Do While True
            If r.Read() Then
                Dim SQL2 As String = "SELECT * from Invoices WHERE Num = '" & r("Num") & "'"
                Dim conPubs2 = New SqlClient.SqlConnection("")
                Dim sqlCommand2 = New SqlClient.SqlCommand(SQL2, conPubs2)
                conPubs2.Open()
                Dim r2 As SqlClient.SqlDataReader = sqlCommand2.ExecuteReader()
                Do While True
                    If r2.Read() Then
                        MsgBox(RTrim(r("Num")) & ": " & RTrim(r2("ItemID")))
                    Else
                        Exit Do
                    End If
                Loop
                conPubs2.Close()       'Is a second SqlServer Connection
            Else
                Exit Do
            End If
        Loop
        conPubs.Close()      'Is SqlServer Connection
    End Sub
</code>```

The Conversion to C# :

```<code>public void Hello()
{
    SqlClient.SqlConnection conPubs = new SqlClient.SqlConnection() { ConnectionString = "Your_ConnectionString" };
    conPubs.Open();
    SqlClient.SqlCommand ThisCommand1 = new SqlClient.SqlCommand(); // This line was missing from the example you copied this from.
    SqlClient.SqlDataReader r = ThisCommand1.ExecuteReader;
    while (true)
    {
        if (r.Read())
        {
            string SQL2 = "SELECT * from Invoices WHERE Num = '" + r("Num") + "'";
            var conPubs2 = new SqlClient.SqlConnection("");
            var sqlCommand2 = new SqlClient.SqlCommand(SQL2, conPubs2);
            conPubs2.Open();
            SqlClient.SqlDataReader r2 = sqlCommand2.ExecuteReader();
            while (true)
            {
                if (r2.Read())
                    MsgBox(RTrim(r("Num")) + ": " + RTrim(r2("ItemID")));
                else
                    break;
            }
            conPubs2.Close();       // Is a second SqlServer Connection
        }
        else
            break;
    }
    conPubs.Close();      // Is SqlServer Connection
}
</code>```

Again, note :

This answers to your conversion issues, but doesn't mean that VB .Net
  code is not going to generate Errors.

In VB.Net :

VB.Net code needs to be re-written.

Consider using [Using ... End Using] method with Database Connection.

Body:
I am trying to analyze SQL command text in vb.net and integrate it to be compatible with C#.

I am having issues converting SQL command text from vb.net to c#.

I used Telerik: http://converter.telerik.com/

and got these results (shown below). I was wondering if someone who is familiar with both VB.NET and C# could help me re-write the full SQL command text.

Original vb.net command text:

Dim r As SqlDataReader = sqlCommand.ExecuteReader()

Do While True
    If r.Read() Then
         SQL2 = "SELECT * from Invoices "
         SQL2 = SQL2 & " WHERE Num = '" & r("Num") & "'"

         conPubs2 = New SqlConnection(<ConnectionString>)
         sqlCommand2 = New SqlCommand(SQL2, conPubs2)
         conPubs2.Open()

         Dim r2 As SqlDataReader = sqlCommand2.ExecuteReader()

         Do While True
             If r2.Read() Then
                 MsgBox(RTrim(r("Num")) & ": " & RTrim(r2("ItemID")))
             Else
                 Exit Do
             End If
         Loop

    Else
        Exit Do
    End If
Loop

conPubs.Close()
conPubs2.Close()

End Sub

Here's what I got in C# when I used Telerik's online converter:

SqlDataReader r = sqlCommand.ExecuteReader();

while (true)
{
    if (r.Read())
    {
        SQL2 = "SELECT * from Invoices ";
        SQL2 = SQL2 + " WHERE Num = '" + r("Num") + "'";

/* Cannot convert AssignmentStatementSyntax, CONVERSION ERROR: Conversion for XmlElement not implemented, please report this issue in ')

  sql...' at character 314

at ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.NodesVisitor.DefaultVisit(SyntaxNode node)

  at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.VisitXmlElement(XmlElementSyntax node)

  at Microsoft.CodeAnalysis.VisualBasic.Syntax.XmlElementSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)

  at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.Visit(SyntaxNode node)

  at ICSharpCode.CodeConverter.CSharp.CommentConvertingNodesVisitor.DefaultVisit(SyntaxNode node)

  at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.VisitXmlElement(XmlElementSyntax node)

  at Microsoft.CodeAnalysis.VisualBasic.Syntax.XmlElementSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)

  at  ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.NodesVisitor.VisitSimpleArgument(SimpleArgumentSyntax node)

  at Microsoft.CodeAnalysis.VisualBasic.Syntax.SimpleArgumentSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)

  at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.Visit(SyntaxNode node)

  at ICSharpCode.CodeConverter.CSharp.CommentConvertingNodesVisitor.DefaultVisit(SyntaxNode node)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.VisitSimpleArgument(SimpleArgumentSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.SimpleArgumentSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.NodesVisitor.<>c__DisplayClass83_0.<ConvertArguments>b__0(ArgumentSyntax a, Int32 i)
     at System.Linq.Enumerable.<SelectIterator>d__52.MoveNext()
     at System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext()
     at Microsoft.CodeAnalysis.CSharp.SyntaxFactory.SeparatedList[TNode](IEnumerable1 nodes)
     at ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.NodesVisitor.VisitArgumentList(ArgumentListSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.ArgumentListSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.Visit(SyntaxNode node)
     at ICSharpCode.CodeConverter.CSharp.CommentConvertingNodesVisitor.DefaultVisit(SyntaxNode node)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.VisitArgumentList(ArgumentListSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.ArgumentListSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.NodesVisitor.VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.ObjectCreationExpressionSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.Visit(SyntaxNode node)
     at ICSharpCode.CodeConverter.CSharp.CommentConvertingNodesVisitor.DefaultVisit(SyntaxNode node)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.ObjectCreationExpressionSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at ICSharpCode.CodeConverter.CSharp.VisualBasicConverter.MethodBodyVisitor.VisitAssignmentStatement(AssignmentStatementSyntax node)
     at Microsoft.CodeAnalysis.VisualBasic.Syntax.AssignmentStatementSyntax.Accept[TResult](VisualBasicSyntaxVisitor1 visitor)
     at Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxVisitor1.Visit(SyntaxNode node)
     at ICSharpCode.CodeConverter.CSharp.CommentConvertingMethodBodyVisitor.ConvertWithTrivia(SyntaxNode node)
     at ICSharpCode.CodeConverter.CSharp.CommentConvertingMethodBodyVisitor.DefaultVisit(SyntaxNode node)

I am trying ultimately, to expand on a different query that has the following command text; the reason why is I need to expand upon it is to be able to count the total number of lines associated with the Num (lines returned, e.g. if more than 1):

dbConnection.Open();
var sqlCmd = dbConnection.CreateCommand();
sqlCmd.CommandText = @"SELECT [ItemID], [Num]
                       FROM [Test].[dbo].[Invoices]
                       WHERE Num = '" + orderNumber.ToString() + "'";

Body:
OK as for the first part concerning conversion, first of all, you did not copy the whole code of VB.Net, it was missing many parts IN ORDER TO be correctly converted to C# code, I did some implementations and converted it in the same website you used.
The VB.Net [As it should be], it doesn't mean that is written in a correct way or won't generate errors.

Sub Hello()
        Dim conPubs As SqlClient.SqlConnection = New SqlClient.SqlConnection With {.ConnectionString = "Your_ConnectionString"}
        conPubs.Open()
        Dim ThisCommand1 As New SqlClient.SqlCommand 'This line was missing from the example you copied this from.
        Dim r As SqlClient.SqlDataReader = ThisCommand1.ExecuteReader
        Do While True
            If r.Read() Then
                Dim SQL2 As String = "SELECT * from Invoices WHERE Num = '" & r("Num") & "'"
                Dim conPubs2 = New SqlClient.SqlConnection("")
                Dim sqlCommand2 = New SqlClient.SqlCommand(SQL2, conPubs2)
                conPubs2.Open()
                Dim r2 As SqlClient.SqlDataReader = sqlCommand2.ExecuteReader()
                Do While True
                    If r2.Read() Then
                        MsgBox(RTrim(r("Num")) & ": " & RTrim(r2("ItemID")))
                    Else
                        Exit Do
                    End If
                Loop
                conPubs2.Close()       'Is a second SqlServer Connection
            Else
                Exit Do
            End If
        Loop
        conPubs.Close()      'Is SqlServer Connection
    End Sub

The Conversion to C# :

public void Hello()
{
    SqlClient.SqlConnection conPubs = new SqlClient.SqlConnection() { ConnectionString = "Your_ConnectionString" };
    conPubs.Open();
    SqlClient.SqlCommand ThisCommand1 = new SqlClient.SqlCommand(); // This line was missing from the example you copied this from.
    SqlClient.SqlDataReader r = ThisCommand1.ExecuteReader;
    while (true)
    {
        if (r.Read())
        {
            string SQL2 = "SELECT * from Invoices WHERE Num = '" + r("Num") + "'";
            var conPubs2 = new SqlClient.SqlConnection("");
            var sqlCommand2 = new SqlClient.SqlCommand(SQL2, conPubs2);
            conPubs2.Open();
            SqlClient.SqlDataReader r2 = sqlCommand2.ExecuteReader();
            while (true)
            {
                if (r2.Read())
                    MsgBox(RTrim(r("Num")) + ": " + RTrim(r2("ItemID")));
                else
                    break;
            }
            conPubs2.Close();       // Is a second SqlServer Connection
        }
        else
            break;
    }
    conPubs.Close();      // Is SqlServer Connection
}

Again, note :

This answers to your conversion issues, but doesn't mean that VB .Net
  code is not going to generate Errors.

In VB.Net :

VB.Net code needs to be re-written.

Consider using [Using ... End Using] method with Database Connection.


问:
mySQL UPDATE table based on SELECT (count) of a different table
I have a table of classes, and a table of subjects.

```
CLASS
|class_id|class_name|subject_id|date_time|
------------------------------------------
(imagine some rows here)

SUBJECT
|subject_id|subject_name|current_class_count|
---------------------------------------------
(imagine some rows here)
```

For indexing purposes I'd like to update the list of subjects every hour with the list of classes which have a date_time greater than right now.

I can do a select statement like this:

```
SELECT count(*) AS num, subject_id
FROM class
GROUP BY subject_id
where date_time > NOW()
```

and I will get something like

```
RESULT
|num|subject_id|
----------------
| 8 |        1 |
| 6 |        2 |
| 9 |        3 |
----------------
```

What's the most efficient way to get the subject table updated with the current_class_count? I could do this with PHP by looping through and doing several update statements, but I think mySql should have an easier way.

答:
Edit:  How about this:

```
UPDATE SUBJECT
LEFT JOIN (
SELECT count(*) AS num, subject_id
FROM class
GROUP BY subject_id
where date_time > NOW()) AS t ON SUBJECT.subject_id = t.subject_id
SET SUBJECT.current_class_count = coalesce( t.num, 0 )
```

As long as I've typed it right, basically you should be able to run this once an hour and it will update your SUBJECT table.

Joining a table in an UPDATE statement is a bit different in MySQL compared to Microsoft SQL.  Here is a link about it:

http://blog.ookamikun.com/2008/03/mysql-update-with-join.html

Body:
I have a table of classes, and a table of subjects.

CLASS
|class_id|class_name|subject_id|date_time|
------------------------------------------
(imagine some rows here)

SUBJECT
|subject_id|subject_name|current_class_count|
---------------------------------------------
(imagine some rows here)

For indexing purposes I'd like to update the list of subjects every hour with the list of classes which have a date_time greater than right now.

I can do a select statement like this:

SELECT count(*) AS num, subject_id
FROM class
GROUP BY subject_id
where date_time > NOW()

and I will get something like

RESULT
|num|subject_id|
----------------
| 8 |        1 |
| 6 |        2 |
| 9 |        3 |
----------------

What's the most efficient way to get the subject table updated with the current_class_count? I could do this with PHP by looping through and doing several update statements, but I think mySql should have an easier way.

Body:
Edit:  How about this:

UPDATE SUBJECT
LEFT JOIN (
SELECT count(*) AS num, subject_id
FROM class
GROUP BY subject_id
where date_time > NOW()) AS t ON SUBJECT.subject_id = t.subject_id
SET SUBJECT.current_class_count = coalesce( t.num, 0 )

As long as I've typed it right, basically you should be able to run this once an hour and it will update your SUBJECT table.

Joining a table in an UPDATE statement is a bit different in MySQL compared to Microsoft SQL.  Here is a link about it:

http://blog.ookamikun.com/2008/03/mysql-update-with-join.html


问:
Assigning values to cross selection of MultiIndex DataFrame (ellipsis style of numpy)
In numpy we can select the last axis with ellipsis indexing, f.i. array[..., 4].

In Pandas DataFrames for structuring large amounts of data, I like to use MultiIndex (which I see as some kind of additional dimensions of the DataFrame). If I want to select a given subset of a DataFrame df, in this case all columns 'key' in the last level of the columns MultiIndex, I can do it with the cross selection method xs:

```<code># create sample multiindex dataframe
mi = pd.MultiIndex.from_product((('a', 'b', 'c'), (1, 2), ('some', 'key', 'foo')))
data = pd.DataFrame(data=np.random.rand(20, 18), columns=mi)

# make cross selection:
xs_df = data.xs('key', axis=1, level=-1)
</code>```

But if I want to assign values to the cross selection, xs won't work.

The documentation proposes to use IndexSlice to access and set values to a cross selection:

```<code>idx = pd.IndexSlice
data.loc[:, idx[:, :, 'key']] *= 10
</code>```

Which is working well as long as I explicitly enter the number of levels by inserting the correct amount of : before 'key'.

Assuming I just want to give the number of levels to a selection function or f.i. always select the last level, independent of the number of levels of the DataFrame, this won't work (afaik).

My current workaround is using None slices for n_levels to skip:

```<code>n_levels = data.columns.nlevels - 1  # assuming I want to select the last level
data.loc[:, (*n_levels*[slice(None)], 'key')] *= 100
</code>```

This is imho a quite nasty and cumbersome workaround. Is there any more pythonic/nicer/better way?

答:
I don't think there is as straightforward a way to index and set values the way you want. Adding to previous answers, I'd suggest naming your columns, ... makes it easier to wrangle with the query method:</p>
```<code>#assign names
data.columns = data.columns.set_names(['first','second','third'])

#select interested level :
ind=data.T.query('third=="key"').index

#assign value
data.loc(axis=1)[ind] *=10
</code>```

Body:
In numpy we can select the last axis with ellipsis indexing, f.i. array[..., 4].

In Pandas DataFrames for structuring large amounts of data, I like to use MultiIndex (which I see as some kind of additional dimensions of the DataFrame). If I want to select a given subset of a DataFrame df, in this case all columns 'key' in the last level of the columns MultiIndex, I can do it with the cross selection method xs:

# create sample multiindex dataframe
mi = pd.MultiIndex.from_product((('a', 'b', 'c'), (1, 2), ('some', 'key', 'foo')))
data = pd.DataFrame(data=np.random.rand(20, 18), columns=mi)

# make cross selection:
xs_df = data.xs('key', axis=1, level=-1)

But if I want to assign values to the cross selection, xs won't work.

The documentation proposes to use IndexSlice to access and set values to a cross selection:

idx = pd.IndexSlice
data.loc[:, idx[:, :, 'key']] *= 10

Which is working well as long as I explicitly enter the number of levels by inserting the correct amount of : before 'key'.

Assuming I just want to give the number of levels to a selection function or f.i. always select the last level, independent of the number of levels of the DataFrame, this won't work (afaik).

My current workaround is using None slices for n_levels to skip:

n_levels = data.columns.nlevels - 1  # assuming I want to select the last level
data.loc[:, (*n_levels*[slice(None)], 'key')] *= 100

This is imho a quite nasty and cumbersome workaround. Is there any more pythonic/nicer/better way?

Body:
I don't think there is as straightforward a way to index and set values the way you want. Adding to previous answers, I'd suggest naming your columns, ... makes it easier to wrangle with the query method:

#assign names
data.columns = data.columns.set_names(['first','second','third'])

#select interested level :
ind=data.T.query('third=="key"').index

#assign value
data.loc(axis=1)[ind] *=10


问:
Class members visibility C++
I need to make the initializer of a class invisible for the child classes, but visible for the main(). How can I do it? The only way I see is to make it PUBLIC, but it will be inherited to the child classes. Any ideas?</p>

答:
You can make it private and add main as a friend</p>

```<code>class A {
private:
    A() {}
public:

friend int main(void);
};

int main(void) {
    // Your code
}
</code>```

Title: Class members visibility C++

Body:
You can make it private and add main as a friend

class A {
private:
    A() {}
public:

friend int main(void);
};

int main(void) {
    // Your code
}


问:
Extract specific dictionaries from a list of nested dictionaries to a temp list
I have been struggling to extract sub dictionaries where the value is "0" from a list of dictionaries and add them to temporary dictionaries.

I tried this:

new_users = [{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}]
    def approachA():
        for data in new_users:          # new_users is a list of nested dictionaries
            if data == '0':
                 print("found 0")
                 keys = data.keys()
                 for key in keys:
                     if key == '0':
                        key.pop() # tried to deleted delete the elements at first
```

<p>It did not work for some reason, and I have been trying to do it for 2 hours so please do not ask questions not related to the problem.</p>

<p>This is a simple version of what I am trying to do:</p>

<pre class="lang-py prettyprint-override"><code>[{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}] -> [{'user1':{'book1':'0'}}, {'user2':{'book3':'0'}}]
</code>```

So basically the keys with value "0" get copied to a temp list of dictionaries.

答:
If you're interested in recursion, the below example ought to get you going:</p>

```<code># d_xy => x = nest level
#         y = dictionary item in nest level x

d = {'d_00' : {'d_10' : {'d_20' : 0,
                         'd_21' : 43,
                         'd_22' : 12},
               'd_11' : 4,
               'd_12' : 0,
               'd_13' : 1},
     'd_01' : 0,
     'd_02' : {'d_14' : {'d_23' : 0,
                         'd_24' : 1,
                         'd_25' : 0},
               'd_15' : 4,
               'd_16' : {'d_26' : 0,
                         'd_27' : {'d_30' : 3,
                                   'd_31' : 0,
                                   'd_32' : {'d_40' : 0},
                                   'd_33' : 0},
                         'd_28' : 1},
               'd_17' : 0}}

important_items = []

def get_0_key_values(dic):

    for key in dic:
        if type(dic[key]) == dict:
            get_0_key_values(dic[key])
        else:
            if dic[key] == 0:
                important_items.append({key : dic[key]})

get_0_key_values(d)

print(important_items)
</code>```

Body:
I have been struggling to extract sub dictionaries where the value is "0" from a list of dictionaries and add them to temporary dictionaries.

I tried this:

new_users = [{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}]
    def approachA():
        for data in new_users:          # new_users is a list of nested dictionaries
            if data == '0':
                 print("found 0")
                 keys = data.keys()
                 for key in keys:
                     if key == '0':
                        key.pop() # tried to deleted delete the elements at first

It did not work for some reason, and I have been trying to do it for 2 hours so please do not ask questions not related to the problem.

This is a simple version of what I am trying to do:

[{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}] -> [{'user1':{'book1':'0'}}, {'user2':{'book3':'0'}}]

So basically the keys with value "0" get copied to a temp list of dictionaries.

Body:
If you're interested in recursion, the below example ought to get you going:

# d_xy => x = nest level
#         y = dictionary item in nest level x

d = {'d_00' : {'d_10' : {'d_20' : 0,
                         'd_21' : 43,
                         'd_22' : 12},
               'd_11' : 4,
               'd_12' : 0,
               'd_13' : 1},
     'd_01' : 0,
     'd_02' : {'d_14' : {'d_23' : 0,
                         'd_24' : 1,
                         'd_25' : 0},
               'd_15' : 4,
               'd_16' : {'d_26' : 0,
                         'd_27' : {'d_30' : 3,
                                   'd_31' : 0,
                                   'd_32' : {'d_40' : 0},
                                   'd_33' : 0},
                         'd_28' : 1},
               'd_17' : 0}}

important_items = []

def get_0_key_values(dic):

    for key in dic:
        if type(dic[key]) == dict:
            get_0_key_values(dic[key])
        else:
            if dic[key] == 0:
                important_items.append({key : dic[key]})

get_0_key_values(d)

print(important_items)


问:
Can't connect using windows authentication to azure cube over Azure SSIS /SSIS run time created in ADF
I have SSIS package created locally which connects to azure cube. In order to connect to azure cube I am using windows authentication as shown below:

As shown above I am able to connect to Azure cube locally (i.e. on my desktop version of SSDT) via windows authentication.

Now I have created a azure SSIS runtime in ADF (Please note this azure subscription of ADF is different than that of the azure cube which i am connecting to). Now when i deploy the local (i.e. desktop version ) of SSIS package to the azure SSIS and try to run trigger the SSIS package via azure catlog in SSMS or through azure ADF i am getting the below connection failure message

1) Error which i get when i try to run the package on SSIS catlog over azure server

2) Error which i get when i try to run the deployed SSIS package via ADf created.

Error details

Output

{
    "SsisDBOperationGuid": "ed2ca785-a942-434a-955a-9c1f0b5ed3b7",
    "SsisDBOperationId": 26,
    "OperationErrorMessages": "12/29/2019 7:23:47 AM +00:00 : Data Flow Task:Error: ADO NET Source has failed to acquire the connection {280FE230-2294-49D8-A947-D2EA8A7F29A2} with the following error message: \"COM error: COM error: mscorlib; Exception has been thrown by the target of an invocation..\".\r\n\n12/29/2019 7:23:47 AM +00:00 : Data Flow Task:Error: ADO NET Source failed validation and returned error code 0xC0208449.\r\n\n12/29/2019 7:23:47 AM +00:00 : Data Flow Task:Error: One or more component failed validation.\r\n\n",
    "effectiveIntegrationRuntime": "SSSISruntime (West US 2)",
    "executionDuration": 6,
    "durationInQueue": {
        "integrationRuntimeQueue": 1
    }
}

Even though i am using windows authentication in ADF  connection which uses the same credentials by which visual studio package is running locally i am getting the above error.
Could you please let me know how can i run a ssis pakage package in ssis azure runtime by windows authention mode and can connect to the azure cube?
Any help would be greatly appreciated

答:
You will need to refer this section:

Use Windows authentication in staging tasks

If the staging tasks on your self-hosted IR require Windows authentication, configure your SSIS packages to use the same Windows authentication.

Your staging tasks will be invoked with the self-hosted IR service account (NT SERVICE\DIAHostService, by default), and your data stores will be accessed with the Windows authentication account. Both accounts require certain security policies to be assigned to them. On the self-hosted IR machine, go to Local Security Policy > Local Policies > User Rights Assignment, and then do the following:

Assign the Adjust memory quotas for a process and Replace a process level token policies to the self-hosted IR service account. This should occur automatically when you install your self-hosted IR with the default service account. If it doesn't, assign those policies manually. If you use a different service account, assign the same policies to it.

Assign the Log on as a service policy to the Windows Authentication account.

MSFT Document


答: There is no software that will get the code for you. Asking the website owner to see it for educational purposes is the best way.</p>

Title: Is it possible to read php code from other sites?

Body: Just a curious question. I was wondering is it possible to read a sites php/server side codes? Is there any software/method that can be used to do so? Sometimes for educational purposes, i really want to see how people form the backend infrastructure of their sites.


问:
SuperScalar Out of Order Scheduling

In the figure above, isn't it SUB BX,4 be busy (in out of order scheduling)?? Why is that not busy? Because by the definition of out of order execution, we are just changing the way we schedule instructions. Instead of doing them sequentially, we do them in any order as long as there are no dependencies. Can anyone give the logic behind filling table 15.4? I can follow table 15.3 but not table 15.4

答:
In the out-of-order processor, SUB BX,4 isn't data dependent on the results of another instruction. So it can begin execution because a pipeline, #2, is available although that pipeline is also busy with the load. It's a pipeline with multiple instructions in flight rather than simply a two cycle functional unit with only one instruction. MOV CX,2000 also issues because it is available.

Now there is a bubble because the load isn't finished and another instruction can't be found to execute. So it's marked busy for a cycle. Now the result of the load is available in DL and the next instruction can execute in pipeline 1 in cycle 4. Pipeline #2 goes idle because, I assume, the SUB took two cycles.

You don't give enough information about instruction latencies.

Title: SuperScalar Out of Order Scheduling


问:
Why is my Node.js package missing the main file when installed globally?
This feels like an embarrassing question to ask but having recently published a Node package to the NPM registry, I now find it doesn't work.

The issue seems to be that my main file, ./src/index.js, isn't being included in the global install.

I know this because when I call the package from the command line it
runs ./bin/cli.js in the package as expected, but then throws:

```<code>Error: Cannot find module '../src/index.js'
Require stack:
- /usr/lib/node_modules/diffcraft/bin/cli.js
</code>```

The error even references the line in ./bin/cli.js where the index
file is required, so that's definitely where the problem is.

I also know this because I checked the folder where the module is
installed globally and while the bin folder is there, the src
folder isn't. So the main code for my package just isn't there.

After discovering this, I even patched package.json to ensure that ./src/index.js was explicitly whitelisted in the files array. I hadn't done this before as NPM guidance states that whichever file is listed under main is also automatically whitelisted. But even including the file in files explicitly hasn't worked.

For reference, I don't have an .npmignore file.

I've got a horrible feeling I'm missing something simple and basic... Any ideas why my main file might be being skipped?

The package is diffcraft.

答:
It works if you omit the ./ in front of the files (tested with npm 6.14.4 on Windows):

```<code>  "files": [
    "bin/cli.js",
    "src/index.js"
  ],
</code>```

This might be a bug in npm.

You can check this without publishing by running npm pack and checking the archive file.

Alternative is using an .npmignore file.

Body:
This feels like an embarrassing question to ask but having recently published a Node package to the NPM registry, I now find it doesn't work.

The issue seems to be that my main file, ./src/index.js, isn't being included in the global install.

I know this because when I call the package from the command line it
runs ./bin/cli.js in the package as expected, but then throws:

Error: Cannot find module '../src/index.js'
Require stack:
- /usr/lib/node_modules/diffcraft/bin/cli.js

The error even references the line in ./bin/cli.js where the index
file is required, so that's definitely where the problem is.

I also know this because I checked the folder where the module is
installed globally and while the bin folder is there, the src
folder isn't. So the main code for my package just isn't there.

After discovering this, I even patched package.json to ensure that ./src/index.js was explicitly whitelisted in the files array. I hadn't done this before as NPM guidance states that whichever file is listed under main is also automatically whitelisted. But even including the file in files explicitly hasn't worked.

For reference, I don't have an .npmignore file.

I've got a horrible feeling I'm missing something simple and basic... Any ideas why my main file might be being skipped?

The package is diffcraft.

Body:
It works if you omit the ./ in front of the files (tested with npm 6.14.4 on Windows):

  "files": [
    "bin/cli.js",
    "src/index.js"
  ],

This might be a bug in npm.

You can check this without publishing by running npm pack and checking the archive file.

Alternative is using an .npmignore file.


问:
Get the current value in Selectpicker using jQuery in Codeigniter Framework
I was trying to do a DOM manipulation using the value of the selected option of the selectpicker. What i wanted was to get the value of the selectpicker id="service_provider_select" to get printed first.I change the option using the selectpicker and when i run the console.log(input), every time I've got the Dialog as the printed value in the console.

How can I get the value for the recent selection?

HTML

```<code><select class="selectpicker form-control item_select" id="service_provider_select" name="service_provider_select" data-size="5" data-live-search="true">
        <option value="">Select Sevice Provider</option>
        <option value="Dialog"> Dialog </option>
        <option value="Mobitel"> Mobitel </option>
        <option value="Airtel"> Airtel </option>
        <option value="Hutch"> Hutch </option>
</select>

</code>```

JAVASCRIPT

```<code><script>
   $(document).ready(function()
   {
      $(".selectpicker").selectpicker();

      $('#service_provider_select').on("click", function()
      {
         input = $('#service_provider_select').val();
         console.log(input);
      });
   });

   var input = "Dialog";

</script>
</code>```

答:
I created a working snippet for your issue which seems to work for me, see if it works for you as well.

$(document).ready(function() {
  $(".selectpicker").selectpicker();

  // Fire event on change instead of on click
  $('#service_provider_select').on("change", function() {
    input = $('#service_provider_select').val();
    console.clear();
    console.log(input);
  });
});

var input = "Dialog";```
<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>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>

<select class="selectpicker form-control item_select" id="service_provider_select" name="service_provider_select" data-size="5" data-live-search="true">
  <option value="">Select Sevice Provider</option>
  <option value="Dialog"> Dialog </option>
  <option value="Mobitel"> Mobitel </option>
  <option value="Airtel"> Airtel </option>
  <option value="Hutch"> Hutch </option>
</select></code>```

Body:
I was trying to do a DOM manipulation using the value of the selected option of the selectpicker. What i wanted was to get the value of the selectpicker id="service_provider_select" to get printed first.I change the option using the selectpicker and when i run the console.log(input), every time I've got the Dialog as the printed value in the console.

How can I get the value for the recent selection?

HTML

<select class="selectpicker form-control item_select" id="service_provider_select" name="service_provider_select" data-size="5" data-live-search="true">
        <option value="">Select Sevice Provider</option>
        <option value="Dialog"> Dialog </option>
        <option value="Mobitel"> Mobitel </option>
        <option value="Airtel"> Airtel </option>
        <option value="Hutch"> Hutch </option>
</select>

JAVASCRIPT

Body:
I created a working snippet for your issue which seems to work for me, see if it works for you as well.

$(document).ready(function() {
  $(".selectpicker").selectpicker();

  // Fire event on change instead of on click
  $('#service_provider_select').on("change", function() {
    input = $('#service_provider_select').val();
    console.clear();
    console.log(input);
  });
});

var input = "Dialog";

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>

<select class="selectpicker form-control item_select" id="service_provider_select" name="service_provider_select" data-size="5" data-live-search="true">
  <option value="">Select Sevice Provider</option>
  <option value="Dialog"> Dialog </option>
  <option value="Mobitel"> Mobitel </option>
  <option value="Airtel"> Airtel </option>
  <option value="Hutch"> Hutch </option>
</select>


答:
It is only possible if the site's owner intentionally makes the code publicly available, or if the site has a very critical security hole. Usually, no, you cannot read other people's server-side code.

After all, we'd have huge problems if you could just read any server-side code you wanted. If, say, a bank's website were built in PHP, it would be important that raw PHP files could not be read by the public: they might contain private data like database passwords, or simply make it much, much easier to find other key security issues, since, after all, which is easier—finding problems with code you can see, or code you can't see? As much as I am a fan of open-source coding, I would not put my money in any bank that makes its source code available. It's just too risky.

However, if you're interested in learning, there are plenty of open-source web applications out there. Try searching Github for, say, projects written in PHP. It's definitely a good idea to read other people's code, and I'm sure you could find some stellar examples of real-world code if you know where to look. Additionally, if you ask nicely, a website owner may be willing to share parts of the source code with you, though probably not all of it, for security reasons. Couldn't hurt to ask.


问:
Is there a standard way for Javascript classes to refer to each other?
I was wondering, is there a standard way for class properties and methods to refer to each other in their declaration? For example:

```<code>class A {
  methodA(){
    b.methodB()
    ...
  }
}

class B {
  methodB(){...}
}

const a = new A();
const b = new B();

///will throw ReferenceError: Cannot access 'b' before initialization;
</code>```

I understand that you can add methodA in later after all class/object declarations, but it gets quite untidy after many repetitions, which I feel like defeats the purpose of classes. Or that you can delay the reference through some other means. Is there a standard way to do this?

答:
Well, you could always keep instantiating the other classes in your class, say A and access their methods and properties like this.

class A {
  methodA(){
    const b = new B();
    b.methodB()
  }
}

class B {
  methodB(){console.log("Here I am")}
}

const a = new A();
a.methodA();```
</div>
</div>
</p>

<p>Or, You can use <code>inheritance</code>.</p>

```class A {}
class B extends A{
 constructor() { super(); //}
}
```

Body:
I was wondering, is there a standard way for class properties and methods to refer to each other in their declaration? For example:

class A {
  methodA(){
    b.methodB()
    ...
  }
}

class B {
  methodB(){...}
}

const a = new A();
const b = new B();

///will throw ReferenceError: Cannot access 'b' before initialization;

I understand that you can add methodA in later after all class/object declarations, but it gets quite untidy after many repetitions, which I feel like defeats the purpose of classes. Or that you can delay the reference through some other means. Is there a standard way to do this?

Body:
Well, you could always keep instantiating the other classes in your class, say A and access their methods and properties like this.

class A {
  methodA(){
    const b = new B();
    b.methodB()
  }
}

class B {
  methodB(){console.log("Here I am")}
}

const a = new A();
a.methodA();

Or, You can use inheritance.

class A {}
class B extends A{
 constructor() { super(); //}
}


问:
Matplotlib figure is not saving in a specific folder
I am trying to save matplotlib figure in r"C:\Users\USER\Handcrafted dataset\binary_image". but instead of saving figure in binary_image folder figure is saving in Handcrafted dataset  folder. And the image name is becoming binary_image0.png. But i want to save figure in my desired directory as i.png .How can i fix this?

```<code>di=r"C:\Users\USER\Handcrafted dataset\binary_image"
for i,img in enumerate(images):
    img = rgb2gray(img)
    plt.figure(figsize=(5,5))
    plt.imshow(img ,cmap='gray')
    plt.savefig(di+str(i)+".png")
</code>```

答:
Using os.path.join or pathlib.Path is better.

```<code>import os

fn = "file_{}.png".format(i)
fn = os.path.join(dir, fn)
plt.savefig(fn)
</code>```

or

```<code>from pathlib import Path

dir = Path(dir)
fn = dir / "file_{}.png".format(i)
plt.savefig(fn)
</code>```

Body:
I am trying to save matplotlib figure in r"C:\Users\USER\Handcrafted dataset\binary_image". but instead of saving figure in binary_image folder figure is saving in Handcrafted dataset  folder. And the image name is becoming binary_image0.png. But i want to save figure in my desired directory as i.png .How can i fix this?

di=r"C:\Users\USER\Handcrafted dataset\binary_image"
for i,img in enumerate(images):
    img = rgb2gray(img)
    plt.figure(figsize=(5,5))
    plt.imshow(img ,cmap='gray')
    plt.savefig(di+str(i)+".png")

Body:
Using os.path.join or pathlib.Path is better.

import os

fn = "file_{}.png".format(i)
fn = os.path.join(dir, fn)
plt.savefig(fn)

or

from pathlib import Path

dir = Path(dir)
fn = dir / "file_{}.png".format(i)
plt.savefig(fn)


问:
AWS lambda duration spike (nothing to do with cold start)
I have a few AWS Lambda functions, but the troubleshooting is for one of them. this Lambda function is triggered by message queue, read DynamoDB, process, write DynamoDB. it is called up to 10 requests per second and I have set Lambda provision concurrency. Average Lambda duration is 60 ms which I am very happy with. But every day there are around 10 instances which Lambda function duration is more than 1 second up to 3 second timeout.

I put log in my Lambda, during duration spikes, read/write (getitem/putitem) DynamoDB took more than 1 second. Dynamodb is set to on-demend. it is a very simple table, two columns, ID (auto number) and a json string(about 1KB). I have tried Redis, but weird enough, still had spikes. Lambda is not put in VPC. Dynamo connection has been set to http timeout 500, max retry to 2.

Code to read DynamodDB:

Log for Duration:

答:
When using provisioned concurrency, the Lambda service would keep a set number of the underlying containers "warm" so as to minimize start up time. Since you mention that you intermittently face higher execution durations, refer to the below debugging steps which you can do:

Check the "Concurrent Executions" metric for the Lambda function against the "Duration" metric: If the number of instances of the function executing at a particular time is higher than the set provisioned concurrency, then that would imply that s few of these instances had cold starts causing the higher duration.

Enable X-Ray tracing for the Lambda function and also add X-ray instrumentation to your code: This would give a complete idea of which network call takes up too much time and also give you the cold start "init" duration (if any).


问:
Why does each element of my array automatically turn into the last element?
```<code>char *string[n];
for (int i = 0; i < n; i++) {
    char string[60];
    fscanf(fptr, "%s%*[^\n]", string);
    strings[i] = string;
    printf("%s\n", strings[i]);
}
puts("Ended");
for (int i = 0; i < n; i++) {
printf("%s\n", strings[i]);
</code>```

This is part of my code in C ^. strings[] contains pointers to the first word of each line in the file. So if my file contains:

```
ABC 123
DEF 123
GHI 123
```

I get the following output:

```
ABC
DEF
GHI
Ended
GHI
GHI
GHI
```

Which means there's nothing wrong with the initialisation. Then what is going on?

答:
When you wrote :

```<code>strings[i]=string
</code>```

You were not copying the original string into the array because the “string” variable only contains a pointer (memory address) of the stack allocated string. When you go into the next iteration of the for loop, the stack allocated “string” variable gets freed/thrown away.

So your “strings” array contains pointers to unallocated memory. You should use “strcpy” instead. If the size of your “strings” array is not constant, use “malloc” then “strcpy”.

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

int main()
{
    FILE *fptr = fopen("test.txt", "r");
    char strings[10][60];
    int n = 3;
    for (int i = 0; i < n; i++)
    {
        char string[60];
        fscanf(fptr, "%s%*[^\n]", string);
        strcpy(strings[i], string);
        printf("%s\n", strings[i]);
    }
    puts("Ended");
    for (int i = 0; i < n; i++)
    {
         printf("%s\n", strings[i]);
    }
}
</code>```

Or, simpler:

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

int main()
{
    FILE *fptr = fopen("test.txt", "r");
    char strings[10][60];
    int n = 3;
    for (int i = 0; i < n; i++)
    {
        fscanf(fptr, "%s%*[^\n]", strings[i]);
        printf("%s\n", strings[i]);
    }
    puts("Ended");
    for (int i = 0; i < n; i++)
    {
        printf("%s\n", strings[i]);
    }
}
</code>```

Body:
char *string[n];
for (int i = 0; i < n; i++) {
    char string[60];
    fscanf(fptr, "%s%*[^\n]", string);
    strings[i] = string;
    printf("%s\n", strings[i]);
}
puts("Ended");
for (int i = 0; i < n; i++) {
printf("%s\n", strings[i]);

This is part of my code in C ^. strings[] contains pointers to the first word of each line in the file. So if my file contains:

ABC 123
DEF 123
GHI 123

I get the following output:

ABC
DEF
GHI
Ended
GHI
GHI
GHI

Which means there's nothing wrong with the initialisation. Then what is going on?

Body:
When you wrote :

strings[i]=string

You were not copying the original string into the array because the “string” variable only contains a pointer (memory address) of the stack allocated string. When you go into the next iteration of the for loop, the stack allocated “string” variable gets freed/thrown away.

So your “strings” array contains pointers to unallocated memory. You should use “strcpy” instead. If the size of your “strings” array is not constant, use “malloc” then “strcpy”.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fptr = fopen("test.txt", "r");
    char strings[10][60];
    int n = 3;
    for (int i = 0; i < n; i++)
    {
        char string[60];
        fscanf(fptr, "%s%*[^\n]", string);
        strcpy(strings[i], string);
        printf("%s\n", strings[i]);
    }
    puts("Ended");
    for (int i = 0; i < n; i++)
    {
         printf("%s\n", strings[i]);
    }
}

Or, simpler:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fptr = fopen("test.txt", "r");
    char strings[10][60];
    int n = 3;
    for (int i = 0; i < n; i++)
    {
        fscanf(fptr, "%s%*[^\n]", strings[i]);
        printf("%s\n", strings[i]);
    }
    puts("Ended");
    for (int i = 0; i < n; i++)
    {
        printf("%s\n", strings[i]);
    }
}


问:
sscanf() causing infinite loop by changing the index value of for loop
Function:

void input_bytes(unsigned char bytes[], int num_bytes)
{
    const int CHAR_PER_BYTE = 2; /* expects hex input */
    const int STRING_SIZE = num_bytes * CHAR_PER_BYTE;

    char input_string[STRING_SIZE + 1];  /* + 1 for null char */
    int ind;
    unsigned char byte;

    fgets(input_string, STRING_SIZE + 1, stdin);

    printf("after fgets\n");

    for (ind = 0; ind < num_bytes; ind++)
    {
        printf("top of loop, ind: %d\n", ind);

        sscanf(input_string, "%2x", &byte);
        bytes[ind] = byte;

        printf("bottom of loop, ind: %d\n", ind);
    }

    printf("\n\n");
}
```

<p>Driver:</p>

<pre class="lang-c prettyprint-override"><code>int main()
{
    unsigned char bytes[5];

    input_bytes(bytes, 5);
}
</code>```

Output:

```<code>after fgets
top of loop, ind: 0
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
...
</code>```

Compiling with gcc driver.c -o driver.

I put an ind++ in the loop out of curiosity and it goes to 2 at the top and 1 at the bottom. If I take the sscanf() out it terminates.

答:
The variable corresponding to %x format must be int, not char. Using the wrong type results in undefined behavior; in your program, it's writing 0 to ind, so the loop never stops.

The size argument to fgets() should be the size of the buffer, without adding 1. fgets() will subtract 1 to get the number of characters it can read before the null. You should add 1 to the size of input_string, not the argument to fgets().

fgets() also includes the newline in the input that it returns, you need to add room for that to input_string as well.

If you want to convert all the bytes in the input, you need to scan from a different index in input_string each time through the loop.

```<code>void input_bytes(unsigned char bytes[], int num_bytes)
{
    const int CHAR_PER_BYTE = 2; /* expects hex input */
    const int STRING_SIZE = num_bytes * CHAR_PER_BYTE + 2; // + 2 for newline and null byte

    char input_string[STRING_SIZE];
    int ind;
    unsigned int byte;

    fgets(input_string, STRING_SIZE, stdin); /* + 1 for null char */

    printf("after fgets\n");

    for (ind = 0; ind < num_bytes; ind++)
    {
        printf("top of loop, ind: %d\n", ind);

        sscanf(&input_string[2*ind], "%2x", &byte);
        bytes[ind] = byte;

        printf("bottom of loop, ind: %d\n", ind);
    }

    printf("\n\n");
}
</code>```

Since you're not actually performing any string operations on input_string. You could make it exactly num_bytes * CHAR_PER_BYTE characters long, without adding space for the newline and null. Instead of using fgets(), use fread() to read exactly the number of characters you want:

```<code>fread(input_string, CHAR_PER_BYTE, num_bytes, stdin);
</code>```

Body:
Function:

void input_bytes(unsigned char bytes[], int num_bytes)
{
    const int CHAR_PER_BYTE = 2; /* expects hex input */
    const int STRING_SIZE = num_bytes * CHAR_PER_BYTE;

    char input_string[STRING_SIZE + 1];  /* + 1 for null char */
    int ind;
    unsigned char byte;

    fgets(input_string, STRING_SIZE + 1, stdin);

    printf("after fgets\n");

    for (ind = 0; ind < num_bytes; ind++)
    {
        printf("top of loop, ind: %d\n", ind);

        sscanf(input_string, "%2x", &byte);
        bytes[ind] = byte;

        printf("bottom of loop, ind: %d\n", ind);
    }

    printf("\n\n");
}

Driver:

int main()
{
    unsigned char bytes[5];

    input_bytes(bytes, 5);
}

Output:

after fgets
top of loop, ind: 0
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
top of loop, ind: 1
bottom of loop, ind: 0
...

Compiling with gcc driver.c -o driver.

I put an ind++ in the loop out of curiosity and it goes to 2 at the top and 1 at the bottom. If I take the sscanf() out it terminates.

Body:
The variable corresponding to %x format must be int, not char. Using the wrong type results in undefined behavior; in your program, it's writing 0 to ind, so the loop never stops.

The size argument to fgets() should be the size of the buffer, without adding 1. fgets() will subtract 1 to get the number of characters it can read before the null. You should add 1 to the size of input_string, not the argument to fgets().

fgets() also includes the newline in the input that it returns, you need to add room for that to input_string as well.

If you want to convert all the bytes in the input, you need to scan from a different index in input_string each time through the loop.

void input_bytes(unsigned char bytes[], int num_bytes)
{
    const int CHAR_PER_BYTE = 2; /* expects hex input */
    const int STRING_SIZE = num_bytes * CHAR_PER_BYTE + 2; // + 2 for newline and null byte

    char input_string[STRING_SIZE];
    int ind;
    unsigned int byte;

    fgets(input_string, STRING_SIZE, stdin); /* + 1 for null char */

    printf("after fgets\n");

    for (ind = 0; ind < num_bytes; ind++)
    {
        printf("top of loop, ind: %d\n", ind);

        sscanf(&input_string[2*ind], "%2x", &byte);
        bytes[ind] = byte;

        printf("bottom of loop, ind: %d\n", ind);
    }

    printf("\n\n");
}

Since you're not actually performing any string operations on input_string. You could make it exactly num_bytes * CHAR_PER_BYTE characters long, without adding space for the newline and null. Instead of using fgets(), use fread() to read exactly the number of characters you want:

fread(input_string, CHAR_PER_BYTE, num_bytes, stdin);


问:
imagemagick cannot read these files
I have jasper installed and the lastest version of imagemagick. When I attempt to process these two files: here and here

I get a decode error. Can anyone let me know which other packages I need to install for imagemagick to read these files properly?

答:
Has your IM been compiled with --with-jpeg=no or --without-jpeg?

Or did the compilation fail to include JPEG support because of a lack of decoder libraries being installed?  You need libjpeg installed, and the development header files for that library.

You can find out what formats are supported by issuing the command:

```<code>$ identify -list format
</code>```

If you state your OS (inc. distribution if Linux) and how you installed IM, you might get more information on how to resolve it.  If you are on linux the package names are probably libjpeg and libjpeg-devel.

Title: imagemagick cannot read these files

Body:
Has your IM been compiled with --with-jpeg=no or --without-jpeg?

Or did the compilation fail to include JPEG support because of a lack of decoder libraries being installed?  You need libjpeg installed, and the development header files for that library.

You can find out what formats are supported by issuing the command:

$ identify -list format

If you state your OS (inc. distribution if Linux) and how you installed IM, you might get more information on how to resolve it.  If you are on linux the package names are probably libjpeg and libjpeg-devel.


问:
Embedded UIcollectionView scrolling inside UITableView Cell
I have UICollectionView inside Static UITableView Cell. I want to ask how to enable vertical scrolling in UIcollectionView interface builder. what are the right settings to achieve that?

答:
You couldn't see any scrolling in the Interface Builder:) Only when compiled.
Yes, you have right set - Scroll direction to Vertical. But... I guess, this is doesn't work for you?
If you set custom layout for collection view in code - you have to setup it.


问:
"GetPassWarning: Can not control echo on the terminal" when running from IDLE
When I run this code:

```<code>import getpass

p = getpass.getpass(prompt='digite a senha\n')
if p == '12345':
    print('YO Paul')
else:
    print('BRHHH')
print('O seu input foi:', p) # p = seu input
</code>```

I got this warning:

```<code>Warning (from warnings module):
   File "/usr/lib/python3.4/getpass.py", line 63
    passwd = fallback_getpass(prompt, stream)
GetPassWarning: Can not control echo on the terminal. Warning: Password input may be echoed.
</code>```

答:
use cmd ie. command prompt and then run the file in it.

like:

```<code>python abc.py
</code>```

Body:
When I run this code:

import getpass

p = getpass.getpass(prompt='digite a senha\n')
if p == '12345':
    print('YO Paul')
else:
    print('BRHHH')
print('O seu input foi:', p) # p = seu input

I got this warning:

Warning (from warnings module):
   File "/usr/lib/python3.4/getpass.py", line 63
    passwd = fallback_getpass(prompt, stream)
GetPassWarning: Can not control echo on the terminal. Warning: Password input may be echoed.

Body:
use cmd ie. command prompt and then run the file in it.

like:

python abc.py


问:
Using gitLab-CI for Qt-Projects
I want to use gitLab-CI for a Qt-project, but i can't figure out, what I need to do so. I understand, that the whole pipeline process takes place on the CI-Server, but how do I setup the needed requirements like the qt-environment?

Solution:

Ok now I got it! You just use the Runner for it, if you do not have a Server, you can use a VM.

答:
For GitLab.com

The runners are already set up (shared runners).

You need to use a Qt SDK Docker image or install it yourself:

Use image: <image-name> for .gitlab-ci.yml

Use apt or some other package manager (not recommended)

Once you got a Qt SDK environment set up inside .gitlab-ci.yml, make sure to add a command to build/compile/run/test it.

For non-GitLab.com

The runners may or may not be set up, but you do not need to do any specific changes (other than using faster machines with bigger memory, etc for building in necessary).

You need to use a Qt SDK Docker image or install it yourself:

Use image: <image-name> for .gitlab-ci.yml

Use apt or some other package manager (not recommended)

Once you got a Qt SDK environment set up inside .gitlab-ci.yml, make sure to add a command to build/compile/run/test it.

Other Helpful Comments

This is from Josh Peak's comment:

Ok that answers my question. I'm going to have to preconfigure a VM image and/or a Docker image with the QT SDK that the rest of my dev team can leverage. Thanks for the quick response.

This answer is from ManuelP.'s question:

Ok now I got it! You just use the Runner for it, if you do not have a Server, you can use a VM.

Title: Using gitLab-CI for Qt-Projects


问:
plotting on the y-axis in Mathematica
I have another question about Wolfram Mathematica. Is there someone that knows how I can plot a graphic on the y axis?

I hope that the figure helps.

答:
You can flip the axes after plotting with Reverse:

```<code>g = Plot[Sin[x], {x, 0, 9}];

Show[g /. x_Line :> Reverse[x, 3], PlotRange -> Automatic]
</code>```

With a minor change this works for plots using Filling as well:

```<code>g1 = Plot[{Sin[x], .5 Sin[2 x]}, {x, 0, 2 \[Pi]}];
g2 = Plot[{Sin[x], .5 Sin[2 x]}, {x, 0, 2 \[Pi]}, Filling -> {1 -> {2}}];

Show[# /. x_Line | x_GraphicsComplex :> x~Reverse~3,
     PlotRange -> Automatic] & /@ {g1, g2}
</code>```

(It may be more robust to replace the RHS of :> with MapAt[#~Reverse~2 &, x, 1])

As a Function

Here is the form I recommend one use.  It includes flipping of the original PlotRange rather than forcing PlotRange -> All:

```<code>axisFlip = # /. {
   x_Line | x_GraphicsComplex :>
      MapAt[#~Reverse~2 &, x, 1],
   x : (PlotRange -> _) :>
      x~Reverse~2 } &;
</code>```

To be used like: axisFlip @ g1 or axisFlip @ {g1, g2}

A different effect can be had with Rotate:

```<code>Show[g /. x_Line :> Rotate[x, Pi/2, {0,0}], PlotRange -> Automatic]
</code>```

Title: plotting on the y-axis in Mathematica

Body:
You can flip the axes after plotting with Reverse:

g = Plot[Sin[x], {x, 0, 9}];

Show[g /. x_Line :> Reverse[x, 3], PlotRange -> Automatic]

With a minor change this works for plots using Filling as well:

g1 = Plot[{Sin[x], .5 Sin[2 x]}, {x, 0, 2 \[Pi]}];
g2 = Plot[{Sin[x], .5 Sin[2 x]}, {x, 0, 2 \[Pi]}, Filling -> {1 -> {2}}];

Show[# /. x_Line | x_GraphicsComplex :> x~Reverse~3,
     PlotRange -> Automatic] & /@ {g1, g2}

(It may be more robust to replace the RHS of :> with MapAt[#~Reverse~2 &, x, 1])

As a Function

Here is the form I recommend one use.  It includes flipping of the original PlotRange rather than forcing PlotRange -> All:

axisFlip = # /. {
   x_Line | x_GraphicsComplex :>
      MapAt[#~Reverse~2 &, x, 1],
   x : (PlotRange -> _) :>
      x~Reverse~2 } &;

To be used like: axisFlip @ g1 or axisFlip @ {g1, g2}

A different effect can be had with Rotate:

Show[g /. x_Line :> Rotate[x, Pi/2, {0,0}], PlotRange -> Automatic]