问:
Most efficient way to find the index of the only '1' bit in a char variable (in C)
This is an interview question:

You are given a char variable named ch, when you know that it represents a number that in its binary form, only one of its eight bits will be equal to '1'. I.E. , the only possible values for ch are: 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80.

Given the variable ch, I need to write the most efficient code to get the index of that '1' bit. For example: if ch == 0x1 -> result is 0. if ch == 0x4 -> result is 2.

The obvious way is to use switch-case, but I need something more efficient.

Is there any bit manipulation you can do here for efficient implementation?

答:
You can use binary search technique here to reduce the number of comparison from 7 to 3. </p>

```<code>assert((n & n-1) == 0);
if(n & 0x0F) {
    if(n & 0x03){
        if(n & 0x01){
            idx = 0;
        }
        else{
            idx = 1;
        }
    }else{
        if(n & 0x04){
            idx = 2;
        }
        else{
            idx = 4;
        }
    }
}else{
    if(n & 0x30){
        if(n & 0x10){
            idx = 3;
        }
        else{
            idx = 4;
        }
    }else{
        if(n & 0x40){
            idx = 5;
        }
        else{
            idx = 6;
        }
    }
}
</code>```

Body:
You can use binary search technique here to reduce the number of comparison from 7 to 3.

assert((n & n-1) == 0);
if(n & 0x0F) {
    if(n & 0x03){
        if(n & 0x01){
            idx = 0;
        }
        else{
            idx = 1;
        }
    }else{
        if(n & 0x04){
            idx = 2;
        }
        else{
            idx = 4;
        }
    }
}else{
    if(n & 0x30){
        if(n & 0x10){
            idx = 3;
        }
        else{
            idx = 4;
        }
    }else{
        if(n & 0x40){
            idx = 5;
        }
        else{
            idx = 6;
        }
    }
}


来源: stackexchange

问:
Possible to HTML scrape for LaTeX through a URL?
I've looked through many places for any LaTeX integration with processing (java), and can't find any that work. Although not all hope is lost as I have an idea.

Are there any websites that convert raw LaTeX to images, where I could access the raw LaTeX within the URL?

e.g;

https://www.latexgen.com/?text=2x+5-y (fake website).

where 2x+5-y would be processed into a LaTeX picture.

From there, I might be able to scrape the HTML to find the image. Essentially creating a tedious, but functional text-to-LaTeX function.

I'm aware that a few modules aleady exist for Java. And that there are many websites that convert text to LaTeX.

答:
Found exactly what I was looking for!

```<code>http://latex.codecogs.com/png.latex?\dpi{300} \huge x
</code>```

Replace x with the LaTeX formula and the site will generate the image.

ContentLicense: CC BY-SA 3.0

Body:
Found exactly what I was looking for!

http://latex.codecogs.com/png.latex?\dpi{300} \huge x

Replace x with the LaTeX formula and the site will generate the image.


问:
Codeigniter two project same session directory
I want to use same directory (for 2 project) for codeigniter "files" session driver. Both projects are in same server.

project 1 save path settings

```<code>$config['sess_save_path'] = APPPATH.'session_data';
</code>```

project 2 save path settings

```<code>$config['sess_save_path'] = $_SERVER['DOCUMENT_ROOT'].'/project1/application/session_data';
</code>```

This is working locally but not working in production server. Whats wrong there? My "session_data" directory permission is "755". 777 tested but not work

答:
In simple write the same value for both the files in config.php

```<code> $['encryption_key'] = 'ci_sesion';
 $config['sess_cookie_name'] = 'ci_session';
 $config['csrf_token_name'] = 'csrf_test_name';
 $config['csrf_cookie_name'] = 'csrf_cookie_name';
</code>```

I did and getting my output like move from one project to another project using same session.

Suppose you need to create two different project having different session then change the value of given above variables.

Body:
I want to use same directory (for 2 project) for codeigniter "files" session driver. Both projects are in same server.

project 1 save path settings

$config['sess_save_path'] = APPPATH.'session_data';

project 2 save path settings

$config['sess_save_path'] = $_SERVER['DOCUMENT_ROOT'].'/project1/application/session_data';

This is working locally but not working in production server. Whats wrong there? My "session_data" directory permission is "755". 777 tested but not work

Body:
In simple write the same value for both the files in config.php

 $['encryption_key'] = 'ci_sesion';
 $config['sess_cookie_name'] = 'ci_session';
 $config['csrf_token_name'] = 'csrf_test_name';
 $config['csrf_cookie_name'] = 'csrf_cookie_name';

I did and getting my output like move from one project to another project using same session.

Suppose you need to create two different project having different session then change the value of given above variables.


问:
Join three tables in mysql but have all data from one table
I have three tables named book (isbn, name, publisher, price, category, quantity), author (auth_id, auth_name) and written_by(isbn,auth_id). I am joining all three tables but in the result, I want all the books even whose author is not entered in the database. I have written the following query

```<code>select b.isbn, b.name, b.publisher, b.price, b.category, b.quantity,
group_concat(a.auth_name) as authors
from book b
left outer join written_by w on b.isbn=w.isbn
left outer join author a on a.auth_id=w.auth_id
group by b.isbn
having  authors like '%';
</code>```

The above query returns only the books who have authors linked to them in the written_by table. I want all the books including the ones with no authors in the database.
How do I join these three tables in such a way?
EDIT:
Sample Data
Book table

    isbn    name      publisher    price    category    quantity
 112345  It        New Lib      $10      Horror      2
 234562  The Hob   Puffin       $20      Fiction     5

Author table

    auth_id    auth_name
 1          Stephen King
 2          Tolkien

Written_by table

    isbn     auth_id
112345    1

Sample output

isbn    name      publisher    price    category    quantity    author
 112345  It        New Lib      $10      Horror      2           Stephen King
 234562  The Hob   Puffin       $20      Fiction     5           null

The above query will return only the book named "It" and will ignore "The Hobbit" since there is no author linked to that book in the written_by table, but I want both the books in the result table with author as null for the book that has no author linked to it

答:
The below query will select all the books along with the author name, and will be null for those books which are not linked.

```<code>select b.isbn, b.name, b.publisher, b.price, b.category, b.quantity,
a.auth_name as authors
from book b
left outer join written_by w on b.isbn=w.isbn
left outer join author a on a.auth_id=w.auth_id
</code>```

is that the one you are looking for?

Body:
I have three tables named book (isbn, name, publisher, price, category, quantity), author (auth_id, auth_name) and written_by(isbn,auth_id). I am joining all three tables but in the result, I want all the books even whose author is not entered in the database. I have written the following query

select b.isbn, b.name, b.publisher, b.price, b.category, b.quantity,
group_concat(a.auth_name) as authors
from book b
left outer join written_by w on b.isbn=w.isbn
left outer join author a on a.auth_id=w.auth_id
group by b.isbn
having  authors like '%';

The above query returns only the books who have authors linked to them in the written_by table. I want all the books including the ones with no authors in the database.
How do I join these three tables in such a way?
EDIT:
Sample Data
Book table

    isbn    name      publisher    price    category    quantity
 112345  It        New Lib      $10      Horror      2
 234562  The Hob   Puffin       $20      Fiction     5

Author table

    auth_id    auth_name
 1          Stephen King
 2          Tolkien

Written_by table

    isbn     auth_id
112345    1

Sample output

isbn    name      publisher    price    category    quantity    author
 112345  It        New Lib      $10      Horror      2           Stephen King
 234562  The Hob   Puffin       $20      Fiction     5           null

The above query will return only the book named "It" and will ignore "The Hobbit" since there is no author linked to that book in the written_by table, but I want both the books in the result table with author as null for the book that has no author linked to it

Body:
The below query will select all the books along with the author name, and will be null for those books which are not linked.

select b.isbn, b.name, b.publisher, b.price, b.category, b.quantity,
a.auth_name as authors
from book b
left outer join written_by w on b.isbn=w.isbn
left outer join author a on a.auth_id=w.auth_id

is that the one you are looking for?


问:
How to make 0 in all column in a specific table where value is null using MSSQL
Let the table name is "MyTable"

My current data looks like:

Following, I need after a query on above table:

Actually I need to update all column where value is "NULL", in a single query.

答:
```<code>   declare @tableName varchar(30)
    set @tableName='MyTable'

    DECLARE @MakeString AS NVARCHAR(MAX)
    SELECT @MakeString=
    (SELECT cname + ',' AS 'data()'
    FROM ( select  COLUMN_NAME +'= isnull(['+COLUMN_NAME+'],0)' as cname from INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = @tableName
                )  as ccc
    FOR XML PATH(''))

    SET @MakeString = LEFT(@MakeString, LEN(@MakeString) - 1)

    DECLARE @Sql AS NVARCHAR(MAX)
    set @Sql='Update '+@tableName+'
    SET '+@MakeString+''

    EXEC(@Sql);
</code>```


问:
IDE0006 warning and many others on new Cross Platform Xamarin app with a fresh install of Visual Studio
I just installed Visual Studio 2017 on a PC running Windows 10, and created a Cross Platform Xamarin app (Blank and PLC) called "trial". Right off the bat, the following warning came up in the Errors box:

```<code>IDE0006 - Error encountered while loading the project. Some project pfeatures, such as full solution alaysisis for the failed project and projects that depend on it, have been disabled.

To see what caused the issue, please try below.

1. Close Visual Studio
2. Open a Visual Studio Developer Command Prompt
3. Set environment variable "TraceDesignTime" to true (set TraceDesignTime=true)
4. Delete .vs directory/.suo file
5. Restart VS from the command prompt you set the environment variable (devenv)
6. Open the solution
7. Check 'C:\Users\Me\AppData\Local\Temp\\trial.Android_*.designtime.log' and look for the failed tasks (FAILED)
</code>```

Since then, I've tried creating many other apps, all of which start with at least that warning, and usually more. Searching for the other errors yields no results - searching for the IDE0006 one yields this and a few suggestions to update packages, but I tried all of them, including various combinations of updating/reinstalling/using previous versions of packages, deleting the "System.ObjectModel" reference, restarting, cleaning, and rebuilding, and the errors are still there. I even tried uninstalling and reinstalling Visual Studio, but nothing changed.

Weirder still, when I run my Android project despite the errors, nothing happens. On my first install of Visual Studio, an Android emulator popped up -
 the screen was completely black which I doubt is expected behavior but at least the emulator was there - but ever since the reinstall, nothing at all happens, and all errors and warnings just disappear from the Error box, so the box is totally empty (although the top bar still displays "1 Warnings"), and I can't get them to come back. I set up my Android project exactly as prescribed here.

I started to follow the 7 steps outlined in the error, but I couldn't find any ".vs" directory or ".suo" file, and then it occurred to me that I didn't know what I was doing and I didn't want to risk screwing up Visual Studio even further (I can't find any references to the 7 steps on Google and they also contain misspellings, so they feel outdated/sketchy). Anyone have any experience/insight on these steps?

Here are some of the other warnings that keep popping up - I assume/hope that all the warnings are caused by the same fundamental error, but I can't find any record of anyone else encountering any but the one above.

```<code>Cannot resolve Assembly or Windows Metadata file 'System.Runtime.dll'   trial.UWP   C:\Users\User\source\repos\trial\trial\trial.UWP\trial.UWP.csproj

Type universe cannot resolve assembly: System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=jf98hs8fsihso9. trial.UWP

Could not load assembly 'trial, Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?   trial.Android

The "ResolveLibraryProjectImports" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load assembly 'trial, Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'trial.dll'
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName)
   at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Extract(DirectoryAssemblyResolver res, ICollection`1 jars, ICollection`1 resolvedResourceDirectories, ICollection`1 resolvedAssetDirectories, ICollection`1 resolvedEnvironments)
   at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() trial.Android
</code>```

I've been tearing my hair out over this. I was really looking forward to learning Xamarin but I literally haven't been able to code a single line yet. What could be going on?? It's like my install is corrupted or something, but I don't see how that is possible, especially since I downloaded it twice, from the official site.

UPDATE

I tried the solution given here, namely building the Android project, unloading it then reloading it. All my warnings disappeared when I built it, but when I unloaded it I got this single error (which has appeared sporadically before), which remained.

```<code>The referenced component 'System.ObjectModel' could not be found.
</code>```

(I've already removed "System.ObjectModel" from the list of references, which worked once on that error, but since then it's recurred). When I ran the app, it said "There were deployment errors, would you like to continue?" like it always does, I clicked "yes", and once again nothing happened. The single warning remained, even when the build the Android project again.

UPDATE 2

I created a new project and uploaded it to Github to demonstrate the problem: https://github.com/joeymorano/newfailure

UPDATE 3

I  tried:

```<code>1.) Cleaning
2.) Deleting all `bin` and `obj` files
3.) Rebuilding
</code>```

but I still have errors. To be sure, I created a new project and tried the same steps, and three errors went away, but there's still the IDE0006 error. I uploaded that project too: https://github.com/joeymorano/stack

UPDATE 4

I still have the following errors this app: https://github.com/joeymorano/newfailure

```<code>Error   CS0103  The name 'InitializeComponent' does not exist in the current context

Warning     The referenced component 'System.ObjectModel' could not be found.
</code>```

Here's the Build Diagnostics, with the build verbosity set to Normal (it was too long to post here so I made a Google doc - Warning, it really is ridiculously long): https://docs.google.com/document/d/1qUJDdjNNOBqhS_Sp9pvH6ipLx67l5fgskRX4ltluxM8/edit?usp=sharing

答:
This isn't my work, but I found something similar on GitHub. https://github.com/dotnet/roslyn/issues/17667

From Pilchie

I just took a look and I see these errors:

```<code>Severity    Code    Description Project File    Line    Suppression State
Warning IDE0006 Error encountered while loading the project. Some project features, such as full solution analysis for the failed project and projects that depend on it, have been disabled.   Monitoramentos      1   Active
Warning     The "XamlCTask" task could not be instantiated from "D:\KevinPi\Downloads\Monitoramentos\Monitoramentos\packages\Xamarin.Forms.2.3.3.193\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+Xamarin.iOS10+xamarinmac20\Xamarin.Forms.Build.Tasks.dll". Could not load file or assembly 'Xamarin.Forms.Build.Tasks, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515) Monitoramentos
Warning     The "XamlCTask" task has been declared or used incorrectly, or failed during construction. Check the spelling of the task name and the assembly name.   Monitoramentos
</code>```

After I deleted the packages\Xamarin.Forms.2.3.3.193\ and did a new restore from NuGet, things worked as expected. I suspect a file in the packages directory is corrupt somehow.

Body:
I just installed Visual Studio 2017 on a PC running Windows 10, and created a Cross Platform Xamarin app (Blank and PLC) called "trial". Right off the bat, the following warning came up in the Errors box:

IDE0006 - Error encountered while loading the project. Some project pfeatures, such as full solution alaysisis for the failed project and projects that depend on it, have been disabled.

To see what caused the issue, please try below.

1. Close Visual Studio
2. Open a Visual Studio Developer Command Prompt
3. Set environment variable "TraceDesignTime" to true (set TraceDesignTime=true)
4. Delete .vs directory/.suo file
5. Restart VS from the command prompt you set the environment variable (devenv)
6. Open the solution
7. Check 'C:\Users\Me\AppData\Local\Temp\\trial.Android_*.designtime.log' and look for the failed tasks (FAILED)

Since then, I've tried creating many other apps, all of which start with at least that warning, and usually more. Searching for the other errors yields no results - searching for the IDE0006 one yields this and a few suggestions to update packages, but I tried all of them, including various combinations of updating/reinstalling/using previous versions of packages, deleting the "System.ObjectModel" reference, restarting, cleaning, and rebuilding, and the errors are still there. I even tried uninstalling and reinstalling Visual Studio, but nothing changed.

Weirder still, when I run my Android project despite the errors, nothing happens. On my first install of Visual Studio, an Android emulator popped up -
 the screen was completely black which I doubt is expected behavior but at least the emulator was there - but ever since the reinstall, nothing at all happens, and all errors and warnings just disappear from the Error box, so the box is totally empty (although the top bar still displays "1 Warnings"), and I can't get them to come back. I set up my Android project exactly as prescribed here.

I started to follow the 7 steps outlined in the error, but I couldn't find any ".vs" directory or ".suo" file, and then it occurred to me that I didn't know what I was doing and I didn't want to risk screwing up Visual Studio even further (I can't find any references to the 7 steps on Google and they also contain misspellings, so they feel outdated/sketchy). Anyone have any experience/insight on these steps?

Here are some of the other warnings that keep popping up - I assume/hope that all the warnings are caused by the same fundamental error, but I can't find any record of anyone else encountering any but the one above.

Cannot resolve Assembly or Windows Metadata file 'System.Runtime.dll'   trial.UWP   C:\Users\User\source\repos\trial\trial\trial.UWP\trial.UWP.csproj

Type universe cannot resolve assembly: System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=jf98hs8fsihso9. trial.UWP

Could not load assembly 'trial, Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?   trial.Android

The "ResolveLibraryProjectImports" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load assembly 'trial, Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'trial.dll'
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName)
   at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Extract(DirectoryAssemblyResolver res, ICollection`1 jars, ICollection`1 resolvedResourceDirectories, ICollection`1 resolvedAssetDirectories, ICollection`1 resolvedEnvironments)
   at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() trial.Android

I've been tearing my hair out over this. I was really looking forward to learning Xamarin but I literally haven't been able to code a single line yet. What could be going on?? It's like my install is corrupted or something, but I don't see how that is possible, especially since I downloaded it twice, from the official site.

UPDATE

I tried the solution given here, namely building the Android project, unloading it then reloading it. All my warnings disappeared when I built it, but when I unloaded it I got this single error (which has appeared sporadically before), which remained.

The referenced component 'System.ObjectModel' could not be found.

(I've already removed "System.ObjectModel" from the list of references, which worked once on that error, but since then it's recurred). When I ran the app, it said "There were deployment errors, would you like to continue?" like it always does, I clicked "yes", and once again nothing happened. The single warning remained, even when the build the Android project again.

UPDATE 2

I created a new project and uploaded it to Github to demonstrate the problem: https://github.com/joeymorano/newfailure

UPDATE 3

I  tried:

1.) Cleaning
2.) Deleting all `bin` and `obj` files
3.) Rebuilding

but I still have errors. To be sure, I created a new project and tried the same steps, and three errors went away, but there's still the IDE0006 error. I uploaded that project too: https://github.com/joeymorano/stack

UPDATE 4

I still have the following errors this app: https://github.com/joeymorano/newfailure

Error   CS0103  The name 'InitializeComponent' does not exist in the current context

Warning     The referenced component 'System.ObjectModel' could not be found.

Here's the Build Diagnostics, with the build verbosity set to Normal (it was too long to post here so I made a Google doc - Warning, it really is ridiculously long): https://docs.google.com/document/d/1qUJDdjNNOBqhS_Sp9pvH6ipLx67l5fgskRX4ltluxM8/edit?usp=sharing

Body:
This isn't my work, but I found something similar on GitHub. https://github.com/dotnet/roslyn/issues/17667

From Pilchie

I just took a look and I see these errors:

Severity    Code    Description Project File    Line    Suppression State
Warning IDE0006 Error encountered while loading the project. Some project features, such as full solution analysis for the failed project and projects that depend on it, have been disabled.   Monitoramentos      1   Active
Warning     The "XamlCTask" task could not be instantiated from "D:\KevinPi\Downloads\Monitoramentos\Monitoramentos\packages\Xamarin.Forms.2.3.3.193\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+Xamarin.iOS10+xamarinmac20\Xamarin.Forms.Build.Tasks.dll". Could not load file or assembly 'Xamarin.Forms.Build.Tasks, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515) Monitoramentos
Warning     The "XamlCTask" task has been declared or used incorrectly, or failed during construction. Check the spelling of the task name and the assembly name.   Monitoramentos

After I deleted the packages\Xamarin.Forms.2.3.3.193\ and did a new restore from NuGet, things worked as expected. I suspect a file in the packages directory is corrupt somehow.


问:
Why "C:\Program Files" used as default. Is there any violations or degradation in performance if we change it?
Why does Microsoft recommend "C:\Program Files" for default installation destination? Are there any specific reason for that? And if I change the location is that going to effect the performance of the system and the application?</p>

答:
Since it is the default, lots of things in Windows just assume that's what it is.

It's not a performance issue, but a user changing it might break things unexpectedly.  It might be a good thing to test for.

You should definitely refer to the %ProgramFiles% environment variable in your program rather than a hard-coded path.

OwnerDisplayName: Maharajan

LastEditorDisplayName: bdukes

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Darcy Casselman


问:
How to determine if stdin is empty
I have a little project to do for school. We have a program that generate a maze.
We can put arguments to generate a different maze or even get it as a picture.

We call it like that :

./test

or

./test --arg1 val --arg2 val --etc

We have been asked to parse the argument into a file that we put in stdin like that :

./test  < args.txt

Now I must be able to call the program with every one of the lines above. The line with the arguments work, the mine with the program in stdin works, but the line without anything doesnt work anymore.

So i should check if the user as sent some file in stdin i call the program with a file, else i call it the normal way. I tried with feof but it can't work since stdin won't have anything in not even eof.
When i call the program without arguments or file it waits for the user to write something, which it shouldnt.

Basically my code should look like that

```<code>int main()
{
    int v;
    if (stdin!=NULL)) { //if a file has been passed "./test <test.txt"
        scanf("%d",&v);
    }
    else {  //if no files has been passed "./test "
        printf("no file forwarded \n");
        return 1;
    }
    if (v<50) {
        printf("you drive slow\n");
    }
    else {
        printf("you drive fast\n");
    }
    return 0;
}
</code>```

But obviously (stdin != NULL) doesn't work. So is there a way to check if stdin has something in?
I asked my classmate, one of them told me something about useing fgetc to get the first char and then put it back if there is really a char but when i try to use fgetc, if there is no char it waits for me to put a char in.

So how could I check if stdin is empty or if there is a file into it (without using new libraries)?

Thanks you in advance
have a good day

If i am not completely clear please tell it to me i am not a native speaker and i have a bit of difficulties since it's a technical question

答:
Okay i found a solution it is not the best one since i shouldn't use external libraries but for now it works, i hope it will be usefull for someone :

feof was a good idea but indeed it doesn't work, the reason is stdin will never have EOF in it if you worte nothing in it. So if you provide a file since you must parse the file when there is no file it will try to parse what the user types in.

first you must include

```<code>#include <unistd.h>
</code>```

then

```<code>int v;
    if (!isatty(STDIN_FILENO)) //if stdin is not a terminal (a file was provided)
    {
         scanf("%d",&v);
    }
    else { //if stdin is a terminal (no file provided)
        printf("no file forwarded \n");
        return 1;
    }
    if (v<50){printf("you drive slow\n");}
    else {printf("you drive fast\n");}
    return 0;
</code>```

it will check if stdin is a terminal or not.
This solution works but if someone has one without the use of external libraries it would be super cool !

ContentLicense: CC BY-SA 4.0

Title: How to determine if stdin is empty

Body:
I have a little project to do for school. We have a program that generate a maze.
We can put arguments to generate a different maze or even get it as a picture.

We call it like that :

./test

or

./test --arg1 val --arg2 val --etc

We have been asked to parse the argument into a file that we put in stdin like that :

./test  < args.txt

Now I must be able to call the program with every one of the lines above. The line with the arguments work, the mine with the program in stdin works, but the line without anything doesnt work anymore.

So i should check if the user as sent some file in stdin i call the program with a file, else i call it the normal way. I tried with feof but it can't work since stdin won't have anything in not even eof.
When i call the program without arguments or file it waits for the user to write something, which it shouldnt.

Basically my code should look like that

int main()
{
    int v;
    if (stdin!=NULL)) { //if a file has been passed "./test <test.txt"
        scanf("%d",&v);
    }
    else {  //if no files has been passed "./test "
        printf("no file forwarded \n");
        return 1;
    }
    if (v<50) {
        printf("you drive slow\n");
    }
    else {
        printf("you drive fast\n");
    }
    return 0;
}

But obviously (stdin != NULL) doesn't work. So is there a way to check if stdin has something in?
I asked my classmate, one of them told me something about useing fgetc to get the first char and then put it back if there is really a char but when i try to use fgetc, if there is no char it waits for me to put a char in.

So how could I check if stdin is empty or if there is a file into it (without using new libraries)?

Thanks you in advance
have a good day

If i am not completely clear please tell it to me i am not a native speaker and i have a bit of difficulties since it's a technical question

Body:
Okay i found a solution it is not the best one since i shouldn't use external libraries but for now it works, i hope it will be usefull for someone :

feof was a good idea but indeed it doesn't work, the reason is stdin will never have EOF in it if you worte nothing in it. So if you provide a file since you must parse the file when there is no file it will try to parse what the user types in.

first you must include

#include <unistd.h>

then

int v;
    if (!isatty(STDIN_FILENO)) //if stdin is not a terminal (a file was provided)
    {
         scanf("%d",&v);
    }
    else { //if stdin is a terminal (no file provided)
        printf("no file forwarded \n");
        return 1;
    }
    if (v<50){printf("you drive slow\n");}
    else {printf("you drive fast\n");}
    return 0;

it will check if stdin is a terminal or not.
This solution works but if someone has one without the use of external libraries it would be super cool !


问:
Button next to collapsible moves with text, should be on the bottom
I've been learning bootstrap so I've been making a website to practice with it. I have a large red collapsible which displays some text when clicked on. I have a button next to it that moves below the text when clicked on, when I would like it to be on the bottom of the red button, and when the collapsible is clicked on, have the text come between the two buttons. I'm not sure how to move the button below and have the text come between.

EDIT: Bonus points if you can help me figure out why the "X" button on the modal is left of modal texts

https://codepen.io/anon/pen/Nwajax

HTML

```<code><!DOCTYPE html>
<html>
  <html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>

</head>
<body>

<link rel="stylesheet" href="test.css">
<script src="test.js"></script>
<div class="container-fluid" id="main">
  <h1 id="main_head">This is a heading</h1>

  <div class="row">

    <div class="col-sm-2 div1">
      <div class="btn-group-vertical">
        <h4>These buttons don't work yet because I haven't implemented anything yet</h4>
        <button type="button" class="btn btn-warning">Button 1</button>
        <button type="button" class="btn btn-info">Button 2</button>
        <button type="button" class="btn btn-success">Button 3</button>
      </div>
    </div>

    <div class="col-sm-8 div2">
      <button data-toggle="collapse" data-target="#main_collapse" class="btn-danger" id="coll_button">Collapsible</button>

      <div id="main_collapse" class="collapse">
        <h1>Some pretty neat random text that just appears when you click on the collapse thing</h1>
      </div>
      <!--Start modal-->
      <!-- Trigger the modal with a button -->
      <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

      <!-- Modal -->
      <div id="myModal" class="modal fade" role="dialog">
        <div class="modal-dialog">

          <!-- Modal content-->
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal">×</button>
              <h4 class="modal-title">Modal Header</h4>
            </div>
            <div class="modal-body">
              <p>Some text in the modal.</p>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
          </div>

        </div>
      </div>
      <!--End modal-->
    </div>

    <div class="col-sm-2 div3">
      <div class="container">
        <h4>This is a dropdown menu</h4>
        <div class="dropdown">
        <button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown">Click the dropdown menu
        <span class="caret"></span></button>
          <ul class="dropdown-menu drop1">
            <li class="drop1"><a href="#">Dropdown 1</a></li>
            <li class="drop1"><a href="#">Dropdown 2</a></li>
            <li class="drop1"><a href="#">Dropdown 3</a></li>
          </ul>
        </div>
      </div>
    </div>

  </div>

  <div id="main_foot" class="container-fluid"><h1>This is a footer</h1>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">
</script>
</body>
</html>
</code>```

Here is a codepen (view should be changed to have display on the right/left, bootstrap is a bit weird with it) Thanks for your help.

答:
Joel,

The button next to the collapsible is disappearing from view when you click on the collapsible because the size of the text in between is h1. Change it to a smaller size for eg. h6

```<code><h6>Some pretty neat random text that just appears when you click on the
collapse thing</h6>
</code>```

Also, the reason why you are seeing the close button on the model before the heading is because of way the markup is constructed. you have the markup for the button first followed by the heading change it to heading first followed by button like this:

```<code><h4 class="modal-title">Modal Header</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</code>```

Body:
I've been learning bootstrap so I've been making a website to practice with it. I have a large red collapsible which displays some text when clicked on. I have a button next to it that moves below the text when clicked on, when I would like it to be on the bottom of the red button, and when the collapsible is clicked on, have the text come between the two buttons. I'm not sure how to move the button below and have the text come between.

EDIT: Bonus points if you can help me figure out why the "X" button on the modal is left of modal texts

https://codepen.io/anon/pen/Nwajax

HTML

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

<link rel="stylesheet" href="test.css">

This is a heading

These buttons don't work yet because I haven't implemented anything yet

        <button type="button" class="btn btn-warning">Button 1</button>
        <button type="button" class="btn btn-info">Button 2</button>
        <button type="button" class="btn btn-success">Button 3</button>

      <button data-toggle="collapse" data-target="#main_collapse" class="btn-danger" id="coll_button">Collapsible</button>

Some pretty neat random text that just appears when you click on the collapse thing

      <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

              <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

This is a dropdown menu

        <button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown">Click the dropdown menu
        </button>

Dropdown 1

Dropdown 2

Dropdown 3

This is a footer

Here is a codepen (view should be changed to have display on the right/left, bootstrap is a bit weird with it) Thanks for your help.

Body:
Joel,

The button next to the collapsible is disappearing from view when you click on the collapsible because the size of the text in between is h1. Change it to a smaller size for eg. h6

<h6>Some pretty neat random text that just appears when you click on the
collapse thing</h6>

Also, the reason why you are seeing the close button on the model before the heading is because of way the markup is constructed. you have the markup for the button first followed by the heading change it to heading first followed by button like this:

<h4 class="modal-title">Modal Header</h4>
<button type="button" class="close" data-dismiss="modal">&times;</button>


问:
GRID items right aligned
I'm playing with "grid layout" and I have a "section" with 100% width. This is display: grid.

Inside it there are 4 other divs that I would like to appear on the right side instead of the left side.

Here is my code:

.fullWidth {
  display: grid;
  grid-template: "it01 it02 it03 it04 it05";
  grid-template-rows: 40px;
  grid-template-columns: 40px 40px 40px 200px 40px;
  background: orange;
}

.item01 {
  grid-area: it01;
  background: lime;
}

.item02 {
  grid-area: it02;
  background: blue;
}

.item03 {
  grid-area: it03;
  background: red;
}

.item04 {
  grid-area: it04;
  background: yellow;
}

.item05 {
  grid-area: it05;
  background: tomato;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="fullWidth">
  <div class="item01"> </div>
  <div class="item02"> </div>
  <div class="item03"> </div>
  <div class="item04"> </div>
  <div class="item05"> </div>
</section></code>```

Here's the fiddle:
https://jsfiddle.net/2mpsuc7c/

答:
Just add:

```<code>.fullWidth {
    justify-content: end;
}
</code>```

Updated snippet:

.fullWidth {
  display: grid;
  grid-template: "it01 it02 it03 it04 it05";
  grid-template-rows: 40px;
  grid-template-columns: 40px 40px 40px 200px 40px;
  background: orange;
  justify-content: end;
}

.item01 {
  grid-area: it01;
  background: lime;
}

.item02 {
  grid-area: it02;
  background: blue;
}

.item03 {
  grid-area: it03;
  background: red;
}

.item04 {
  grid-area: it04;
  background: yellow;
}

.item05 {
  grid-area: it05;
  background: tomato;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="fullWidth">
  <div class="item01"> </div>
  <div class="item02"> </div>
  <div class="item03"> </div>
  <div class="item04"> </div>
  <div class="item05"> </div>
</section></code>```

Updated Fiddle

Title: GRID items right aligned

Body:
I'm playing with "grid layout" and I have a "section" with 100% width. This is display: grid.

Inside it there are 4 other divs that I would like to appear on the right side instead of the left side.

Here is my code:

.fullWidth {
  display: grid;
  grid-template: "it01 it02 it03 it04 it05";
  grid-template-rows: 40px;
  grid-template-columns: 40px 40px 40px 200px 40px;
  background: orange;
}

.item01 {
  grid-area: it01;
  background: lime;
}

.item02 {
  grid-area: it02;
  background: blue;
}

.item03 {
  grid-area: it03;
  background: red;
}

.item04 {
  grid-area: it04;
  background: yellow;
}

.item05 {
  grid-area: it05;
  background: tomato;
}

Here's the fiddle:
https://jsfiddle.net/2mpsuc7c/

Body:
Just add:

.fullWidth {
    justify-content: end;
}

Updated snippet:

.fullWidth {
  display: grid;
  grid-template: "it01 it02 it03 it04 it05";
  grid-template-rows: 40px;
  grid-template-columns: 40px 40px 40px 200px 40px;
  background: orange;
  justify-content: end;
}

.item01 {
  grid-area: it01;
  background: lime;
}

.item02 {
  grid-area: it02;
  background: blue;
}

.item03 {
  grid-area: it03;
  background: red;
}

.item04 {
  grid-area: it04;
  background: yellow;
}

.item05 {
  grid-area: it05;
  background: tomato;
}

<section class="fullWidth">
  <div class="item01"> </div>
  <div class="item02"> </div>
  <div class="item03"> </div>
  <div class="item04"> </div>
  <div class="item05"> </div>
</section>

Updated Fiddle


问:
Violation Long running JavaScript task took xx ms
Recently, I got this kind of warning, and this is my first time getting it:

[Violation] Long running JavaScript task took 234ms
[Violation] Forced reflow while executing JavaScript took 45ms
```
</blockquote>

<p>I'm working on a group project and I have no idea where this is coming from. This never happened before. Suddenly, it appeared when someone else got involved in the project. How do I find what file/function causes this warning? I've been looking for the answer, but mostly about the solution on how to solve it. I can't solve it if I can't even find the source of the problem.</p>

<p>In this case, the warning appears only on Chrome. I tried to use Edge, but I didn't get any similar warnings, and I haven't tested it on Firefox yet.</p>

<p>I even get the error from <code>jquery.min.js</code>:</p>

<blockquote>
  <pre class="lang-none prettyprint-override"><code>[Violation] Handler took 231ms of runtime (50ms allowed)            jquery.min.js:2
</code>```

答:
I found a solution in Apache Cordova source code.
They implement like this:

```<code>var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();
var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); };
</code>```

Simple implementation, but smart way.

Over the Android 4.4, use Promise.
For older browsers, use setTimeout()

Usage:

```<code>nextTick(function() {
  // your code
});
</code>```

After inserting this trick code, all warning messages are gone.

Body:
Recently, I got this kind of warning, and this is my first time getting it:

[Violation] Long running JavaScript task took 234ms
[Violation] Forced reflow while executing JavaScript took 45ms

I'm working on a group project and I have no idea where this is coming from. This never happened before. Suddenly, it appeared when someone else got involved in the project. How do I find what file/function causes this warning? I've been looking for the answer, but mostly about the solution on how to solve it. I can't solve it if I can't even find the source of the problem.

In this case, the warning appears only on Chrome. I tried to use Edge, but I didn't get any similar warnings, and I haven't tested it on Firefox yet.

I even get the error from jquery.min.js:

[Violation] Handler took 231ms of runtime (50ms allowed)            jquery.min.js:2

Body:
I found a solution in Apache Cordova source code.
They implement like this:

var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();
var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); };

Simple implementation, but smart way.

Over the Android 4.4, use Promise.
For older browsers, use setTimeout()

Usage:

nextTick(function() {
  // your code
});

After inserting this trick code, all warning messages are gone.


问:
SQL Substring separation throws conversion error
I have to get the last four digits of credit card number, after separating this by substring function the result throws conversion error. Below is a sample table

```<code>CREATE TABLE REV (MEMO varchar(100),MEMO_TYPE varchar(100))
INSERT REV VALUES ('09999D,xxxxxxxxxxxx0999,xx/xx,   30.27', 'CREDCARD')
INSERT REV VALUES ('09999D,xxxxxxxxxxxx0666,xx/xx,   50.45', 'CREDCARD')
INSERT REV VALUES ('09999D,REVVALS,ALC,   0', 'OTHER')
</code>```

Below is  the query  used

```<code>Select CAST(case when MEMO_TYPE = 'CREDCARD' then
SUBSTRING(MEMO, CHARINDEX(',', MEMO)+1, LEN(MEMO)
-CHARINDEX(',', MEMO-CHARINDEX(',',REVERSE(MEMO))-6)) ELSE null END
as varchar(100))
-- as Cardnumber)
From REV
</code>```

It throws
    Conversion failed when converting the varchar value
    '09999D,xxxxxxxxxxxx0999,xx/xx, 30.27' to data type int.

I'm sure I'm missing something incredibly simple... Anyone care to enlighten?

答: @Gordon is right, you have MEMO - CHARINDEX(...) which is a VARCHAR field minus an INT function result, which would result in the conversion failed message you are seeing.

Body:
I have to get the last four digits of credit card number, after separating this by substring function the result throws conversion error. Below is a sample table

CREATE TABLE REV (MEMO varchar(100),MEMO_TYPE varchar(100))
INSERT REV VALUES ('09999D,xxxxxxxxxxxx0999,xx/xx,   30.27', 'CREDCARD')
INSERT REV VALUES ('09999D,xxxxxxxxxxxx0666,xx/xx,   50.45', 'CREDCARD')
INSERT REV VALUES ('09999D,REVVALS,ALC,   0', 'OTHER')

Below is  the query  used

Select CAST(case when MEMO_TYPE = 'CREDCARD' then
SUBSTRING(MEMO, CHARINDEX(',', MEMO)+1, LEN(MEMO)
-CHARINDEX(',', MEMO-CHARINDEX(',',REVERSE(MEMO))-6)) ELSE null END
as varchar(100))
-- as Cardnumber)
From REV

It throws
    Conversion failed when converting the varchar value
    '09999D,xxxxxxxxxxxx0999,xx/xx, 30.27' to data type int.

I'm sure I'm missing something incredibly simple... Anyone care to enlighten?


问:
Getting the "text" from a script element using Selenium
I'm working on a web scraper, and the site I'm scraping has a script element on the page that looks like this:

```<code><script type="text/javascript">
                        jQuery(window).load(function($) {
                        Morris.Line({
                          element: 'mpr-graph',
                          data: [
                            {'date': '25-04-2017','y':'1.05'},
                            {'date': '25-04-2017','y':'1.50'},
                            ...
</code>```

What I want:

I want to get to the data property of the object passed to Morris.Line so that I can turn the data into something usable.

I've managed to select the correct element as a Selenium WebElement using the surrounding div's id and the tag name script, but now I'm stuck.

Is there a way to get the text of a script element using Selenium? The text property is empty since it only returns the text shown on the page for a given element.

What I've tried:

Since I was able to get the text in the browser console by grabbing the text property of the element, I tried using execute_script.

```<code>script_text = driver.execute_script("return document.getElementById('avg').getElementsByTagName('script');")
</code>```

This returns a WebElement, so we're back to square 1, but at least we know it's working so we can move on to:

```<code>script_text = driver.execute_script("return document.getElementById('avg').getElementsByTagName('script').text;")
</code>```

I thought this might work since it works in the browser console, but Selenium returns nothing.

```<code>script_text = driver.execute_script("return document.getElementById('avg').getElementsByTagName('script').innerHTML;")
</code>```

As above.

答:
You should be able to use an XPath to find the SCRIPT tag based on its contents

```<code>script_text = driver.find_element_by_xpath("//script[contains(.,'mpr-graph')]").text
</code>```

If for some reason that isn't specific enough (more than one SCRIPT tag contains "mpr-graph") then you can adjust it to whatever text is unique among SCRIPT tags.

Body:
You should be able to use an XPath to find the SCRIPT tag based on its contents

script_text = driver.find_element_by_xpath("//script[contains(.,'mpr-graph')]").text

If for some reason that isn't specific enough (more than one SCRIPT tag contains "mpr-graph") then you can adjust it to whatever text is unique among SCRIPT tags.


问:
Message "During startup program terminated with signal SIGKILL" from GDB
I'm having trouble debugging a C++ program on AIX built with GNU tools. When the program runs outside the debugger:

```<code>-bash-4.3$ ./cryptestcwd v
Segmentation fault (core dumped)
</code>```

When the program runs under GDB, the debugger prints the message During startup program terminated with signal SIGKILL, Killed. and exits:

An added wrinkle is, this only happens with an Autotools front-end. It does not happens with our regular GNUmakefile. We supply the same arguments to both Autotools and the GNUmakefile. We are aware Autotools adds additional options and even adds C files to the C++ project, but we have no control over it.

A related question is at During startup program terminated with signal SIGKILL, Killed, but it does not have useful answers. Two other related questions just state that SIGKILL cannot be caught. Also see Debugging program that catches SIGKILL under Linux and Handling signals with gdb.

How can I debug the problem further?

答:
The SIGKILL at startup most likely means that the AIX runtime loader couldn't find some library that the binary links against (a Linux runtime loader produces a more helpful error message when that happens).

You should verify that ldd cryptestcwd doesn't complain about anything.

You could also try to load the core that is produced when you run your program outside of GDB into GDB -- there may be additional clues there (use info shared, where, x/i $pc commands).

Body:
I'm having trouble debugging a C++ program on AIX built with GNU tools. When the program runs outside the debugger:

-bash-4.3$ ./cryptestcwd v
Segmentation fault (core dumped)

When the program runs under GDB, the debugger prints the message During startup program terminated with signal SIGKILL, Killed. and exits:

An added wrinkle is, this only happens with an Autotools front-end. It does not happens with our regular GNUmakefile. We supply the same arguments to both Autotools and the GNUmakefile. We are aware Autotools adds additional options and even adds C files to the C++ project, but we have no control over it.

A related question is at During startup program terminated with signal SIGKILL, Killed, but it does not have useful answers. Two other related questions just state that SIGKILL cannot be caught. Also see Debugging program that catches SIGKILL under Linux and Handling signals with gdb.

How can I debug the problem further?


问:
Redirect to another controller after clicking on the button

Simple Problem:

I have a button and whenever the user will click on this button, I want to redirect him to another action in another controller. How could I do that?!

This code would be in the .html.erb file

```<code><%= form.submit "Create Request"%>
</code>```

Note: i don't want to use link_to! Additionally, I could not use redirect_to in the controller because i used render there.

答:
In your create action within the controller, you can redirect wherever you want after save the  values.
For example:</p>

```<code>def create
  @model = Model.new(permited_params)

  respond_to do |format|
    If @model.save
      format.html { # todo block with redirect }
    end
  end
end
</code>```

Body:
Simple Problem:

I have a button and whenever the user will click on this button, I want to redirect him to another action in another controller. How could I do that?!

This code would be in the .html.erb file

<%= form.submit "Create Request"%>

Note: i don't want to use link_to! Additionally, I could not use redirect_to in the controller because i used render there.

Body:
In your create action within the controller, you can redirect wherever you want after save the  values.
For example:

def create
  @model = Model.new(permited_params)

  respond_to do |format|
    If @model.save
      format.html { # todo block with redirect }
    end
  end
end


问:
How Do I Add A Keystroke To VS 2015 Toolbar
I've found a keystroke that I'd like to create as a button on my Visual Studio toolbar. If it matters, the keystroke is Ctrl+r, Ctrl+t.

This command is not listed in the "Add/Remove Buttons => Customize => Toolbar => Add Command" dialog.

Does anyone know how to add a toolbar button based on a keystroke?

答: You can't add a keystroke to the VS toolbar. So, first you have to find the command name in Visual Studio keyboard options:


问:
CodeContracts: Possibly calling a method on a null reference 'this.Master'
If I have a basic master page and content page and I want to use some property or method of the master page from the content page, such as:

```<code>string something = this.Master.MasterPageFile;
</code>```

Code Contracts static analysis will complain with:

```<code>warning : CodeContracts: Possibly calling a method on a null reference 'this.Master'
</code>```

How can I get Code Contracts to stop complaining whenever I want to access the master page?

R.

[Edit]

Take a look at this?

```<code>public partial class Manage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Master.ShowFeedback("Test.", true);
    }

   [ContractInvariantMethod]
   private void ObjectInvariants()
   {
       Contract.Invariant(this.Master != null);
   }
}
</code>```

I don't want to have to do the following every time I want to call Showfeedback():

```<code>Contract.Assume(this.Master != null)
this.Master.ShowFeedback("Test.", true);
</code>```

Does that make sense?

答:
You can add it as an invariant to your class:</p>

```<code>[ContractInvariantMethod]
private void Invariants()
{
    Contract.Invariant(Master != null);
}
</code>```

Body:
If I have a basic master page and content page and I want to use some property or method of the master page from the content page, such as:

string something = this.Master.MasterPageFile;

Code Contracts static analysis will complain with:

warning : CodeContracts: Possibly calling a method on a null reference 'this.Master'

How can I get Code Contracts to stop complaining whenever I want to access the master page?

R.

[Edit]

Take a look at this?

public partial class Manage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Master.ShowFeedback("Test.", true);
    }

   [ContractInvariantMethod]
   private void ObjectInvariants()
   {
       Contract.Invariant(this.Master != null);
   }
}

I don't want to have to do the following every time I want to call Showfeedback():

Contract.Assume(this.Master != null)
this.Master.ShowFeedback("Test.", true);

Does that make sense?

Body:
You can add it as an invariant to your class:

[ContractInvariantMethod]
private void Invariants()
{
    Contract.Invariant(Master != null);
}


问:
Sum up values received from webform?
Below is a print out of what python receives from a web form using cherrypy, I would like to add up all the values of "asset_cost_x"  where x is a dynamic number, provided that the corresponding value of "asset_allocation_capex_x" equals 'on'.

How could this be done as neat as possible?

I am currently trying the following code, however this code is just an indication

Code:

```<code># I would like to get python to determone the total number so that can set
# the (1,19) automatically
for x in range(1,19):
    try:
        i1 = "asset_cost_" + str(x)
        i2 = "asset_allocation_capex_" + str(x)
        i3 = "asset_allocation_opex_" + str(x)
        #kwarg1 = kwargs[i1]
        #kwarg2 = kwargs[i2]
        kwarg3 = kwargs[i3]
        kwarg3i = kwargs.get(i3)
        #if kwarg2 == 'on':
        #   print "Capex"
        if kwarg3i:
            if kwarg3 == 'on':
                print "Opex"
        #print kwarg1
    except:
        print "Unexpected error:", sys.exc_info()[0]
</code>```

webform printout:

{'asset_description_9': u'Operations and Maintenance Manuals /
As-Installed Drawings', 'asset_description_8': u'12 Months Defects
Liability and Maintenance', 'checkbox-create_f06': u'off', 'old_asset_
d_1': u'', 'WO': u'1', 'asset_description_5': u'Level 4 Works',
'asset_description_4': u'Level 8 Works', 'asset_description_7': u'Pre
and Post Works Building 2 Smoke Management System Testing (incl re
porting and fire matrix updating)', 'asset_description_6': u'NSW Long
Service Levy', 'project_manager': u'contractors', 'asset_desc_8':
u'Structural', 'new_asset_s_1': u'', 'pc_date': u'2017-07-30', '
asset_desc_1': u'Structural', 'F06_yes_33': u'on', 'F06_yes_34':
u'on', 'asset_desc_4': u'Structural', 'asset_desc_7': u'Project',
'asset_desc_6': u'Service', 'discipline': u'BW', 'new_asset_w_1': u''
, 'new_asset_mo_1': u'', 'new_asset_ams_1': u'',
'outstanding_notaffecting_d_1': u'', 'F06_yes_22': u'on',
'asset_description_1': u'Level 9 Works', 'drawing-n-1': u'',
'drawing-s-1': u'', 'F06_yes_8':  u'on', 'F06_yes_9': u'on',
'F06_yes_4': u'on', 'F06_yes_5': u'on', 'new_asset_ma_1': u'',
'F06_yes_7': u'on', 'F06_yes_1': u'on', 'F06_yes_2': u'on',
'F06_yes_3': u'on', 'old_asset_ma_1': u'', 'const ruction_manager':
u'Dane Wilson', 'F06_no_48': u'on', 'outstanding_affecting_r_1': u'',
'new_asset_d_1': u'', 'old_asset_mo_1': u'', 'F06_yes_25': u'on',
'F06_yes_24': u'on', 'F06_yes_23': u'on', 'old
_asset_s_1': u'', 'F06_yes_21': u'on', 'asset_desc_9': u'Handover', 'outstanding_affecting_date_1': u'', 'F06_yes_39': u'on', 'd_c':
u'on', 'F06-c-48': u'', 'F06-c-45': u'', 'F06-c-44': u'', 'F06-c-47 ':
u'', 'contractor_list': u'contractors', 'F06-c-41': u'', 'F06-c-40':
u'', 'F06-c-43': u'', 'F06-c-42': u'', 'F06_yes_30': u'on',
'F06-c-22': u'', 'F06-c-21': u'', 'F06-c-20': u'', 'F06-c-34': u'',
'outstanding_notaffecting_date_1': u'', 'asset_desc_5': u'Structural',
'F06_na_6': u'on', 'F06_yes_35': u'on', 'asset_cost_19': u'10500.0',
'asset_cost_18': u'104773.76', 'F06_yes_36': u'on', 'asset_c ost_11':
u'34100.64', 'asset_cost_10': u'34100.64', 'asset_cost_13':
u'10080.0', 'asset_cost_12': u'34100.64', 'asset_cost_15':
u'34100.64', 'asset_cost_14': u'34100.64', 'asset_cost_17':
u'83279.83',  'asset_cost_16': u'34100.64',
'outstanding_notaffecting_r_1': u'', 'project_description':
u'Haymarket - Divestment of Carpark', 'F06_yes_42': u'on', 'F06-c-38':
u'', 'F06-c-39': u'', 'F06_na_17': u'o n', 'F06-c-30': u'',
'F06-c-31': u'', 'F06-c-32': u'', 'F06-c-33': u'', 'F06_na_19': u'on',
'F06_na_18': u'on', 'F06-c-36': u'', 'foxtrot': u'off', 'planner': u'
Ken Wenham', 'F06_yes_41': u'on', 'F06
_yes_40': u'on', 'F06_yes_43': u'on', 'checkbox-rpc-status': u'off', 'F06_yes_45': u'on', 'F06_yes_44': u'on', 'F06_yes_47': u'on',
'F06_yes_46': u'on', 'outstanding_affecting_d_1': u'', 'asset_alloca
tion_capex_18': u'on', 'asset_allocation_capex_19': u'on',
'new_asset_v_1': u'', 'asset_allocation_capex_14': u'on',
'asset_allocation_capex_15': u'on', 'asset_allocation_capex_16':
u'on', 'asset_allo cation_capex_17': u'on',
'asset_allocation_capex_10': u'on', 'asset_allocation_capex_11':
u'on', 'asset_allocation_capex_12': u'on',
'asset_allocation_capex_13': u'on', 'asset_desc_11': u'Structural',
'asset_desc_10': u'Structural', 'asset_desc_13': u'Structural',
'asset_desc_12': u'Structural', 'asset_desc_15': u'Structural',
'asset_desc_14': u'Structural', 'asset_desc_17': u'Structural',
'asset_ desc_16': u'Structural', 'asset_desc_19': u'Structural',
'asset_desc_18': u'Structural', 'F06-c-29': u'', 'F06-c-28': u'',
'asset_allocation_capex_8': u'on', 'asset_allocation_capex_9': u'on',
'F06-c- 23': u'', 'asset_allocation_capex_7': u'on',
'asset_allocation_capex_4': u'on', 'asset_allocation_capex_5': u'on',
'F06-c-27': u'', 'F06-c-26': u'', 'F06-c-25': u'', 'F06-c-24': u'',
'asset_cost_1': u '34100.64', 'asset_cost_5': u'34100.64',
'asset_cost_4': u'34100.64', 'asset_cost_7': u'6089.44',
'asset_cost_6': u'2070.0', 'asset_cost_9': u'12096.0', 'asset_cost_8':
u'13661.76', 'F06-c-35': u'', ' asset_description_15': u'Level 11
Works', 'asset_description_14': u'Level 7 Works',
'asset_description_17': u'Protection Hoarding and Scaffolding',
'asset_description_16': u'Level 3 Works', 'asset_des cription_11':
u'Level 2 Works', 'asset_description_10': u'Level 6 Works',
'asset_description_13': u'Pre and Post Works Smoke Exhaust Air
Measurement Testing', 'asset_description_12': u'Level 5 Works',
'F06_yes_37': u'on', 'scope': u'klhjk', 'contract_manager': u' Joel
Dixon', 'F06-c-37': u'', 'asset_description_19': u'PC Sums Available
for Project', 'asset_description_18': u'Level 1 / Gnd / Baseme nt
Works', 'address_ID': u'44196', 'Project_Description': u' Divestment
of Carpark', 'new_asset_l_1': u'', 'F06_na_32': u'on', 'F06_na_31':
u'on', 'outstanding_affecting_n_1': u'1', 'asset_number_6': u'
11230101 ', 'date_form_completed': u'', 'F06-c-18': u'', 'F06-c-19':
u'', 'F06-c-16': u'', 'F06-c-17': u'', 'F06-c-14': u'', 'F06-c-15':
u'', 'WAMS_conf_folder': u'off', 'F06-c-13': u'', 'F06-c-10' : u'',
'F06-c-11': u'', 'outstanding_notaffecting_n_1': u'1', 'F06_yes_38':
u'on', 'asset_allocation_capex_1': u'on', 'asset_number_9': u'
11230101 ', 'asset_number_8': u' 11230101 ', 'F06_na_28': u'o n',
'F06_na_29': u'on', 'F06_na_26': u'on', 'F06_na_27': u'on',
'F06_na_20': u'on', 'site': u'Haymarket ', 'asset_number_5': u'
11230101 ', 'asset_number_4': u' 11230101 ', 'F06_yes_11': u'on',
'F06-c
-4': u'', 'F06-c-5': u'', 'F06-c-6': u'', 'old_asset_a_1': u'', 'F06_yes_12': u'on', 'F06-c-1': u'', 'F06-c-2': u'', 'F06-c-3': u'',
'asset_number_7': u' 11230101 ', 'F06-c-8': u'', 'F06-c-9': u'', 'a
sset_number_13': u' 11230101 ', 'asset_number_12': u' 11230101 ',
'asset_number_11': u' 11230101 ', 'asset_number_10': u' 11230101 ',
'asset_number_17': u' 11230101 ', 'asset_number_16': u' 11230101 ' ,
'asset_number_15': u' 11230101 ', 'asset_number_14': u' 11230101 ',
'asset_number_19': u' 11230101 ', 'asset_number_18': u' 11230101 ',
'asset_allocation_opex_6': u'on', 'F06_yes_16': u'on', 'drawin g-d-1':
u'', 'F06-c-12': u'', 'asset_number_1': u' 11230101 ', 'F06_yes_14':
u'on', 'F06-c-7': u'', 'F06_yes_15': u'on', 'F06_yes_13': u'on',
'new_asset_c_1': u'', 'F06_yes_10': u'on', 'PM_contact': u '0404 828
433', 'drawing-i-1': u'', 'sp': u'30060686', 'old_asset_l_1': u'',
'checkbox-create_handover': u'off', 'F06-c-46': u''}

答:
If you have no way of knowing the total number of asset_cost_x items, you could do something like the following to look through the entire dictionary:

```<code>asset_cost_keys = [key for key in kwargs if key.startswith("asset_cost_")]

sum = 0
for asset_cost_key in asset_cost_keys:
    i = asset_cost_key[11:] # 11 = len("asset_cost_")
    capex = kwargs.get("asset_allocation_capex_{}".format(i))
    cost = kwargs.get(asset_cost_key)

    if capex is not None and cost is not None and capex == "on":
        sum += float(cost))
</code>```

So first we make a list called asset_cost_keys, which contains all keys in kwargs that look like asset_cost_x.  Note that this looks through kwargs in its entirety, so if this data is likely to be huge, you may want to look for another way of enumerating all cost items.

Then, for each one, we look for a corresponding asset_allocation_capex_x.  If the value of that is defined, and equal to "on", and the value of the cost is defined, we add the cost to a running total.

Note I haven't run this so there may be typos, but hopefully this should get you what you need.

Title: Sum up values received from webform?

Body:
Below is a print out of what python receives from a web form using cherrypy, I would like to add up all the values of "asset_cost_x"  where x is a dynamic number, provided that the corresponding value of "asset_allocation_capex_x" equals 'on'.

How could this be done as neat as possible?

I am currently trying the following code, however this code is just an indication

Code:

# I would like to get python to determone the total number so that can set
# the (1,19) automatically
for x in range(1,19):
    try:
        i1 = "asset_cost_" + str(x)
        i2 = "asset_allocation_capex_" + str(x)
        i3 = "asset_allocation_opex_" + str(x)
        #kwarg1 = kwargs[i1]
        #kwarg2 = kwargs[i2]
        kwarg3 = kwargs[i3]
        kwarg3i = kwargs.get(i3)
        #if kwarg2 == 'on':
        #   print "Capex"
        if kwarg3i:
            if kwarg3 == 'on':
                print "Opex"
        #print kwarg1
    except:
        print "Unexpected error:", sys.exc_info()[0]

webform printout:

{'asset_description_9': u'Operations and Maintenance Manuals /
As-Installed Drawings', 'asset_description_8': u'12 Months Defects
Liability and Maintenance', 'checkbox-create_f06': u'off', 'old_asset_
d_1': u'', 'WO': u'1', 'asset_description_5': u'Level 4 Works',
'asset_description_4': u'Level 8 Works', 'asset_description_7': u'Pre
and Post Works Building 2 Smoke Management System Testing (incl re
porting and fire matrix updating)', 'asset_description_6': u'NSW Long
Service Levy', 'project_manager': u'contractors', 'asset_desc_8':
u'Structural', 'new_asset_s_1': u'', 'pc_date': u'2017-07-30', '
asset_desc_1': u'Structural', 'F06_yes_33': u'on', 'F06_yes_34':
u'on', 'asset_desc_4': u'Structural', 'asset_desc_7': u'Project',
'asset_desc_6': u'Service', 'discipline': u'BW', 'new_asset_w_1': u''
, 'new_asset_mo_1': u'', 'new_asset_ams_1': u'',
'outstanding_notaffecting_d_1': u'', 'F06_yes_22': u'on',
'asset_description_1': u'Level 9 Works', 'drawing-n-1': u'',
'drawing-s-1': u'', 'F06_yes_8':  u'on', 'F06_yes_9': u'on',
'F06_yes_4': u'on', 'F06_yes_5': u'on', 'new_asset_ma_1': u'',
'F06_yes_7': u'on', 'F06_yes_1': u'on', 'F06_yes_2': u'on',
'F06_yes_3': u'on', 'old_asset_ma_1': u'', 'const ruction_manager':
u'Dane Wilson', 'F06_no_48': u'on', 'outstanding_affecting_r_1': u'',
'new_asset_d_1': u'', 'old_asset_mo_1': u'', 'F06_yes_25': u'on',
'F06_yes_24': u'on', 'F06_yes_23': u'on', 'old
_asset_s_1': u'', 'F06_yes_21': u'on', 'asset_desc_9': u'Handover', 'outstanding_affecting_date_1': u'', 'F06_yes_39': u'on', 'd_c':
u'on', 'F06-c-48': u'', 'F06-c-45': u'', 'F06-c-44': u'', 'F06-c-47 ':
u'', 'contractor_list': u'contractors', 'F06-c-41': u'', 'F06-c-40':
u'', 'F06-c-43': u'', 'F06-c-42': u'', 'F06_yes_30': u'on',
'F06-c-22': u'', 'F06-c-21': u'', 'F06-c-20': u'', 'F06-c-34': u'',
'outstanding_notaffecting_date_1': u'', 'asset_desc_5': u'Structural',
'F06_na_6': u'on', 'F06_yes_35': u'on', 'asset_cost_19': u'10500.0',
'asset_cost_18': u'104773.76', 'F06_yes_36': u'on', 'asset_c ost_11':
u'34100.64', 'asset_cost_10': u'34100.64', 'asset_cost_13':
u'10080.0', 'asset_cost_12': u'34100.64', 'asset_cost_15':
u'34100.64', 'asset_cost_14': u'34100.64', 'asset_cost_17':
u'83279.83',  'asset_cost_16': u'34100.64',
'outstanding_notaffecting_r_1': u'', 'project_description':
u'Haymarket - Divestment of Carpark', 'F06_yes_42': u'on', 'F06-c-38':
u'', 'F06-c-39': u'', 'F06_na_17': u'o n', 'F06-c-30': u'',
'F06-c-31': u'', 'F06-c-32': u'', 'F06-c-33': u'', 'F06_na_19': u'on',
'F06_na_18': u'on', 'F06-c-36': u'', 'foxtrot': u'off', 'planner': u'
Ken Wenham', 'F06_yes_41': u'on', 'F06
_yes_40': u'on', 'F06_yes_43': u'on', 'checkbox-rpc-status': u'off', 'F06_yes_45': u'on', 'F06_yes_44': u'on', 'F06_yes_47': u'on',
'F06_yes_46': u'on', 'outstanding_affecting_d_1': u'', 'asset_alloca
tion_capex_18': u'on', 'asset_allocation_capex_19': u'on',
'new_asset_v_1': u'', 'asset_allocation_capex_14': u'on',
'asset_allocation_capex_15': u'on', 'asset_allocation_capex_16':
u'on', 'asset_allo cation_capex_17': u'on',
'asset_allocation_capex_10': u'on', 'asset_allocation_capex_11':
u'on', 'asset_allocation_capex_12': u'on',
'asset_allocation_capex_13': u'on', 'asset_desc_11': u'Structural',
'asset_desc_10': u'Structural', 'asset_desc_13': u'Structural',
'asset_desc_12': u'Structural', 'asset_desc_15': u'Structural',
'asset_desc_14': u'Structural', 'asset_desc_17': u'Structural',
'asset_ desc_16': u'Structural', 'asset_desc_19': u'Structural',
'asset_desc_18': u'Structural', 'F06-c-29': u'', 'F06-c-28': u'',
'asset_allocation_capex_8': u'on', 'asset_allocation_capex_9': u'on',
'F06-c- 23': u'', 'asset_allocation_capex_7': u'on',
'asset_allocation_capex_4': u'on', 'asset_allocation_capex_5': u'on',
'F06-c-27': u'', 'F06-c-26': u'', 'F06-c-25': u'', 'F06-c-24': u'',
'asset_cost_1': u '34100.64', 'asset_cost_5': u'34100.64',
'asset_cost_4': u'34100.64', 'asset_cost_7': u'6089.44',
'asset_cost_6': u'2070.0', 'asset_cost_9': u'12096.0', 'asset_cost_8':
u'13661.76', 'F06-c-35': u'', ' asset_description_15': u'Level 11
Works', 'asset_description_14': u'Level 7 Works',
'asset_description_17': u'Protection Hoarding and Scaffolding',
'asset_description_16': u'Level 3 Works', 'asset_des cription_11':
u'Level 2 Works', 'asset_description_10': u'Level 6 Works',
'asset_description_13': u'Pre and Post Works Smoke Exhaust Air
Measurement Testing', 'asset_description_12': u'Level 5 Works',
'F06_yes_37': u'on', 'scope': u'klhjk', 'contract_manager': u' Joel
Dixon', 'F06-c-37': u'', 'asset_description_19': u'PC Sums Available
for Project', 'asset_description_18': u'Level 1 / Gnd / Baseme nt
Works', 'address_ID': u'44196', 'Project_Description': u' Divestment
of Carpark', 'new_asset_l_1': u'', 'F06_na_32': u'on', 'F06_na_31':
u'on', 'outstanding_affecting_n_1': u'1', 'asset_number_6': u'
11230101 ', 'date_form_completed': u'', 'F06-c-18': u'', 'F06-c-19':
u'', 'F06-c-16': u'', 'F06-c-17': u'', 'F06-c-14': u'', 'F06-c-15':
u'', 'WAMS_conf_folder': u'off', 'F06-c-13': u'', 'F06-c-10' : u'',
'F06-c-11': u'', 'outstanding_notaffecting_n_1': u'1', 'F06_yes_38':
u'on', 'asset_allocation_capex_1': u'on', 'asset_number_9': u'
11230101 ', 'asset_number_8': u' 11230101 ', 'F06_na_28': u'o n',
'F06_na_29': u'on', 'F06_na_26': u'on', 'F06_na_27': u'on',
'F06_na_20': u'on', 'site': u'Haymarket ', 'asset_number_5': u'
11230101 ', 'asset_number_4': u' 11230101 ', 'F06_yes_11': u'on',
'F06-c
-4': u'', 'F06-c-5': u'', 'F06-c-6': u'', 'old_asset_a_1': u'', 'F06_yes_12': u'on', 'F06-c-1': u'', 'F06-c-2': u'', 'F06-c-3': u'',
'asset_number_7': u' 11230101 ', 'F06-c-8': u'', 'F06-c-9': u'', 'a
sset_number_13': u' 11230101 ', 'asset_number_12': u' 11230101 ',
'asset_number_11': u' 11230101 ', 'asset_number_10': u' 11230101 ',
'asset_number_17': u' 11230101 ', 'asset_number_16': u' 11230101 ' ,
'asset_number_15': u' 11230101 ', 'asset_number_14': u' 11230101 ',
'asset_number_19': u' 11230101 ', 'asset_number_18': u' 11230101 ',
'asset_allocation_opex_6': u'on', 'F06_yes_16': u'on', 'drawin g-d-1':
u'', 'F06-c-12': u'', 'asset_number_1': u' 11230101 ', 'F06_yes_14':
u'on', 'F06-c-7': u'', 'F06_yes_15': u'on', 'F06_yes_13': u'on',
'new_asset_c_1': u'', 'F06_yes_10': u'on', 'PM_contact': u '0404 828
433', 'drawing-i-1': u'', 'sp': u'30060686', 'old_asset_l_1': u'',
'checkbox-create_handover': u'off', 'F06-c-46': u''}

Body:
If you have no way of knowing the total number of asset_cost_x items, you could do something like the following to look through the entire dictionary:

asset_cost_keys = [key for key in kwargs if key.startswith("asset_cost_")]

sum = 0
for asset_cost_key in asset_cost_keys:
    i = asset_cost_key[11:] # 11 = len("asset_cost_")
    capex = kwargs.get("asset_allocation_capex_{}".format(i))
    cost = kwargs.get(asset_cost_key)

    if capex is not None and cost is not None and capex == "on":
        sum += float(cost))

So first we make a list called asset_cost_keys, which contains all keys in kwargs that look like asset_cost_x.  Note that this looks through kwargs in its entirety, so if this data is likely to be huge, you may want to look for another way of enumerating all cost items.

Then, for each one, we look for a corresponding asset_allocation_capex_x.  If the value of that is defined, and equal to "on", and the value of the cost is defined, we add the cost to a running total.

Note I haven't run this so there may be typos, but hopefully this should get you what you need.


问:
Recover from "Fatal error: Uncaught SoapFault exception"
I already have functional code, but I'm currently trying to find ways to break it so that I can find exceptions to catch. The code below connects to a Bluecat/Proteus API and attempts to allocate a DHCP Reservation against a list of IP/MAC combos being uploaded via CSV. Knowing the people who would be using this tool, typos in the IP and/or MAC are possible and there could potentially be hundreds of items to process in a given CSV upload.

To test, I'm passing an IP with an invalid octet and a MAC with the same problem. Unfortunately, I've come across this error type and from what I've searched for, there is no way to gracefully catch and log the error and move on to the next item in the list to be processed.

Here is my code:

```<code><?php
session_start();
$client = new SoapClient("...server with WSDL thingy...");
$client->login($_SESSION['user'], $_SESSION['pass']);

# List of items to process taken from a form upload on a preceeding page
# List saved as array in 'csv'

foreach ($_SESSION['csv'] as $i=>$row) {

try {
$_SESSION['csv'][$i] = array_combine($_SESSION['keys'], $row);

$client->assignIP4Address('5',$_SESSION['csv'][$i]['ip4Address'],$_SESSION['csv'][$i]['macAddress'],'','MAKE_DHCP_RESERVED','');
}

catch (Exception $e) {
#Exception messaging goes here
}
}
?>
</code>```

The specific errors I'm getting are:

Fatal error: Uncaught SoapFault exception: [env:Server] Invalid octet value: 666 in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php:30 Stack trace: #0 C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php(30): SoapClient->__call('assignIP4Addres...', Array) #1 C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php(30): SoapClient->assignIP4Address('5', '10.166.28.666', 'cc:dd:ee:ff:00:...', '', 'MAKE_DHCP_RESER...', '') #2 {main} thrown in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php on line 30

and

SoapFault: Invalid octet value: 666 in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php on line 30

Note that the error kills the script at the invalid IP as it comes first in the list of arguments for the method call to the soap provider. I have no clue what the error for the invalid MAC would be yet, but I'm guessing something similar.

The invalid IP/MAC octets are as such: x.x.x.666 and xx:xx:xx:xx:xx:ZZ

Is there any way to catch this specific type of fatal error and continue processing with the next item in the foreach loop? As I said, there could be hundreds of rows in the source CSV and having the script die at some random place because of a typo would be a pain in the ass.

This question is for PHP 5.6, just to be complete.

答:
```<code>foreach ($_SESSION['csv'] as $i=>$row){

        $_SESSION['csv'][$i] = array_combine($_SESSION['keys'],$row);

        if (filter_var($_SESSION['csv'][$i]['ip4Address'],FILTER_VALIDATE_IP) && filter_var($_SESSION['csv'][$i]['macAddress'],FILTER_VALIDATE_MAC)){
            $client->assignIP4Address('5',$_SESSION['csv'][$i]['ip4Address'],$_SESSION['csv'][$i]['macAddress'],'','MAKE_DHCP_RESERVED','');
        }else{
            // nothing actually it will just move on to then next row
            //you could record the faliur or alert the user if required
        }
    }
</code>```

Try\catch removed as you did not seem to be doing anything with it

Body:
I already have functional code, but I'm currently trying to find ways to break it so that I can find exceptions to catch. The code below connects to a Bluecat/Proteus API and attempts to allocate a DHCP Reservation against a list of IP/MAC combos being uploaded via CSV. Knowing the people who would be using this tool, typos in the IP and/or MAC are possible and there could potentially be hundreds of items to process in a given CSV upload.

To test, I'm passing an IP with an invalid octet and a MAC with the same problem. Unfortunately, I've come across this error type and from what I've searched for, there is no way to gracefully catch and log the error and move on to the next item in the list to be processed.

Here is my code:

<?php
session_start();
$client = new SoapClient("...server with WSDL thingy...");
$client->login($_SESSION['user'], $_SESSION['pass']);

# List of items to process taken from a form upload on a preceeding page
# List saved as array in 'csv'

foreach ($_SESSION['csv'] as $i=>$row) {

try {
$_SESSION['csv'][$i] = array_combine($_SESSION['keys'], $row);

$client->assignIP4Address('5',$_SESSION['csv'][$i]['ip4Address'],$_SESSION['csv'][$i]['macAddress'],'','MAKE_DHCP_RESERVED','');
}

catch (Exception $e) {
#Exception messaging goes here
}
}
?>

The specific errors I'm getting are:

Fatal error: Uncaught SoapFault exception: [env:Server] Invalid octet value: 666 in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php:30 Stack trace: #0 C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php(30): SoapClient->__call('assignIP4Addres...', Array) #1 C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php(30): SoapClient->assignIP4Address('5', '10.166.28.666', 'cc:dd:ee:ff:00:...', '', 'MAKE_DHCP_RESER...', '') #2 {main} thrown in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php on line 30

and

SoapFault: Invalid octet value: 666 in C:\Program Files (x86)\Ampps\www\proteustool\dhcp_reservations.php on line 30

Note that the error kills the script at the invalid IP as it comes first in the list of arguments for the method call to the soap provider. I have no clue what the error for the invalid MAC would be yet, but I'm guessing something similar.

The invalid IP/MAC octets are as such: x.x.x.666 and xx:xx:xx:xx:xx:ZZ

Is there any way to catch this specific type of fatal error and continue processing with the next item in the foreach loop? As I said, there could be hundreds of rows in the source CSV and having the script die at some random place because of a typo would be a pain in the ass.

This question is for PHP 5.6, just to be complete.

Body:
foreach ($_SESSION['csv'] as $i=>$row){

        $_SESSION['csv'][$i] = array_combine($_SESSION['keys'],$row);

        if (filter_var($_SESSION['csv'][$i]['ip4Address'],FILTER_VALIDATE_IP) && filter_var($_SESSION['csv'][$i]['macAddress'],FILTER_VALIDATE_MAC)){
            $client->assignIP4Address('5',$_SESSION['csv'][$i]['ip4Address'],$_SESSION['csv'][$i]['macAddress'],'','MAKE_DHCP_RESERVED','');
        }else{
            // nothing actually it will just move on to then next row
            //you could record the faliur or alert the user if required
        }
    }

Try\catch removed as you did not seem to be doing anything with it


问:
ERROR TypeError: Cannot read property 'unread' of undefined
I keep getting the error below when the page first loads, but I can just exit out of it and everything keeps working as expected.

```<code>ERROR TypeError: Cannot read property 'unread'
of undefined
at listing-element.ts:34
at Array.forEach (<anonymous>)
at SafeSubscriber._next (listing-element.ts:33)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.next (Subscriber.js:185)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
</code>```

I am currently using Angular 4.4.3, Ionic-Angular 3.9.2, AngularFire2 5.0.0.

When I run the code below, everything works as expected, but I can't seem to get rid of the Cannot read property 'unread' error that pops up on init no matter how many if statements I wrap the offending bit of code in. It's like I have Schrodinger's Observable; I am simultaneously getting the data I am expecting, yet it's coming back undefined. I realize it's due to the async nature of Observables, but I did not have any issues with this until my team switched our database to Google Firestore and therefore had to upgrade AngularFire 2.

We're having similar issues with our pipes and HTML. For our HTML, usually wrapping the code within an
 will work, so that it will only appear once we get the listing data. However, wrapping the TypeScript within something like if (threads.length > 0 && threads) does nothing, as the data still console logs with the expected result.

```<code>    //listing-element.ts
    this.userId = this.auth.getUser().uid;
    this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads => {
          threads.forEach(thread => {
            if (thread[this.userId].unread) { // <-Line 34 is here
              this.unread = true;
            }
          })
        })

    //listing-provider
      checkUnreadThreads(listingId) {
        return this.afs.collection(`listings/${listingId}/threads`)
          .snapshotChanges()
          .map(actions => {
            return actions.map(action => {
              const id = action.payload.doc.id;
              const data = action.payload.doc.data();
              return { id, ...data }
            });
          })
      }

    //listing-element.html
    <notification-badge *ngIf="userId === listingUserId && page.activity === true && unread"></notification-badge>
</code>```

This is all the information I thought was pertinent, but if anyone needs more information, I'm more than happy to provide whatever I can.

答:
You can try as shown below. </p>

```<code>this.afAuth.authState.subscribe(
      (auth) => {
        if (auth != null) {
            this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads
               => {
              threads.forEach(thread => {
                if (thread[auth.uid].unread) { // <-Line 34 is here
                  this.unread = true;
                }
              })
            })
          })
        }
      });
</code>```

Body:
I keep getting the error below when the page first loads, but I can just exit out of it and everything keeps working as expected.

ERROR TypeError: Cannot read property 'unread'
of undefined
at listing-element.ts:34
at Array.forEach (<anonymous>)
at SafeSubscriber._next (listing-element.ts:33)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.next (Subscriber.js:185)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)

I am currently using Angular 4.4.3, Ionic-Angular 3.9.2, AngularFire2 5.0.0.

When I run the code below, everything works as expected, but I can't seem to get rid of the Cannot read property 'unread' error that pops up on init no matter how many if statements I wrap the offending bit of code in. It's like I have Schrodinger's Observable; I am simultaneously getting the data I am expecting, yet it's coming back undefined. I realize it's due to the async nature of Observables, but I did not have any issues with this until my team switched our database to Google Firestore and therefore had to upgrade AngularFire 2.

We're having similar issues with our pipes and HTML. For our HTML, usually wrapping the code within an
 will work, so that it will only appear once we get the listing data. However, wrapping the TypeScript within something like if (threads.length > 0 && threads) does nothing, as the data still console logs with the expected result.

    //listing-element.ts
    this.userId = this.auth.getUser().uid;
    this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads => {
          threads.forEach(thread => {
            if (thread[this.userId].unread) { // <-Line 34 is here
              this.unread = true;
            }
          })
        })

    //listing-provider
      checkUnreadThreads(listingId) {
        return this.afs.collection(`listings/${listingId}/threads`)
          .snapshotChanges()
          .map(actions => {
            return actions.map(action => {
              const id = action.payload.doc.id;
              const data = action.payload.doc.data();
              return { id, ...data }
            });
          })
      }

    //listing-element.html
    <notification-badge *ngIf="userId === listingUserId && page.activity === true && unread"></notification-badge>

This is all the information I thought was pertinent, but if anyone needs more information, I'm more than happy to provide whatever I can.

Body:
You can try as shown below.

this.afAuth.authState.subscribe(
      (auth) => {
        if (auth != null) {
            this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads
               => {
              threads.forEach(thread => {
                if (thread[auth.uid].unread) { // <-Line 34 is here
                  this.unread = true;
                }
              })
            })
          })
        }
      });


问:
How to fix table view's search bar overlapping with status bar
I have a UITableViewController inside a navigation controller, with a search bar. This is how I add the search bar in viewDidLoad:

```<code>let resultsController = SearchTableViewController()
resultsController.people = people
searchController = UISearchController(searchResultsController: resultsController)
let searchBar = searchController.searchBar
searchBar.placeholder = "Search a person"
searchBar.sizeToFit()
tableView.tableHeaderView = searchBar
searchController.searchResultsUpdater = resultsController
</code>```

This is the result:

I tried editing the table view in the storyboard to add a constraint to make it further from the top view's margins, but I can't add contraints, probably because the table view is inside a UITableViewController.

答:
Add UISearchControllerDelegate;

Then

```<code>-(void)willDismissSearchController:(UISearchController *)searchController{
_tableView.contentInset = UIEdgeInsetsMake(20, 0, 44, 0);}
</code>```

Body:
I have a UITableViewController inside a navigation controller, with a search bar. This is how I add the search bar in viewDidLoad:

let resultsController = SearchTableViewController()
resultsController.people = people
searchController = UISearchController(searchResultsController: resultsController)
let searchBar = searchController.searchBar
searchBar.placeholder = "Search a person"
searchBar.sizeToFit()
tableView.tableHeaderView = searchBar
searchController.searchResultsUpdater = resultsController

This is the result:

I tried editing the table view in the storyboard to add a constraint to make it further from the top view's margins, but I can't add contraints, probably because the table view is inside a UITableViewController.

Body:
Add UISearchControllerDelegate;

Then

-(void)willDismissSearchController:(UISearchController *)searchController{
_tableView.contentInset = UIEdgeInsetsMake(20, 0, 44, 0);}


答:
The important thing to remember here is that items inside of aes() will map data to aesthetics. If you are setting a constant value(s), then you can move that information outside of aes(). A slight modification of your code yields:

```<code>ggplot(data, aes(x=a, y=b)) + geom_point() +
geom_line(aes(x=a, y=c)) +
geom_line(aes(x=a, y=(c - d)), colour="red") +
geom_line(aes(x=a, y=(c + d)), colour="red") +
geom_line(aes(x=a, y=(c - e)), colour="blue") +
geom_line(aes(x=a, y=(c + e)), colour="blue")
</code>```

Which gives you what you are after without any legend. I like @koshke's approach for including a legend above so won't duplicate that. The other approach you could take would be to perform your data manipulation outside of the call to ggplot2() and then melt() it into long format before plotting. That would shorten your call to ggplot() since you could get rid of the multiple calls to geom_line(), but there's obviously the overhead of preprocessing the data. Probably 6 in one, 1/2 dozen in the other for this problem, but something to keep in mind for future problems.

Title: Why does the ggplot legend show the "colour" parameter?

Body:
I have the following example:

data <- structure(list(a = c(-1.25549186262767, -0.840855480786298, -
0.635371312524283,
-0.602907981454667, -0.472166385166945, -0.285773634866154, 0.0701427664273268,
0.138108224803923, 1.38435934347858, 1.71144087270237), b = c(-3.44400412039417,
0.675644682353751, -1.04793816522475, -7.38303347186651, 2.34519166466874,
0.334780748573386, 4.76806919070976, 4.8633533150074, 3.50106026731172,
-1.27172351054143), c = c(-3.02376206439776, -2.56390769080574,
-1.48659913867609, -1.27976202274701, -0.368725655874139, 1.08537150160227,
3.98619381956471, 4.50687017428731, 4.10341582203292, -1.61769414438858
), d = c(5.71851494232005, 2.90539833491649, 2.75195159216204,
2.73478241733301, 2.65941820902101, 2.60630235726839, 3.34836154776286,
3.62938300664006, 4.61153521538016, 5.56230567213863), e = c(8.98703236551896,
4.5660296657415, 4.32487774825464, 4.29789523068949, 4.17945528847841,
4.09598014088541, 5.26217626511884, 5.70382046327322, 7.24733897758039,
8.74153894964533)), .Names = c("a", "b", "c", "d", "e"), row.names = c(NA,
-10L), class = "data.frame")

ggplot(data, aes(x=a, y=b)) + geom_point() +
    geom_line(aes(x=a, y=c)) +
    geom_line(aes(x=a, y=(c - d), colour="red")) +
    geom_line(aes(x=a, y=(c + d), colour="red")) +
    geom_line(aes(x=a, y=(c - e), colour="blue")) +
    geom_line(aes(x=a, y=(c + e), colour="blue"))

I want the labels to be "d" and "e", but they are instead being given the value of the "colour" field.  Two questions:

1) How can I eliminate the legend entirely?
2) If I want to include the legend, how can I have it set to specific values rather than the colour?

Body:
The important thing to remember here is that items inside of aes() will map data to aesthetics. If you are setting a constant value(s), then you can move that information outside of aes(). A slight modification of your code yields:

ggplot(data, aes(x=a, y=b)) + geom_point() +
geom_line(aes(x=a, y=c)) +
geom_line(aes(x=a, y=(c - d)), colour="red") +
geom_line(aes(x=a, y=(c + d)), colour="red") +
geom_line(aes(x=a, y=(c - e)), colour="blue") +
geom_line(aes(x=a, y=(c + e)), colour="blue")

Which gives you what you are after without any legend. I like @koshke's approach for including a legend above so won't duplicate that. The other approach you could take would be to perform your data manipulation outside of the call to ggplot2() and then melt() it into long format before plotting. That would shorten your call to ggplot() since you could get rid of the multiple calls to geom_line(), but there's obviously the overhead of preprocessing the data. Probably 6 in one, 1/2 dozen in the other for this problem, but something to keep in mind for future problems.


答:
try the below query

```<code>Select
case when MEMO_TYPE = 'CREDCARD'
then SUBSTRING(MEMO, CHARINDEX(',', MEMO)+1, LEN(MEMO) - (CHARINDEX(',', MEMO)-CHARINDEX(',',REVERSE(MEMO))-6)) ELSE null END
From REV
</code>```

sorry just fixed conversion error with above query,
Please use below query for getting 4 digit card numbers..

```<code>Select
case when MEMO_TYPE = 'CREDCARD'
then replace(SUBSTRING(MEMO,charindex(',',MEMO)+1,len(MEMO) - charindex(',',reverse(MEMO),CHARINDEX(',',reverse(MEMO))+1) - charindex(',',MEMO)),'x','') ELSE null END
From REV
</code>```

Title: SQL Substring separation throws conversion error

Body:
I have to get the last four digits of credit card number, after separating this by substring function the result throws conversion error. Below is a sample table

CREATE TABLE REV (MEMO varchar(100),MEMO_TYPE varchar(100))
INSERT REV VALUES ('09999D,xxxxxxxxxxxx0999,xx/xx,   30.27', 'CREDCARD')
INSERT REV VALUES ('09999D,xxxxxxxxxxxx0666,xx/xx,   50.45', 'CREDCARD')
INSERT REV VALUES ('09999D,REVVALS,ALC,   0', 'OTHER')

Below is  the query  used

Select CAST(case when MEMO_TYPE = 'CREDCARD' then
SUBSTRING(MEMO, CHARINDEX(',', MEMO)+1, LEN(MEMO)
-CHARINDEX(',', MEMO-CHARINDEX(',',REVERSE(MEMO))-6)) ELSE null END
as varchar(100))
-- as Cardnumber)
From REV

It throws
    Conversion failed when converting the varchar value
    '09999D,xxxxxxxxxxxx0999,xx/xx, 30.27' to data type int.

I'm sure I'm missing something incredibly simple... Anyone care to enlighten?

Body:
try the below query

Select
case when MEMO_TYPE = 'CREDCARD'
then SUBSTRING(MEMO, CHARINDEX(',', MEMO)+1, LEN(MEMO) - (CHARINDEX(',', MEMO)-CHARINDEX(',',REVERSE(MEMO))-6)) ELSE null END
From REV

sorry just fixed conversion error with above query,
Please use below query for getting 4 digit card numbers..

Select
case when MEMO_TYPE = 'CREDCARD'
then replace(SUBSTRING(MEMO,charindex(',',MEMO)+1,len(MEMO) - charindex(',',reverse(MEMO),CHARINDEX(',',reverse(MEMO))+1) - charindex(',',MEMO)),'x','') ELSE null END
From REV


问:
Publish to Azure Adding Files Individually during deployment
I am publishing MVC apps to my Azure account from two different PCs.  One PC (running VS 2017 15.4.3) publishes fast, with output like

```<code>2>Adding ACLs for path (10MinutesIter420171115083013)
2>Publish Succeeded.
2>Web App was published successfully
</code>```

The other PC (running VS 2017 15.4.4, also seen in 15.3.3) publishes slowly with output like

```<code>2>Adding ACLs for path (10MinutesIter320171115082232)
2>Adding file (10MinutesIter320171115082232\ApplicationInsights.config)
2>Adding file (10MinutesIter320171115082232\bin\10minutesIter3.dll)
2>Adding file (10MinutesIter320171115082232\bin\10minutesIter3.pdb)
</code>```

...and so on

The examples on the two PCs were both first publishes to Azure after a File | New of the Project, going to the same Resource Group, both using the Web Deploy publish method.  Project Properties are the same, excepting project names.

What causes this to happen and how can I stop the individual file copy?

答:
What causes this to happen and how can I stop the individual file copy?

Based on my experience, it seems that there is no relationship with VS version.

If we use VS to publish the Website to Azure, it seems that we can't stop the individual file.

I assume the root reason in your case is that when you publish the website from one of you PC first time it will copy all of the files to Azure webApp, and then publish with same content from another PC although first time if you uncheck (default is unchecked) Remove additional files at destination. It will check the remote and locally. If there is no difference then it is no adding file action.

If we don't want to publish the individual file, we could use Azure kudu tool(https://{yourwebsite}.scm.azurewebsites.net). You could zip the project and drag to kudu console directly.

Body:
I am publishing MVC apps to my Azure account from two different PCs.  One PC (running VS 2017 15.4.3) publishes fast, with output like

2>Adding ACLs for path (10MinutesIter420171115083013)
2>Publish Succeeded.
2>Web App was published successfully

The other PC (running VS 2017 15.4.4, also seen in 15.3.3) publishes slowly with output like

2>Adding ACLs for path (10MinutesIter320171115082232)
2>Adding file (10MinutesIter320171115082232\ApplicationInsights.config)
2>Adding file (10MinutesIter320171115082232\bin\10minutesIter3.dll)
2>Adding file (10MinutesIter320171115082232\bin\10minutesIter3.pdb)

...and so on

The examples on the two PCs were both first publishes to Azure after a File | New of the Project, going to the same Resource Group, both using the Web Deploy publish method.  Project Properties are the same, excepting project names.

What causes this to happen and how can I stop the individual file copy?