问:
Workload Scheduler: File transfer job submitted on a Windows agent ends in error
I am trying to submit a file transfer job on a Windows machine where the TWS agent is installed. The agent works correctly and I can detect no problems, but the file transfer regularly fails....  Any suggestions?</p>

答: When endpoint protection software is active on a Windows agent workstation, the FTP connection is blocked by Java. A Java technology bug reporting this issue can be accessed at http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7077696</p>


来源: stackexchange

问:
Dropzone error on crossdomain file upload
I want to upload file from on server to other server with dropzone. But I keep geting error Server responded with 0 code. Dropzone only send Option request to target server. Request And response headers are here. After that i get the error('0 code');
I Also set Headers to my php script. Which are these.

```<code>header('Access-Control-Allow-Origin: '.$pathToOrigin);
header('Access-Control-Allow-Credentials:false');
header('Access-Control-Max-Age:1000');
header('Access-Control-Allow-Methods:PUT, POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: X-Requested-With, cache-control, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
</code>```

requuest headers

答:
Try the following, I updated your sending function to:

```<code>  method: 'put',
  this.on("sending", function(file, xhr, formData) {
    formData.append('k1', $('#k1').val());
    var _send = xhr.send;
    xhr.send = function() {
      _send.call(xhr, file);
    }
  });
</code>```

$("div#drop").dropzone({
  method: 'put',
  url: "<?php echo $pathToUploadFiles ?>",
  autoProcessQueue: false,
  addRemoveLinks: true,
  this.on("sending", function(file, xhr, formData) {
    formData.append('k1', $('#k1').val());
    var _send = xhr.send;
    xhr.send = function() {
      _send.call(xhr, file);
    }
  });
  success: function(file) {
    this.removeFile(file);
  },
  queuecomplete: function() {
    toastr.info("Files are Uploaded Successfully!");
  }
});```

ContentLicense: CC BY-SA 3.0

Body:
I want to upload file from on server to other server with dropzone. But I keep geting error Server responded with 0 code. Dropzone only send Option request to target server. Request And response headers are here. After that i get the error('0 code');
I Also set Headers to my php script. Which are these.

header('Access-Control-Allow-Origin: '.$pathToOrigin);
header('Access-Control-Allow-Credentials:false');
header('Access-Control-Max-Age:1000');
header('Access-Control-Allow-Methods:PUT, POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: X-Requested-With, cache-control, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');

requuest headers

Body:
Try the following, I updated your sending function to:

  method: 'put',
  this.on("sending", function(file, xhr, formData) {
    formData.append('k1', $('#k1').val());
    var _send = xhr.send;
    xhr.send = function() {
      _send.call(xhr, file);
    }
  });

$("div#drop").dropzone({
  method: 'put',
  url: "<?php echo $pathToUploadFiles ?>",
  autoProcessQueue: false,
  addRemoveLinks: true,
  this.on("sending", function(file, xhr, formData) {
    formData.append('k1', $('#k1').val());
    var _send = xhr.send;
    xhr.send = function() {
      _send.call(xhr, file);
    }
  });
  success: function(file) {
    this.removeFile(file);
  },
  queuecomplete: function() {
    toastr.info("Files are Uploaded Successfully!");
  }
});


问:
How to convert java CharSequence to c++ char* through JNI
I feel that this should have a simple answer as I can do it easily with a java String, but something is going wrong with the CharSequence. My java code initializes a cppGenerator, passes a functionBlock object to its generateImplementation method, and returns a CharSequence. Here is my code:

```<code>jobject fBlock = env->CallObjectMethod(structuredTextModel, getFunction);
jclass CPPGenerator = lookForClass(env, "Path/CPPGenerator");
jobject CPPGeneratorImpl = invokeClassObj(env, CPPGenerator);
    jmethodID generateImplementation = env->GetMethodID(CPPGenerator, "generateImplementation", "(LPath/FunctionBlock;)Ljava/lang/CharSequence;");
jobject mid = env->CallObjectMethod(CPPGeneratorImpl, generateImplementation, fBlock);
jstring jresult = (jstring)mid;
char* result = (char*)env->GetStringUTFChars(jresult, 0);
</code>```

This logic has worked for me when using String but this function returns a CharSequence. No classes, objects, or methods are returning null. The program crashes in jni.h attempting to call GetStringUTFChars. So i know I cannot use this method for CharSequence. Is there just a jni method I am missing or do I have to do something completely different for a CharSequence?

答:
You can't just cast mid to jstring and call GetStringUTFChars (since mid might not be a String, which seems to be the case). There is no convenience method like GetStringUTFChars for CharSequences like there is for Strings.

You'd have to do it the inconvenient way of calling charAt:

```<code>jclass cCharSequence = env->FindClass("java/lang/CharSequence");
jmethodID mLength = env->GetMethodID(cCharSequence, "length", "()I");
jmethodID mCharAt = env->GetMethodID(cCharSequence, "charAt", "(I)C");

int length = env->CallIntMethod(mid, mLength);
std::string str;
str.reserve(length);
for(int i = 0; i < length; i++) {
    str += env->CallCharMethod(mid, mCharAt, i);
}

// use 'str.c_str()'...
</code>```

Body:
I feel that this should have a simple answer as I can do it easily with a java String, but something is going wrong with the CharSequence. My java code initializes a cppGenerator, passes a functionBlock object to its generateImplementation method, and returns a CharSequence. Here is my code:

jobject fBlock = env->CallObjectMethod(structuredTextModel, getFunction);
jclass CPPGenerator = lookForClass(env, "Path/CPPGenerator");
jobject CPPGeneratorImpl = invokeClassObj(env, CPPGenerator);
    jmethodID generateImplementation = env->GetMethodID(CPPGenerator, "generateImplementation", "(LPath/FunctionBlock;)Ljava/lang/CharSequence;");
jobject mid = env->CallObjectMethod(CPPGeneratorImpl, generateImplementation, fBlock);
jstring jresult = (jstring)mid;
char* result = (char*)env->GetStringUTFChars(jresult, 0);

This logic has worked for me when using String but this function returns a CharSequence. No classes, objects, or methods are returning null. The program crashes in jni.h attempting to call GetStringUTFChars. So i know I cannot use this method for CharSequence. Is there just a jni method I am missing or do I have to do something completely different for a CharSequence?

Body:
You can't just cast mid to jstring and call GetStringUTFChars (since mid might not be a String, which seems to be the case). There is no convenience method like GetStringUTFChars for CharSequences like there is for Strings.

You'd have to do it the inconvenient way of calling charAt:

jclass cCharSequence = env->FindClass("java/lang/CharSequence");
jmethodID mLength = env->GetMethodID(cCharSequence, "length", "()I");
jmethodID mCharAt = env->GetMethodID(cCharSequence, "charAt", "(I)C");

int length = env->CallIntMethod(mid, mLength);
std::string str;
str.reserve(length);
for(int i = 0; i < length; i++) {
    str += env->CallCharMethod(mid, mCharAt, i);
}

// use 'str.c_str()'...


问:
How to trim values and send to deepEquals method ()
```<code>public static void main(String args[]){
         String [] a={"A","B"};
         String[] b ={"  B"," A"};
         Arrays.sort(a);
         Arrays.sort(b);
         System.out.println(Arrays.deepEquals(a,b));
}
</code>```

I want to compare two string arrays and should return true values but its giving a false value since String[] b values has space. How do I trim my values and send to deepEquals method .

答:
trim() doesn't match all whitespace either (it matches all characters that have a value <= space, most of which aren't technically whitespace). Therefore, this would be feasible.

```<code>for(int i=0;i<b.length,i++)
{
  b[i] = b.replaceAll("\\p{Z}","");
}
</code>```

Body:
public static void main(String args[]){
         String [] a={"A","B"};
         String[] b ={"  B"," A"};
         Arrays.sort(a);
         Arrays.sort(b);
         System.out.println(Arrays.deepEquals(a,b));
}

I want to compare two string arrays and should return true values but its giving a false value since String[] b values has space. How do I trim my values and send to deepEquals method .

Body:
trim() doesn't match all whitespace either (it matches all characters that have a value <= space, most of which aren't technically whitespace). Therefore, this would be feasible.

for(int i=0;i<b.length,i++)
{
  b[i] = b.replaceAll("\\p{Z}","");
}


问:
How to use the 'debug' command inside pdb (python)
I would like to know how to use the debug command in pdb?

```<code>(Pdb) help

Documented commands (type help <topic>):
========================================
EOF    c          d        h         list      q        rv       undisplay
a      cl         debug    help      ll        quit     s        unt
alias  clear      disable  ignore    longlist  r        source   until
args   commands   display  interact  n         restart  step     up
b      condition  down     j         next      return   tbreak   w
break  cont       enable   jump      p         retval   u        whatis
bt     continue   exit     l         pp        run      unalias  where

Miscellaneous help topics:
==========================
pdb  exec
(Pdb) help debug
debug code
        Enter a recursive debugger that steps through the code
        argument (which is an arbitrary expression or statement to be
        executed in the current environment).
(Pdb) debug print('hello')
ENTERING RECURSIVE DEBUGGER
> <string>(1)<module>()->None
((Pdb)) n
hello
--Return--
> <string>(1)<module>()->None
((Pdb)) n
LEAVING RECURSIVE DEBUGGER
(Pdb)
</code>```

答:
Let, you have a bunch of code. You put pdb, say line 3.

In this case, when you run the program, line 1 and line 2 is executed automatically and you can see the result by putting the variable name and from line 4 is not executed.

If you wanna see after line 3 result you have to write code which results you want to see or you can go next line using n, and c for continuing that means exit from debugging mode.

ContentLicense: CC BY-SA 4.0

Body:
I would like to know how to use the debug command in pdb?

(Pdb) help

Documented commands (type help <topic>):
========================================
EOF    c          d        h         list      q        rv       undisplay
a      cl         debug    help      ll        quit     s        unt
alias  clear      disable  ignore    longlist  r        source   until
args   commands   display  interact  n         restart  step     up
b      condition  down     j         next      return   tbreak   w
break  cont       enable   jump      p         retval   u        whatis
bt     continue   exit     l         pp        run      unalias  where

Miscellaneous help topics:
==========================
pdb  exec
(Pdb) help debug
debug code
        Enter a recursive debugger that steps through the code
        argument (which is an arbitrary expression or statement to be
        executed in the current environment).
(Pdb) debug print('hello')
ENTERING RECURSIVE DEBUGGER
> <string>(1)<module>()->None
((Pdb)) n
hello
--Return--
> <string>(1)<module>()->None
((Pdb)) n
LEAVING RECURSIVE DEBUGGER
(Pdb)


问:
Permission denied running python script with the shebang line in linux
I am trying to run a python script in linux without calling python explicitly.
My goal is to have $ myscript.py run my script. Currently calling $ python myscript.py works but I am looking to not have to type the extra command for ease of use. I added the shebang line to the first line of my script to get the proper python call. I have tried both of the following lines and neither has worked for me.

```<code>#!/usr/bin/env python2.7
#!/usr/local/bin/python2.7
</code>```

The problem is that I get the following behavior

```<code>$ python2.7 myscript.py    # This will run

$ myscript.py           # This is the error
$ ./myscript.py         # This will also error
: Permission denied     # Error message
</code>```

When I do ls -ltr on the file I have executable permission for the script and the executable

```<code>-rwxrwxr-x 1 uname users   3544 Jul  7 08:46 myscript.py
-rwxr-xr-x 1 root  root 6231413 Jul  7 00:57 /usr/local/bin/python2.7
</code>```

I can also call python in the command line by typing what is written in either the shebang lines into it.

```<code>/usr/bin/env python2.7
/usr/local/bin/python2.7
</code>```

both run python in the terminal.

I have ran through the following stackoverflow problems and none seem to answer why this problem is happening to me.

bash permission denied for python

Python script: problems with shebang line (unix)

答:
Make sure to use LF line endings not CRLF line endings when running on linux! Thank you @jwodder for the suggestion.

I was using sublimetext to edit my files in windows and running the files on the linux machines. I changed the preferences in sublime to use unix line endings (LF) but I already wrote the file in the DOS endings (CRLF). I thought it would switch over the line endings for me. My assumption was wrong. I converted them all to LF and the script ran as expected.

Body:
I am trying to run a python script in linux without calling python explicitly.
My goal is to have $ myscript.py run my script. Currently calling $ python myscript.py works but I am looking to not have to type the extra command for ease of use. I added the shebang line to the first line of my script to get the proper python call. I have tried both of the following lines and neither has worked for me.

#!/usr/bin/env python2.7
#!/usr/local/bin/python2.7

The problem is that I get the following behavior

$ python2.7 myscript.py    # This will run

$ myscript.py           # This is the error
$ ./myscript.py         # This will also error
: Permission denied     # Error message

When I do ls -ltr on the file I have executable permission for the script and the executable

-rwxrwxr-x 1 uname users   3544 Jul  7 08:46 myscript.py
-rwxr-xr-x 1 root  root 6231413 Jul  7 00:57 /usr/local/bin/python2.7

I can also call python in the command line by typing what is written in either the shebang lines into it.

/usr/bin/env python2.7
/usr/local/bin/python2.7

both run python in the terminal.

I have ran through the following stackoverflow problems and none seem to answer why this problem is happening to me.

bash permission denied for python

Python script: problems with shebang line (unix)


问:
Azure MSAL login issue
I am using Azure AD B2C and trying to login using username and password in my Xamarin app. After signup, I get the following error:

Microsoft.Identity.Client.MsalServiceException: Returned user identifier does not match the sent user identifier at Microsoft.Identity.Client.Internal.Requests.RequestBase.SaveTokenResponseToCache ()

I am using MSAL for login and when we try to log in with Facebook, it works perfectly.

I found another thing, when I try to login with sign up or sign in policy, I can only login with Facebook, but when i try to login only with sign in policy I can only login with username and password not using Facebook.

答:
MSAL has a user cache that requires you to pass in a User in your AcquireTokenSilentAsync calls.

In the case of Azure AD B2C, the user entries in the MSAL cache don't map 1-to-1 to B2C users, rather they are projected across the different policies being used.

So if you have an app that leverages 3 policies for 1 user, MSAL's user cache will have 3 entries in the user cache.

From a code perspective, this means that in order to use MSAL you need to:

Have a GetUserByPolicy helper method that obtains the appropriate user cache entry based on the policy and using that to obtain the user that's passed in to your AcquireTokenAsync and AcquireTokenSilentAsync calls.

Ensure you are always passing an Authority value in your AcquireTokenSilentAsync calls.

The error "Returned user identifier does not match the sent user identifier" is generally caused by either of these two not being done correctly.

From the Azure AD B2C Xamarin Sample:

AcquireTokenAsync call:

```<code>AuthenticationResult ar = await App.PCA.AcquireTokenSilentAsync(App.Scopes, GetUserByPolicy(App.PCA.Users, App.PolicySignUpSignIn), App.Authority, false);
</code>```

AcquireTokenSilentAsync call:

```<code>AuthenticationResult ar = await App.PCA.AcquireTokenAsync(App.Scopes, GetUserByPolicy(App.PCA.Users, App.PolicySignUpSignIn), App.UiParent);
</code>```

GetUserByPolicy helper method:

```<code>private IUser GetUserByPolicy(IEnumerable <IUser> users, string policy)
{
  foreach (var user in users)
  {
    string userIdentifier = Base64UrlDecode(user.Identifier.Split('.')[0]);
    if (userIdentifier.EndsWith(policy.ToLower())) return user;
  }
  return null;
}
</code>```

Title: Azure MSAL login issue

Body:
MSAL has a user cache that requires you to pass in a User in your AcquireTokenSilentAsync calls.

In the case of Azure AD B2C, the user entries in the MSAL cache don't map 1-to-1 to B2C users, rather they are projected across the different policies being used.

So if you have an app that leverages 3 policies for 1 user, MSAL's user cache will have 3 entries in the user cache.

From a code perspective, this means that in order to use MSAL you need to:

Have a GetUserByPolicy helper method that obtains the appropriate user cache entry based on the policy and using that to obtain the user that's passed in to your AcquireTokenAsync and AcquireTokenSilentAsync calls.

Ensure you are always passing an Authority value in your AcquireTokenSilentAsync calls.

The error "Returned user identifier does not match the sent user identifier" is generally caused by either of these two not being done correctly.

From the Azure AD B2C Xamarin Sample:

AcquireTokenAsync call:

AuthenticationResult ar = await App.PCA.AcquireTokenSilentAsync(App.Scopes, GetUserByPolicy(App.PCA.Users, App.PolicySignUpSignIn), App.Authority, false);

AcquireTokenSilentAsync call:

AuthenticationResult ar = await App.PCA.AcquireTokenAsync(App.Scopes, GetUserByPolicy(App.PCA.Users, App.PolicySignUpSignIn), App.UiParent);

GetUserByPolicy helper method:

private IUser GetUserByPolicy(IEnumerable <IUser> users, string policy)
{
  foreach (var user in users)
  {
    string userIdentifier = Base64UrlDecode(user.Identifier.Split('.')[0]);
    if (userIdentifier.EndsWith(policy.ToLower())) return user;
  }
  return null;
}


问:
Hopscotch onClose tour function
I am creating a tour using Hopscotch and I would like to create the ability for the user to take or exit a tour of the page once they hit it.

I am trying to create a onClose function but I am getting stuck.

```<code>var tour = {
   id: "businesstour-hopscotch",
   steps: [
{
  title: "Welcome",
  content: "This is the new business profile page, click next to have a quick tour.",
  target: document.querySelector('#companyname'),
  placement: "right",
  xOffset: -380,
  yOffset: 52,
  onClose: function() {
    window.location = '/';
  }
},
</code>```

etc etc and it's not working. Not showing a button to end the tour either.
Any ideas would help!

答:
From my understanding of the documentation the onClose definition is a 'Tour Option' and should be declared like so, instead of inside the step:

```<code>var tour = {
   id: "businesstour-hopscotch",
   onClose: function() {
       window.location = '/';
   },
   steps: [{
       title: "Welcome",
       content: "This is the new business profile page, click next to have a quick tour.",
       target: document.querySelector('#companyname'),
       placement: "right",
       xOffset: -380,
       yOffset: 52
     }]
};
</code>```

I am initialising mine like this which works for the user clicking on the 'x' at the top right of the tour. However, I am not seeing this event triggered when the user clicks the 'Done' button on the last step in the tour.

Title: Hopscotch onClose tour function

Body:
I am creating a tour using Hopscotch and I would like to create the ability for the user to take or exit a tour of the page once they hit it.

I am trying to create a onClose function but I am getting stuck.

var tour = {
   id: "businesstour-hopscotch",
   steps: [
{
  title: "Welcome",
  content: "This is the new business profile page, click next to have a quick tour.",
  target: document.querySelector('#companyname'),
  placement: "right",
  xOffset: -380,
  yOffset: 52,
  onClose: function() {
    window.location = '/';
  }
},

etc etc and it's not working. Not showing a button to end the tour either.
Any ideas would help!

Body:
From my understanding of the documentation the onClose definition is a 'Tour Option' and should be declared like so, instead of inside the step:

var tour = {
   id: "businesstour-hopscotch",
   onClose: function() {
       window.location = '/';
   },
   steps: [{
       title: "Welcome",
       content: "This is the new business profile page, click next to have a quick tour.",
       target: document.querySelector('#companyname'),
       placement: "right",
       xOffset: -380,
       yOffset: 52
     }]
};

I am initialising mine like this which works for the user clicking on the 'x' at the top right of the tour. However, I am not seeing this event triggered when the user clicks the 'Done' button on the last step in the tour.


问:
T-SQL ORDER BY several clauses
I'm currently working on a stored procedure in TSQL on SQL Server 2014. I need to write a query to order a list of Projects by different StatusIds.

Table Project:

ProjectId

Label

ProjectDataId

Table ProjectData:

ProjectDataId

StatusId

Table Project is linked to ProjectData via ProjectDataId.

Demo Data Table Project:

```<code> ProjectId  | Label |  ProjectDataId |
------------+-------+----------------+
1           | Pro22 |      2         |
2           | Pro54 |      3         |
3           | Pro87 |      4         |
4           | Pro77 |      5         |
5           | Pro28 |      6         |
</code>```

Demo Data Table ProjectData:

```<code> ProjectDataId  |  StatusId   |
----------------+-------------+
2               |      1      |
3               |      2      |
4               |      3      |
5               |      4      |
6               |      4      |
</code>```

My current result looks like this:

```<code> ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
3           | Pro87 |      3      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
</code>```

My current query looks like this:

```<code>SELECT ROW_NUMBER() OVER(ORDER BY StatusId ASC)  AS [RowNumber], *
FROM (SELECT DISTINCT
        [P].ProjectId
      , [P].Label
      , [PD].StatusId
      , [P].ProjectDataId
     FROM [MySchema].[Project] [P]
     INNER JOIN [MyProject].[ProjectData] [PD]
     ON [PD].ProjectDataId = [P].ProjectDataId) dt
</code>```

This query works to order by statusId asc 1, 2, 3, 4 but not to bring it into the right order of statusId 1, 2, 4, 3.

Actually, the desired output should be:

```<code> ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
3           | Pro87 |      3      |
</code>```

Thus, I need to alter my sort query to achieve this.

My question, do you know how to solve this problem? To order by status more or less dynamically?

Thanks!

答:
Not really understanding the issue but try this on your 'status' field in thre 'select' statement;

```<code>[NewOrder]=case [PD].StatusId when 3 then 99 else [PD].StatusId end
</code>```

Order by that field now

Title: T-SQL ORDER BY several clauses

Body:
I'm currently working on a stored procedure in TSQL on SQL Server 2014. I need to write a query to order a list of Projects by different StatusIds.

Table Project:

ProjectId

Label

ProjectDataId

Table ProjectData:

ProjectDataId

StatusId

Table Project is linked to ProjectData via ProjectDataId.

Demo Data Table Project:

 ProjectId  | Label |  ProjectDataId |
------------+-------+----------------+
1           | Pro22 |      2         |
2           | Pro54 |      3         |
3           | Pro87 |      4         |
4           | Pro77 |      5         |
5           | Pro28 |      6         |

Demo Data Table ProjectData:

 ProjectDataId  |  StatusId   |
----------------+-------------+
2               |      1      |
3               |      2      |
4               |      3      |
5               |      4      |
6               |      4      |

My current result looks like this:

 ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
3           | Pro87 |      3      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |

My current query looks like this:

SELECT ROW_NUMBER() OVER(ORDER BY StatusId ASC)  AS [RowNumber], *
FROM (SELECT DISTINCT
        [P].ProjectId
      , [P].Label
      , [PD].StatusId
      , [P].ProjectDataId
     FROM [MySchema].[Project] [P]
     INNER JOIN [MyProject].[ProjectData] [PD]
     ON [PD].ProjectDataId = [P].ProjectDataId) dt

This query works to order by statusId asc 1, 2, 3, 4 but not to bring it into the right order of statusId 1, 2, 4, 3.

Actually, the desired output should be:

 ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
3           | Pro87 |      3      |

Thus, I need to alter my sort query to achieve this.

My question, do you know how to solve this problem? To order by status more or less dynamically?

Thanks!

Body:
Not really understanding the issue but try this on your 'status' field in thre 'select' statement;

[NewOrder]=case [PD].StatusId when 3 then 99 else [PD].StatusId end

Order by that field now


问:
How do I write a SQL query to display course_id, course_name and fee collected from each course?
The various tables and their columns are:

1)Course

```<code>course_id
course_name
duration
fee
</code>```

2)Registration

```<code>course_id
stud_id
doj
</code>```

3)Student

```<code>stud_id
first_name
last name
city
dob
</code>```

I have tried:

```<code>SELECT
    C.COURSE_ID,
    C. COURSE_NAME,
    COUNT(R.COURSE_ID) * FEES AS TOTAL_FEES
FROM
    COURSE C,
    REGISTRATION R,
WHERE
    C.COURSE_ID = R.COURSE_ID
GROUP BY
    R.COURSE_ID
</code>```

答:
```<code>SELECT c.cource_id, c.course_name, (totalNumberOfStudentPerCourse.totalNumberOfStudent * c.fee) as totalFee
FROM Course c
INNER JOIN
        (SELECT r.course_id, COUNT(r.stud_id) as totalNumberOfStudent
        FROM Registration r
        GROUP BY r.course_id) totalNumberOfStudentPerCourse ON c.course_id =  totalNumberOfStudentPerCourse.course_id
</code>```

the subquery creates a totalNumberOfStudentPerCourse table that looks like this:

```<code>course_id     totalNumberOfStudent
1             4
2             2
</code>```

example:

course:

```<code>course_id  course_name  fee

1           math         300
2           english      200
</code>```

registration:

```<code>course_id    stud_id
1             1
1               2
1               3
1               4
2               5
2               6
</code>```

result:

```<code>course_id   course_name     totalFee
1           math            1200
2           english         400
</code>```

Body:
The various tables and their columns are:

1)Course

course_id
course_name
duration
fee

2)Registration

course_id
stud_id
doj

3)Student

stud_id
first_name
last name
city
dob

I have tried:

SELECT
    C.COURSE_ID,
    C. COURSE_NAME,
    COUNT(R.COURSE_ID) * FEES AS TOTAL_FEES
FROM
    COURSE C,
    REGISTRATION R,
WHERE
    C.COURSE_ID = R.COURSE_ID
GROUP BY
    R.COURSE_ID

Body:
SELECT c.cource_id, c.course_name, (totalNumberOfStudentPerCourse.totalNumberOfStudent * c.fee) as totalFee
FROM Course c
INNER JOIN
        (SELECT r.course_id, COUNT(r.stud_id) as totalNumberOfStudent
        FROM Registration r
        GROUP BY r.course_id) totalNumberOfStudentPerCourse ON c.course_id =  totalNumberOfStudentPerCourse.course_id

the subquery creates a totalNumberOfStudentPerCourse table that looks like this:

course_id     totalNumberOfStudent
1             4
2             2

example:

course:

course_id  course_name  fee

1           math         300
2           english      200

registration:

course_id    stud_id
1             1
1               2
1               3
1               4
2               5
2               6

result:

course_id   course_name     totalFee
1           math            1200
2           english         400


问:
Unable to connect to Docker in Docker
I followed the instructions provided at https://docs.docker.com/samples/docker/, i.e.

```<code>docker run --privileged --name some-docker -d docker:dind
</code>```

However, I can't connect to the docker service.

```<code>docker run -i -t --rm --link some-docker:docker docker:latest version

Client:
 Version:      17.06.0-ce
 API version:  1.30
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:15:15 2017
 OS/Arch:      linux/amd64
Cannot connect to the Docker daemon at tcp://docker:2375. Is the docker daemon running?
</code>```

I'm able to telnet when I open a terminal via

```<code>docker run -i -t --rm --link some-docker:docker docker:latest /bin/sh

/ # telnet docker 2375
l
HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
Connection: close

400 Bad RequestConnection closed by foreign host
</code>```

Running docker -H docker info in the same container results in:

```<code>docker -H docker info
Cannot connect to the Docker daemon at tcp://docker:2375. Is the docker daemon running?
</code>```

If however I build a ubuntu based docker with docker installed using the following Dockerfile:

```<code>FROM ubuntu:latest

RUN apt-get update && apt-get -y install \
  apt-transport-https \
  ca-certificates \
  curl \
  software-properties-common

RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -

RUN add-apt-repository \
  "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) \
  stable"

RUN apt-get update && apt-get -y install docker-ce
</code>```

I'm able to connect to the docker-in-docker:

```<code>docker build -t docker-ubuntu .
docker run -i -t --rm --link some-docker:docker docker-ubuntu:latest /bin/sh
# docker -H docker info
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 0
Server Version: 17.06.0-ce
Storage Driver: vfs
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: cfb82a876ecc11b5ca0977d1733adbe58599088a
runc version: 2d41c047c83e09a6d61d464906feb2a2f3c52aa4
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 4.9.27-moby
Operating System: Alpine Linux v3.6 (containerized)
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 1.952GiB
Name: b39967739fb9
ID: NDIF:PU7X:NA4B:IMI4:UH7V:VL4G:Q6L5:DPKP:NKDH:2XH6:XYDB:F2AV
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
No Proxy: *.local, 169.254/16
Registry: https://index.docker.io/v1/
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false

WARNING: bridge-nf-call-iptables is disabled
WARNING: bridge-nf-call-ip6tables is disabled
</code>```

I tried both on docker-ce for Mac OS X as well as docker-ce for Ubuntu. Same result. Any ideas?

答:
--privileged does not mean you have access to the docker-socket, but rather all devices /dev and more.

That said, be sure to volume mount the docker-socket into your container

docker run -v /var/run/docker.sock:/var/run/docker.sock

or analog with docker-compose.yml

Title: Unable to connect to Docker in Docker

Body:
I followed the instructions provided at https://docs.docker.com/samples/docker/, i.e.

docker run --privileged --name some-docker -d docker:dind

However, I can't connect to the docker service.

docker run -i -t --rm --link some-docker:docker docker:latest version

Client:
 Version:      17.06.0-ce
 API version:  1.30
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:15:15 2017
 OS/Arch:      linux/amd64
Cannot connect to the Docker daemon at tcp://docker:2375. Is the docker daemon running?

I'm able to telnet when I open a terminal via

docker run -i -t --rm --link some-docker:docker docker:latest /bin/sh

/ # telnet docker 2375
l
HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
Connection: close

400 Bad RequestConnection closed by foreign host

Running docker -H docker info in the same container results in:

docker -H docker info
Cannot connect to the Docker daemon at tcp://docker:2375. Is the docker daemon running?

If however I build a ubuntu based docker with docker installed using the following Dockerfile:

FROM ubuntu:latest

RUN apt-get update && apt-get -y install \
  apt-transport-https \
  ca-certificates \
  curl \
  software-properties-common

RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -

RUN add-apt-repository \
  "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) \
  stable"

RUN apt-get update && apt-get -y install docker-ce

I'm able to connect to the docker-in-docker:

docker build -t docker-ubuntu .
docker run -i -t --rm --link some-docker:docker docker-ubuntu:latest /bin/sh
# docker -H docker info
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 0
Server Version: 17.06.0-ce
Storage Driver: vfs
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: cfb82a876ecc11b5ca0977d1733adbe58599088a
runc version: 2d41c047c83e09a6d61d464906feb2a2f3c52aa4
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 4.9.27-moby
Operating System: Alpine Linux v3.6 (containerized)
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 1.952GiB
Name: b39967739fb9
ID: NDIF:PU7X:NA4B:IMI4:UH7V:VL4G:Q6L5:DPKP:NKDH:2XH6:XYDB:F2AV
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
No Proxy: *.local, 169.254/16
Registry: https://index.docker.io/v1/
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false

WARNING: bridge-nf-call-iptables is disabled
WARNING: bridge-nf-call-ip6tables is disabled

I tried both on docker-ce for Mac OS X as well as docker-ce for Ubuntu. Same result. Any ideas?


问:
Add a class to child component when parent component state changes
This is my first time attempting to build with React. I typically write UI interaction with jQuery or plain old JS. I simply want a text field which when there is text entered has a class added to it so that I can style it differently to the default state. Note I only want this class adding when there is at least one character entered, not when the field is focused.

I already have an onChange function in the child component which is used to change the state of 'textEntered' but I can't figure out how to make use of this state in the child component to add a class.

Here is my parent component

```<code>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import TextInput from './components/TextInput/TextInput';

export default class Form extends Component {
  constructor(props) {
    super(props);
    this.state = {
      textEntered: '',
      completed: false,
    };
  }

  render() {
    return (
      <div>
        <TextInput
          placeholderText={'Title'}
          updateText={textEntered => this.setState({ textEntered })}
          completed={this.state.completed}
        />
      </div>
    );
  }
}

ReactDOM.render(<Form />, document.getElementById('react-create-form'));
</code>```

And here is the child component

```<code>import React, { PropTypes } from 'react';

const TextInput = props => (
  <div>
    <input
      type={props.type}
      placeholder={props.placeholderText}
      onChange={e => props.updateText(e.target.value)}
      data-completed={props.completed}
    />
  </div>
);

TextInput.propTypes = {
  type: PropTypes.string,
  placeholderText: PropTypes.string,
  updateText: PropTypes.func,
  completed: PropTypes.bool,
};

TextInput.defaultProps = {
  type: 'text',
};

export default TextInput;
</code>```

答:
Pass the class name from parent component, and also put the check on that. If text field has atleast one character then pass the actual class name otherwise blank string.

Since you are storing the value of text field inside state of parent component so put the condition like this:

```<code>customClass = {this.state.textEntered.length ? 'actualClassName': ''}
</code>```

Code:

```<code><div>
    <TextInput
        customClass={this.state.textEntered.length ? 'actualClassName': ''}
        placeholderText={'Title'}
        updateText={textEntered => this.setState({ textEntered })}
        completed={this.state.completed}
    />
</div>
</code>```

Inside child component apply this customClass.

```<code>const TextInput = props => (
    <div>
        <input
            type={props.type}
            className={props.customClass}
            placeholder={props.placeholderText}
            onChange={e => props.updateText(e.target.value)}
            data-completed={props.completed}
        />
    </div>
);
</code>```

Note: Another way is, pass the value in props instead of passing the class name and put the condition inside child component directly.

Body:
This is my first time attempting to build with React. I typically write UI interaction with jQuery or plain old JS. I simply want a text field which when there is text entered has a class added to it so that I can style it differently to the default state. Note I only want this class adding when there is at least one character entered, not when the field is focused.

I already have an onChange function in the child component which is used to change the state of 'textEntered' but I can't figure out how to make use of this state in the child component to add a class.

Here is my parent component

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import TextInput from './components/TextInput/TextInput';

export default class Form extends Component {
  constructor(props) {
    super(props);
    this.state = {
      textEntered: '',
      completed: false,
    };
  }

  render() {
    return (

        <TextInput
          placeholderText={'Title'}
          updateText={textEntered => this.setState({ textEntered })}
          completed={this.state.completed}
        />

    );
  }
}

ReactDOM.render(<Form />, document.getElementById('react-create-form'));

And here is the child component

import React, { PropTypes } from 'react';

const TextInput = props => (

    <input
      type={props.type}
      placeholder={props.placeholderText}
      onChange={e => props.updateText(e.target.value)}
      data-completed={props.completed}
    />

);

TextInput.propTypes = {
  type: PropTypes.string,
  placeholderText: PropTypes.string,
  updateText: PropTypes.func,
  completed: PropTypes.bool,
};

TextInput.defaultProps = {
  type: 'text',
};

export default TextInput;

Body:
Pass the class name from parent component, and also put the check on that. If text field has atleast one character then pass the actual class name otherwise blank string.

Since you are storing the value of text field inside state of parent component so put the condition like this:

customClass = {this.state.textEntered.length ? 'actualClassName': ''}

Code:

<div>
    <TextInput
        customClass={this.state.textEntered.length ? 'actualClassName': ''}
        placeholderText={'Title'}
        updateText={textEntered => this.setState({ textEntered })}
        completed={this.state.completed}
    />
</div>

Inside child component apply this customClass.

const TextInput = props => (
    <div>
        <input
            type={props.type}
            className={props.customClass}
            placeholder={props.placeholderText}
            onChange={e => props.updateText(e.target.value)}
            data-completed={props.completed}
        />
    </div>
);

Note: Another way is, pass the value in props instead of passing the class name and put the condition inside child component directly.


问:
how to get repeated integer value from string specific operators in python
I have a string value that contains numbers symbols and character.
The string is :

```<code>"1=value.2=value.4=value + 3=value.4=value+5=value"
</code>```

How to find how many repeated key value in whole string and also find repeated key values separated by + operator?

Is there a better way than splitting the string?

答:
Is there a better way than splitting the string?

Not really. You can use re.split() to split the string on every . and + character. And you can use len() to then get the length of the resulting list which corresponds to the number of "key, value" pairs:

```<code>>>> from re import split
>>> string = "1=value.2=value.4=value + 3=value.4=value+5=value"
>>> kv_pairs = re.split('\.|\+', string)
>>> kv_pairs
['1=value', '2=value', '4=value ', ' 3=value', '4=value', '5=value']
>>> len(kv_pairs) # number of key, value pairs
6
>>>
</code>```

If you want to count repeated key, value pairs, you can use collections.Counter(). Note however, that in your example there are no repeated key, value pairs:

```<code>>>> from collections import Counter
>>> {k: v for k, v in dict(Counter(kv_pairs)).items() if v > 1}
{}
>>>
</code>```

If you also want to include the separators, you can wrap the regex in parenthesis you form a capture group:

```<code>>>> kv_pairs = re.split('(\.|\+)', string)
>>> kv_pairs
['1=value', '.', '2=value', '.', '4=value ', '+', ' 3=value', '.', '4=value', '+', '5=value']
>>>
</code>```

Body:
I have a string value that contains numbers symbols and character.
The string is :

"1=value.2=value.4=value + 3=value.4=value+5=value"

How to find how many repeated key value in whole string and also find repeated key values separated by + operator?

Is there a better way than splitting the string?

Body:
Is there a better way than splitting the string?

Not really. You can use re.split() to split the string on every . and + character. And you can use len() to then get the length of the resulting list which corresponds to the number of "key, value" pairs:

>>> from re import split
>>> string = "1=value.2=value.4=value + 3=value.4=value+5=value"
>>> kv_pairs = re.split('\.|\+', string)
>>> kv_pairs
['1=value', '2=value', '4=value ', ' 3=value', '4=value', '5=value']
>>> len(kv_pairs) # number of key, value pairs
6
>>>

If you want to count repeated key, value pairs, you can use collections.Counter(). Note however, that in your example there are no repeated key, value pairs:

>>> from collections import Counter
>>> {k: v for k, v in dict(Counter(kv_pairs)).items() if v > 1}
{}
>>>

If you also want to include the separators, you can wrap the regex in parenthesis you form a capture group:

>>> kv_pairs = re.split('(\.|\+)', string)
>>> kv_pairs
['1=value', '.', '2=value', '.', '4=value ', '+', ' 3=value', '.', '4=value', '+', '5=value']
>>>


问:
How are values assigned to non-class types?
If non-class types, like pointers and int, do not have member functions like constructors, how are values assigned to them?
For instance:

```<code>int x = 1;
int p = x;
p = 2;
int a = int();
</code>```

When I did int p = x; would that simply perform a shallow copy, like an implicit copy constructor? Same goes for all other implicit member functions, since non-class types tend to work in the same way as with class types in those situations.

Also, when you have a class, that class would probably have an object that stores a certain value(if the class is supposed to represent a value), but is there some sort of buffer for these non-class types? Otherwise, how can a value be copied from one to another?

答:
To better understand the semantics of built-in types, consider the design and evolution of C++ language.

Initially there was no C++, and there was only C. In C, there were no classes, but only built-in types - such as ints, floats, pointers and so on. Every definition of the variable would mean a space sufficient to store variable of this type was allocated somehow (that allocation could be real memory reserved or might simply be a designation of the CPU register). Later on all access to this variable would be routed to the designated space. No constructors or destructors existed at all, and copying one variable to another simply meant copying the contents of source 'space' into target.

Later, when C++ was introduced, the great efforts were taken to make legacy C programs compatible with new language as much as possible. That mean, that for built-in types behavior remained exactly the same as in C. And it still continues to be true. Whenever you define a variable of built-in type (which doesn't get optimized out by optimizer, since it could), a space is allocated for it and all access is routed to this space. Copying those types is always direct space copy from target to the source.

Body:
If non-class types, like pointers and int, do not have member functions like constructors, how are values assigned to them?
For instance:

int x = 1;
int p = x;
p = 2;
int a = int();

When I did int p = x; would that simply perform a shallow copy, like an implicit copy constructor? Same goes for all other implicit member functions, since non-class types tend to work in the same way as with class types in those situations.

Also, when you have a class, that class would probably have an object that stores a certain value(if the class is supposed to represent a value), but is there some sort of buffer for these non-class types? Otherwise, how can a value be copied from one to another?


问:
Can I inherit from one class to another in CSS
What I'm doing is creating multiple classes for different elements one is a hover class and the other is the non hovered version.  Only one or two things change between the two classes and I don't want to have to copy and paste the whole class over and change just one line.

So what I'd like to do is say have

```<code>.hoverOff {
background-color: green;
font-size: 14pt;
border: 2px;
width: 150px;
}
</code>```

And then I have a hover over class

```<code>.hoverOn {
background-color: red;
}
</code>```

I want to inherit everything else from the hoverOff class and only change the background color.  Can I inherit with CSS like that and overide inherited styles in the new class?  As it stands right now I'm simply copying the entire class, renaming it and changing one line.  Seems pretty redundant and archaic to me.

答:
In pure CSS, simply use both classes in your first selector:

```<code>.hoverOff,
.hoverOn {
  font-size: 14pt;
  border: 2px;
  width: 150px;
}
.hoverOff {
  background-color: green;
}
.hoverOn {
  background-color: red;
}
</code>```

Anyway, unless you're doing some JS advanced magic, I would recommend to use :hover, as stated in this answer.

Body:
What I'm doing is creating multiple classes for different elements one is a hover class and the other is the non hovered version.  Only one or two things change between the two classes and I don't want to have to copy and paste the whole class over and change just one line.

So what I'd like to do is say have

.hoverOff {
background-color: green;
font-size: 14pt;
border: 2px;
width: 150px;
}

And then I have a hover over class

.hoverOn {
background-color: red;
}

I want to inherit everything else from the hoverOff class and only change the background color.  Can I inherit with CSS like that and overide inherited styles in the new class?  As it stands right now I'm simply copying the entire class, renaming it and changing one line.  Seems pretty redundant and archaic to me.

Body:
In pure CSS, simply use both classes in your first selector:

.hoverOff,
.hoverOn {
  font-size: 14pt;
  border: 2px;
  width: 150px;
}
.hoverOff {
  background-color: green;
}
.hoverOn {
  background-color: red;
}

Anyway, unless you're doing some JS advanced magic, I would recommend to use :hover, as stated in this answer.


问:
Store objects in an array and print it out JAVA
I've created different types of objects like object1 object2 etc. Now, how can I store these objects into an array and print that array out? The idea below does not work.

```<code>Buch buch = new Buch("Blablabla", "Baba Isi", "DE 1234567890", 50, 1234f);
    System.out.println(buch.toString());
    //5 Objekte erstellen
    /*2*/Buch buch2 = new Buch("Blabla2", "blubb", "DE 5461563259", 50, 1234f);
    System.out.println(buch2.toString());
    /*3*/Buch buch3 = new Buch("Check this out", "oke", "DE 67892011789", 50, 1234f);
    System.out.println(buch3.toString());
    /*4*/Buch buch4 = new Buch("Got ya", "catch ya", "DE 678198771890", 50, 1234f);
    System.out.println(buch4.toString());
    /*5*/Buch buch5 = new Buch("IDK", "IDK2", "DE 47740710974691", 50, 1234f);
    System.out.println(buch5.toString());

    Buch[] arr = new Buch[5];
    for(int i = 0; i<5; i++){
        arr[i] = new Buch();
    }
    for(int i = 0; i < arr.length; i++){      //toString method exists an it works
        System.out.println(arr[i].toString());
    }
</code>```

The output:

Titel: Ein Mann ein Wort   Autor: Baba Isi   ISBN: DE 1234567890   Seitenzahl: 50   Preis:    1234.0

Titel: Wanna smash   Autor: smash it   ISBN: DE 5461563259   Seitenzahl: 50   Preis:    1234.0

Titel: Smash Me   Autor: oke   ISBN: DE 67892011789   Seitenzahl: 50   Preis:    1234.0

Titel: Got ya   Autor: catch ya   ISBN: DE 678198771890   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

答:
replace the for loop by something like that :</p>

```<code>    Buch[] arr = { buch, buch2, buch3, buch4, buch5 };
</code>```

Body:
I've created different types of objects like object1 object2 etc. Now, how can I store these objects into an array and print that array out? The idea below does not work.

Buch buch = new Buch("Blablabla", "Baba Isi", "DE 1234567890", 50, 1234f);
    System.out.println(buch.toString());
    //5 Objekte erstellen
    /*2*/Buch buch2 = new Buch("Blabla2", "blubb", "DE 5461563259", 50, 1234f);
    System.out.println(buch2.toString());
    /*3*/Buch buch3 = new Buch("Check this out", "oke", "DE 67892011789", 50, 1234f);
    System.out.println(buch3.toString());
    /*4*/Buch buch4 = new Buch("Got ya", "catch ya", "DE 678198771890", 50, 1234f);
    System.out.println(buch4.toString());
    /*5*/Buch buch5 = new Buch("IDK", "IDK2", "DE 47740710974691", 50, 1234f);
    System.out.println(buch5.toString());

    Buch[] arr = new Buch[5];
    for(int i = 0; i<5; i++){
        arr[i] = new Buch();
    }
    for(int i = 0; i < arr.length; i++){      //toString method exists an it works
        System.out.println(arr[i].toString());
    }

The output:

Titel: Ein Mann ein Wort   Autor: Baba Isi   ISBN: DE 1234567890   Seitenzahl: 50   Preis:    1234.0

Titel: Wanna smash   Autor: smash it   ISBN: DE 5461563259   Seitenzahl: 50   Preis:    1234.0

Titel: Smash Me   Autor: oke   ISBN: DE 67892011789   Seitenzahl: 50   Preis:    1234.0

Titel: Got ya   Autor: catch ya   ISBN: DE 678198771890   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Body:
replace the for loop by something like that :

    Buch[] arr = { buch, buch2, buch3, buch4, buch5 };


问:
How to uninstall gfortran on MacOS Sierra?
I followed the instructions given here How to uninstall gfortran compiler on MAC OSX 10.7
But when I try to install gfortran again, it tells me a version of gfortran already exists.</p>

答:
The .plist, and .bom files related to the previous gfortran installation need to be removed from /private/var/db/receipts/.

```<code>rm /private/var/db/receipts/com.gnu.gfortran.bom
rm /private/var/db/receipts/com.gnu.gfortran.plist
</code>```

This is to be done after you have removed gfortran from /usr/local/ and /usr/local/bin/.

Body:
The .plist, and .bom files related to the previous gfortran installation need to be removed from /private/var/db/receipts/.

rm /private/var/db/receipts/com.gnu.gfortran.bom
rm /private/var/db/receipts/com.gnu.gfortran.plist

This is to be done after you have removed gfortran from /usr/local/ and /usr/local/bin/.


问:
How to do select statement after THEN of SELECT CASE in SQL query?
Is it possible to write query which has select statement after THEN of SELECT CASE in SQL query?
Example of logic</p>

```<code>SELECT Id, CASE WHEN level=2 THEN
    (select something here)
    else 0 end as Grade FROM CLASS
</code>```

答:
Based on the PHP Documentation you could run something along these lines:

Start by creating your database connection:

```<code><?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
</code>```

This if statement is checking for the table test if it does not exists then drop it OR create the table test with the field id which is an INT

```<code>if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
</code>```

Then if the conditions are try you run your queries here; here they have three queries.

First - counts the total rows in the table (which will equal 0)

Second - add a value to the table

Third - count the total rows again, which this time will output "1"

```<code>// this is what you may be asking?
// they add to their sql query
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
</code>```

Make sure that the queries have been built correctly

```<code>if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
</code>```

Then run the code

```<code>do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC)); // this will gather all records from the Database
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result()); // You can find the links for documentation for more_results() and next_result() below
?>
</code>```

Documentation for more_results() and next_results()

Note the $sql as you can see they just create multiple queries that will run together if everything is true.

It will output this:

```<code>array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "0"
  }
}
array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "1"
  }
}
</code>```

Please note, this is not my code, I got it from here

Body:
Is it possible to write query which has select statement after THEN of SELECT CASE in SQL query?
Example of logic

SELECT Id, CASE WHEN level=2 THEN
    (select something here)
    else 0 end as Grade FROM CLASS

Body:
Based on the PHP Documentation you could run something along these lines:

Start by creating your database connection:

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

This if statement is checking for the table test if it does not exists then drop it OR create the table test with the field id which is an INT

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

Then if the conditions are try you run your queries here; here they have three queries.

First - counts the total rows in the table (which will equal 0)

Second - add a value to the table

Third - count the total rows again, which this time will output "1"

// this is what you may be asking?
// they add to their sql query
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

Make sure that the queries have been built correctly

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

Then run the code

do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC)); // this will gather all records from the Database
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result()); // You can find the links for documentation for more_results() and next_result() below
?>

Documentation for more_results() and next_results()

Note the $sql as you can see they just create multiple queries that will run together if everything is true.

It will output this:

array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "0"
  }
}
array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "1"
  }
}

Please note, this is not my code, I got it from here


答:
You can do what you describe in the question, however it's much simpler to just use CSS to take care of the hover state for you using the :hover pseudo selector. Try this:

.foo {
  background-color: green;
  font-size: 14pt;
  border: 2px;
  width: 150px;
}

.foo:hover {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="foo">
  Hover over me
</div></code>```

Title: Can I inherit from one class to another in CSS

Body:
You can do what you describe in the question, however it's much simpler to just use CSS to take care of the hover state for you using the :hover pseudo selector. Try this:

.foo {
  background-color: green;
  font-size: 14pt;
  border: 2px;
  width: 150px;
}

.foo:hover {
  background-color: red;
}

<div class="foo">
  Hover over me
</div>


问:
How can I send a SharePoint alert only when a particular column is changed?
I need to trigger alert, if value of particular column (say marks<8, send mail to manager) changes.

What should I do?

答:
Some kinds of lists (e.g. tasks) allow to send alerts when someone changes an item that appears in a particular view. Read the article Use SharePoint Filtered Views to Stop Sending Alerts to Yourself to get all the details (appropriate section begins with Well you need to set up a filtered view).

If you list supports this feature, first create a view that shows only the items that satisfy your marks<8 condition and then configure an alert that uses this view.

ContentLicense: CC BY-SA 2.5


问:
Unable to get Regression line and the variance bounds in Seaborn pairplot
I am unable to get regression line and the variance bounds around it while plotting seaborn.pairplot with kind=reg as shown in the examples at http://seaborn.pydata.org/generated/seaborn.pairplot.html

```<code>import pandas pd
import seaborn as sns
import numpy as np
import matplotlib as plt
# Preparing random dataFrame with two colums, viz., random x and lag-1 values
lst1 = list(np.random.rand(10000))
df = pd.DataFrame({'x1':lst1})
df['x2'] = df['x1'].shift(1)
df = df[df['x2'] > 0]
# Plotting now
pplot = sns.pairplot(df, kind="reg")
pplot.set(ylim=(min(df['x1']), max(df['x1'])))
pplot.set(xlim=(min(df['x1']), max(df['x1'])))
plt.show()
</code>```

答:
The regression line is there, you just don't see it, because it's hidden by the unnaturally high number of points in the plot.

So let's reduce the number of points and you'll see the regression as expected.

```<code>import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
# Preparing random dataFrame with two colums, viz., random x and lag-1 values
lst1 = list(np.random.rand(100))
df = pd.DataFrame({'x1':lst1})
df['x2'] = df['x1'].shift(1)
df = df[df['x2'] > 0]
# Plotting now
pplot = sns.pairplot(df, kind="reg")

plt.show()
</code>```

Body:
I am unable to get regression line and the variance bounds around it while plotting seaborn.pairplot with kind=reg as shown in the examples at http://seaborn.pydata.org/generated/seaborn.pairplot.html

import pandas pd
import seaborn as sns
import numpy as np
import matplotlib as plt
# Preparing random dataFrame with two colums, viz., random x and lag-1 values
lst1 = list(np.random.rand(10000))
df = pd.DataFrame({'x1':lst1})
df['x2'] = df['x1'].shift(1)
df = df[df['x2'] > 0]
# Plotting now
pplot = sns.pairplot(df, kind="reg")
pplot.set(ylim=(min(df['x1']), max(df['x1'])))
pplot.set(xlim=(min(df['x1']), max(df['x1'])))
plt.show()

Body:
The regression line is there, you just don't see it, because it's hidden by the unnaturally high number of points in the plot.

So let's reduce the number of points and you'll see the regression as expected.

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
# Preparing random dataFrame with two colums, viz., random x and lag-1 values
lst1 = list(np.random.rand(100))
df = pd.DataFrame({'x1':lst1})
df['x2'] = df['x1'].shift(1)
df = df[df['x2'] > 0]
# Plotting now
pplot = sns.pairplot(df, kind="reg")

plt.show()


问:
Where does this akka-http test import Marshaller?
I am looking at this akka-http docs example (which links to akka-http test code):

Marshalling

This is actually a test from github code MarshalSpec.scala. My question is, where is the implicit Marshaller imported here? I am looking at imports, and I couldn't find it? I tried using IntelliJ to show me implicit imports, but I still couldn't figure this out. Where is the import statement that gets the implicit declaration for a Marshaller that is passed to:

```<code>  val entityFuture = Marshal(string).to[MessageEntity]
</code>```

at line 21?
It calls

```<code>def to[B](implicit m: Marshaller[A, B], ec: ExecutionContext): Future[B] =
</code>```

in Marshal.scala and passes an implicit m: Marshaller, which I can't pinpoint.

答:
Marshaller extends PredefinedToEntityMarshallers , which provides marshalling from String.

But, why does Marshaller comes with its own implicits ? It's because scala search for implicits in the implicit scope of type arguments : Where does Scala look for implicits?

So, Marshaller comes with its own Marshallers ready to use :)

Body:
I am looking at this akka-http docs example (which links to akka-http test code):

Marshalling

This is actually a test from github code MarshalSpec.scala. My question is, where is the implicit Marshaller imported here? I am looking at imports, and I couldn't find it? I tried using IntelliJ to show me implicit imports, but I still couldn't figure this out. Where is the import statement that gets the implicit declaration for a Marshaller that is passed to:

  val entityFuture = Marshal(string).to[MessageEntity]

at line 21?
It calls

def to[B](implicit m: Marshaller[A, B], ec: ExecutionContext): Future[B] =

in Marshal.scala and passes an implicit m: Marshaller, which I can't pinpoint.


问:
Using multiple timestamp formats in maven
I have two properties in my pom.xml as below that I will use to filter a txt file:

```<code><properties>
    <date>${maven.build.timestamp}</date>
    <dateFormatted>${maven.build.timestamp}</dateFormatted>
</properties>
</code>```

I want date to be in the format yyyyMMdd-HHmm and dateFormatted to be in the form yyyy-MM-dd HH:mm. Is it possible to use two different timestamp formats or is there an alternate way to do this?

答: Answered by Tunaki in this thread. Using the method he describes, you can build whatever format you need based on the individual components. It seems like this wasn't initially working for me because I was only calling mvn resources:resources. When I ran the complete build, mvn package, the correct changes appeared in the file I was filtering.

Body:
I have two properties in my pom.xml as below that I will use to filter a txt file:

<properties>
    <date>${maven.build.timestamp}</date>
    <dateFormatted>${maven.build.timestamp}</dateFormatted>
</properties>

I want date to be in the format yyyyMMdd-HHmm and dateFormatted to be in the form yyyy-MM-dd HH:mm. Is it possible to use two different timestamp formats or is there an alternate way to do this?


问:
Design patterns to avoid
A lot of people seem to agree, that the Singleton pattern has a number of drawbacks and some even suggest avoiding the pattern entirely. There's an excellent discussion here. Please direct any comments about the Singleton pattern to that question.

My question: Are there other design patterns, that should be avoided or used with great care?

答:
I think that Active Record is an overused pattern that encourages mixing business logic with the persistance code. It doesn't do a very good job of hiding the storage implementation from the model layer and ties the models to a database. There are plenty of alternatives (described in PoEAA) such as Table Data Gateway, Row Data Gateway and Data Mapper which often provide a better solution and certainly help to provide a better abstraction to storage. Also, your model should not need to be stored in a database; what about storing them as XML or accessing them using web services? How easy would it be to change the storage mechanism of your models?

That said, Active Record is not always bad and is perfect for simpler applications where the other options would be overkill.

OwnerDisplayName: Brian Rasmussen

Title: Design patterns to avoid

LastEditorDisplayName: Joel Coehoorn


问:
Binding to ObservableCollection from Custom Control
I have a custom control with an ObservableCollection...

In my Generic.xaml, I have the control template defined there and I would like to bind the ListBox there to the observablecollection of its own custom control (INotifyPropertyChanged implemented), which is different than normal since we're not binding to the view model.

Is this possible?

答:
If you want to bind a control in a control template (listbox in your case) to an object in the custom control (ObservableCollection in your case), you should define the object as a dependency property in the custom control and then use 'TemplateBinding' to bind to the object in the control template.

I am however wondering if its indeed a custom control that you want and not a user control.


问:
How to install pymssql on MacOS Sierra
```<code>Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-build-J1I0ox/pymssql/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-qmtdBW-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-J1I0ox/pymssql/
</code>```

I am having the same error as displayed here . I followed the instructions on that page by trying brew install freetds followed by sudo -H pip install pymssql.

That generates this error code:

```<code>    _mssql.c:18814:15: error: use of undeclared identifier 'DBVERSION_80'
    __pyx_r = DBVERSION_80;
              ^
4 warnings and 1 error generated.
error: command 'cc' failed with exit status 1

----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-build-J1I0ox/pymssql/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-qmtdBW-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-J1I0ox/pymssql/
</code>```

Searching this error brought me to  this page. I followed the solution posted there by trying both  brew unlink freetds; brew install homebrew/versions/freetds091 and  brew uninstall freetds; brew install homebrew/versions/freetds091 which generates a different error when trying  sudo -H pip install pymssql:

```<code>_mssql.c:266:10: fatal error: 'sqlfront.h' file not found
#include "sqlfront.h"
         ^
1 error generated.
error: command 'cc' failed with exit status 1

----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/_s/27xppw4j3yl78c9l4v1w3n9m0000gn/T/pip-build-97A9sQ/pymssql/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/_s/27xppw4j3yl78c9l4v1w3n9m0000gn/T/pip-0nUZo4-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/_s/27xppw4j3yl78c9l4v1w3n9m0000gn/T/pip-build-97A9sQ/pymssql/
</code>```

So then I gave up and tried to install pyodbc, but I still get similar errors:  src/pyodbc.h:56:10: fatal error: 'sql.h' file not found
    #include sql.h

Any help with this would be great.

答:
 This link  ended up solving my problem. For anyone else having these issues, this sequence of commands worked for me.</p>

```<code>brew uninstall --force freetds
brew install freetds@0.91
brew link --force freetds@0.91
pip install pymssql
</code>```

Title: How to install pymssql on MacOS Sierra

Body:
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-build-J1I0ox/pymssql/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-qmtdBW-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-J1I0ox/pymssql/

I am having the same error as displayed here . I followed the instructions on that page by trying brew install freetds followed by sudo -H pip install pymssql.

That generates this error code:

    _mssql.c:18814:15: error: use of undeclared identifier 'DBVERSION_80'
    __pyx_r = DBVERSION_80;
              ^
4 warnings and 1 error generated.
error: command 'cc' failed with exit status 1

----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-build-J1I0ox/pymssql/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-qmtdBW-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-J1I0ox/pymssql/

Searching this error brought me to  this page. I followed the solution posted there by trying both  brew unlink freetds; brew install homebrew/versions/freetds091 and  brew uninstall freetds; brew install homebrew/versions/freetds091 which generates a different error when trying  sudo -H pip install pymssql:

_mssql.c:266:10: fatal error: 'sqlfront.h' file not found
#include "sqlfront.h"
         ^
1 error generated.
error: command 'cc' failed with exit status 1

----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/_s/27xppw4j3yl78c9l4v1w3n9m0000gn/T/pip-build-97A9sQ/pymssql/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/_s/27xppw4j3yl78c9l4v1w3n9m0000gn/T/pip-0nUZo4-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/_s/27xppw4j3yl78c9l4v1w3n9m0000gn/T/pip-build-97A9sQ/pymssql/

So then I gave up and tried to install pyodbc, but I still get similar errors:  src/pyodbc.h:56:10: fatal error: 'sql.h' file not found
    #include sql.h

Any help with this would be great.

Body:
 This link  ended up solving my problem. For anyone else having these issues, this sequence of commands worked for me.

brew uninstall --force freetds
brew install freetds@0.91
brew link --force freetds@0.91
pip install pymssql


问:
How to retrieve the data from db in progress 4gl?
How to fetch the value from db in  progress 4gl, initially have a input from user to select the record  based on the value the record will be displayed. we try that but we can't fetch the exact value.

This is our program:

```<code>def var b   as int.
def var obj as int.
/*set obj.
prompt-for obj.*/
def var sum as int.
def var a   as int no-undo.
def var i   as int no-undo.
for each po_mstr break by po_nbr.
select count (*)  from po_mstr.
    assign
        a = 1
        b = 583 .
    repeat:
        if first-of (po_nbr) then
            set obj.
        prompt-for obj.
        if (a le obj and obj lt b) then
            disp po_nbr po_vend po_ship po_ord_date with 2 col.
    end.
end.
</code>```

I can retrieve a single data only if we give more than 2 value means it will display the same first value.

答:
Let's break this down. You're using a lot of commands without really realizing what they're for.

FOR EACH opens a block and perform record reads for each loop, in the selected sorting order (if none is selected, then it uses the primary index).

SELECT will perform a database operation, not necessarily doing on the fly, but it might.

REPEAT will also open a block, in which you might or might not be looping records with additional commands. Having said that, here's how I'd write this:

```<code>def var a as int no-undo.
def var b as int.
def var sum as int.
/*
def var obj as int.
update obj.
def var i as int no-undo.
you're not using this */
select count (*) into sum from po_mstr.
/* is this what you wanted? To have the count in sum? I don't see a reason, but suit yourself */
assign a = 1 b = 583 . /* or use UPDATE a b. if you would like to make that variable */
/* Since a and b are not changing, I moved it to outside the loop */
for each po_mstr where po_nbr >= a and po_nbr < b:
    disp po_nbr po_vend po_ship po_ord_date with 2 col.
end.
</code>```

I took some liberties. I removed obj because as far as I could assess, you were trying to copy po_nbr values to it, then use it to see if it was in the range you wanted to see. Since I believe po_nbr stands for po number, and that is probably unique, I'd also guess every iteration will have a different value for it. So no need to use if first-of. It also eliminates the need to copy it to a variable. Just compare it directly to the range of po's you want to see. Finally, the display should be fine.

I'm going to go ahead and assume your team hasn't been trained. This would be very important going forward, because QAD (any ERP software, in fact) is going to inflate really fast and badly written code, even when harmless, may impact performance and usability, which could be a problem to operation as a whole. Stack Overflow may be helpful for punctual questions, but the kind of problems you will run into if you aren't prepared will likely not be possible to solve here.

Hope this helps.

Body:
How to fetch the value from db in  progress 4gl, initially have a input from user to select the record  based on the value the record will be displayed. we try that but we can't fetch the exact value.

This is our program:

def var b   as int.
def var obj as int.
/*set obj.
prompt-for obj.*/
def var sum as int.
def var a   as int no-undo.
def var i   as int no-undo.
for each po_mstr break by po_nbr.
select count (*)  from po_mstr.
    assign
        a = 1
        b = 583 .
    repeat:
        if first-of (po_nbr) then
            set obj.
        prompt-for obj.
        if (a le obj and obj lt b) then
            disp po_nbr po_vend po_ship po_ord_date with 2 col.
    end.
end.

I can retrieve a single data only if we give more than 2 value means it will display the same first value.

Body:
Let's break this down. You're using a lot of commands without really realizing what they're for.

FOR EACH opens a block and perform record reads for each loop, in the selected sorting order (if none is selected, then it uses the primary index).

SELECT will perform a database operation, not necessarily doing on the fly, but it might.

REPEAT will also open a block, in which you might or might not be looping records with additional commands. Having said that, here's how I'd write this:

def var a as int no-undo.
def var b as int.
def var sum as int.
/*
def var obj as int.
update obj.
def var i as int no-undo.
you're not using this */
select count (*) into sum from po_mstr.
/* is this what you wanted? To have the count in sum? I don't see a reason, but suit yourself */
assign a = 1 b = 583 . /* or use UPDATE a b. if you would like to make that variable */
/* Since a and b are not changing, I moved it to outside the loop */
for each po_mstr where po_nbr >= a and po_nbr < b:
    disp po_nbr po_vend po_ship po_ord_date with 2 col.
end.

I took some liberties. I removed obj because as far as I could assess, you were trying to copy po_nbr values to it, then use it to see if it was in the range you wanted to see. Since I believe po_nbr stands for po number, and that is probably unique, I'd also guess every iteration will have a different value for it. So no need to use if first-of. It also eliminates the need to copy it to a variable. Just compare it directly to the range of po's you want to see. Finally, the display should be fine.

I'm going to go ahead and assume your team hasn't been trained. This would be very important going forward, because QAD (any ERP software, in fact) is going to inflate really fast and badly written code, even when harmless, may impact performance and usability, which could be a problem to operation as a whole. Stack Overflow may be helpful for punctual questions, but the kind of problems you will run into if you aren't prepared will likely not be possible to solve here.

Hope this helps.


问:
How to hide @RequestMapping parameter?
I have a Servlet with a parameter bean. The bean has some fields that should no be able to override by the users get-query.

How can I achieve it?

None of the following worked:

```<code>@JsonIgnore
@XmlTransient
@JsonIgnoreProperties
private String somefield;
</code>```

Run:

```<code>localhost:8080/myservlet?somefield=xxx
</code>```

This will alter the property directly. How can I tell spring to skip that property?

Or even better: let spring reject the request as the user tried to change an unallowed property?

答:
If by servlet you mean controller you can configure binder to ignore some properties of model class:

```<code>@RestController
public class MyServlet {

    @InitBinder
    private void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields("somefield");
    }

    @GetMapping("/myservlet")
    public String myservlet(Model model) {
        return model.toString();
    }
}
</code>```

Model:

```<code>public class Model {
    private String somefield;
    private String property2;
    //getters and setters
}
</code>```

Another way is to remove the ignored property setter from model class at all. In that case spring will not be able to set the value.

If by servlet you mean servlet then just wrap the request excluding ignoring properties from getParameterMap() call.

Update

If you want to force spring to reject entire request when inappropriate property is set then you can register a custom property editor for this very property and throw an exception within setValue method. Like this:

```<code>@InitBinder
private void initBinder(WebDataBinder binder) {
    // binder.setDisallowedFields("property1");
    binder.registerCustomEditor(String.class, "somefield", new PropertyEditorSupport() {
        @Override
        public void setValue(Object value) {
            throw new IllegalStateException();
        }
    });
}
</code>```

Another way is to throw an exception within property setter in Model class. Spring then catch it, wrap into its own org.springframework.validation.BindException and return with 400 bad request.

Title: How to hide @RequestMapping parameter?

Body:
I have a Servlet with a parameter bean. The bean has some fields that should no be able to override by the users get-query.

How can I achieve it?

None of the following worked:

@JsonIgnore
@XmlTransient
@JsonIgnoreProperties
private String somefield;

Run:

localhost:8080/myservlet?somefield=xxx

This will alter the property directly. How can I tell spring to skip that property?

Or even better: let spring reject the request as the user tried to change an unallowed property?

Body:
If by servlet you mean controller you can configure binder to ignore some properties of model class:

@RestController
public class MyServlet {

    @InitBinder
    private void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields("somefield");
    }

    @GetMapping("/myservlet")
    public String myservlet(Model model) {
        return model.toString();
    }
}

Model:

public class Model {
    private String somefield;
    private String property2;
    //getters and setters
}

Another way is to remove the ignored property setter from model class at all. In that case spring will not be able to set the value.

If by servlet you mean servlet then just wrap the request excluding ignoring properties from getParameterMap() call.

Update

If you want to force spring to reject entire request when inappropriate property is set then you can register a custom property editor for this very property and throw an exception within setValue method. Like this:

@InitBinder
private void initBinder(WebDataBinder binder) {
    // binder.setDisallowedFields("property1");
    binder.registerCustomEditor(String.class, "somefield", new PropertyEditorSupport() {
        @Override
        public void setValue(Object value) {
            throw new IllegalStateException();
        }
    });
}

Another way is to throw an exception within property setter in Model class. Spring then catch it, wrap into its own org.springframework.validation.BindException and return with 400 bad request.


答:
Copying the entire class should be the last option, if an option at all.

What I would do is something like this:

```<code>.element {
    background-color: green;
    font-size: 14pt;
    border: 2px;
    width: 150px;
}

.element.on {
    background-color: red;
}
</code>```

.element:hover may make more sense; my answer is more about how to share CSS styles.

Alternatively, you could assign the same styles to multiple classes like this:

```<code>.element.on, .element.off {
    background-color: green;
    font-size: 14pt;
    border: 2px;
    width: 150px;
}

.element.on {
    background-color: red;
}
</code>```

Lastly, CSS pre-compiler languages have features like Mixins in Less, where you can assign a class by name to another class.

Body:
What I'm doing is creating multiple classes for different elements one is a hover class and the other is the non hovered version.  Only one or two things change between the two classes and I don't want to have to copy and paste the whole class over and change just one line.

So what I'd like to do is say have

.hoverOff {
background-color: green;
font-size: 14pt;
border: 2px;
width: 150px;
}

And then I have a hover over class

.hoverOn {
background-color: red;
}

I want to inherit everything else from the hoverOff class and only change the background color.  Can I inherit with CSS like that and overide inherited styles in the new class?  As it stands right now I'm simply copying the entire class, renaming it and changing one line.  Seems pretty redundant and archaic to me.

Body:
Copying the entire class should be the last option, if an option at all.

What I would do is something like this:

.element {
    background-color: green;
    font-size: 14pt;
    border: 2px;
    width: 150px;
}

.element.on {
    background-color: red;
}

.element:hover may make more sense; my answer is more about how to share CSS styles.

Alternatively, you could assign the same styles to multiple classes like this:

.element.on, .element.off {
    background-color: green;
    font-size: 14pt;
    border: 2px;
    width: 150px;
}

.element.on {
    background-color: red;
}

Lastly, CSS pre-compiler languages have features like Mixins in Less, where you can assign a class by name to another class.


问:
Passing a captured binary file through snort
Is it possible to pass pre-captured binary files through snort for analysis (with flagging or detection as the ultimate goal)? </p>

答: You can use -r option for that

Body: You can use -r option for that


问:
How to use transaction in oracle database from java back end?
I have to insert some information to my oracle database. Some of them are complex (array of arrays), so I can't pass them to a PL/SQL function. All the data can't be inserted using one query, and I have to insert data to multiple tables too. But if insertion fails once for a table, the whole insertion process should be rolled back. So I need to use transaction.

I am using java code and PreparedStatement, ResultSet, CallableStatement and other related things to perform database operations from my java back end. How can I define and use transactions from this java back end? Basically I am using Spring MVC.

N.B. No Hibernate related solution please.

答: If you are not using java 8 see oracle full explanation</p>


问:
Solr: getting error on url field while updating
I am trying to update url fields of my Solr documents but i am getting below error

HTTP Error 400: Bad Request

I think it is because of a url field

```<code>image_new_path = https://aaa.com/bbb/posts/post_fta6cueqq1497926075564.jpeg
req = urllib2.Request(url=solrPath + '/update/json?commit=true', data='[{"id":"' + docs['id'] + '","image":{"set":'+image_new_path+'}}]')
</code>```

Is there are some special character which i have to change? If yes which one and how?

Solr error:

```<code>RequestHandlerBase

org.apache.solr.common.SolrException: Cannot parse provided JSON: Expected ',' or '}': char=:,position=41 BEFORE='[{"id":"189","image":{"set":https:' AFTER='//aaa.com/bbb/user'
</code>```

答:
You're missing "" around your image_new_path value, you can fix this by adding "" around it:

```<code>.. {"set":"'+image_new_path+'"}}
</code>```

.. but you should not write JSON manually by concatenating values yourself, as you'll have to take care of following all of JSON's rules when it comes to escaping etc.

Use the built-in support in python for json in the json module instead:

```<code>import json

..

.. data=json.dumps([{'id': docs['id'], 'image': {'set': image_new_path}}])
</code>```

Or maybe even better, use a Solr library such as pysolr or mysolr.

Body:
I am trying to update url fields of my Solr documents but i am getting below error

HTTP Error 400: Bad Request

I think it is because of a url field

image_new_path = https://aaa.com/bbb/posts/post_fta6cueqq1497926075564.jpeg
req = urllib2.Request(url=solrPath + '/update/json?commit=true', data='[{"id":"' + docs['id'] + '","image":{"set":'+image_new_path+'}}]')

Is there are some special character which i have to change? If yes which one and how?

Solr error:

RequestHandlerBase

org.apache.solr.common.SolrException: Cannot parse provided JSON: Expected ',' or '}': char=:,position=41 BEFORE='[{"id":"189","image":{"set":https:' AFTER='//aaa.com/bbb/user'

Body:
You're missing "" around your image_new_path value, you can fix this by adding "" around it:

.. {"set":"'+image_new_path+'"}}

.. but you should not write JSON manually by concatenating values yourself, as you'll have to take care of following all of JSON's rules when it comes to escaping etc.

Use the built-in support in python for json in the json module instead:

import json

..

.. data=json.dumps([{'id': docs['id'], 'image': {'set': image_new_path}}])

Or maybe even better, use a Solr library such as pysolr or mysolr.


问:
How to use await key word on react native?
I tried to use await/async on react native,but I got unexpected token error.

I added the code blow in my javascript source file:

```<code>var value = await AsyncStorage.getItem('STORAGE_KEY');
</code>```

My react native version is 0.15.0.

Do I need to add some configuration to use async/await?

答:
After reading this comment on the react-native GitHub issues, the following worked for me:

Add the following npm module:

npm install babel-preset-react-native-stage-0 --save

Add the following configuration to your .babelrc file:

{ presets: ['react-native-stage-0'] }

Clear your cache:

```<code>$ watchman watch-del-all
$ ./node_modules/react-native/packager/packager.sh --reset-cache
</code>```

Body:
I tried to use await/async on react native,but I got unexpected token error.

I added the code blow in my javascript source file:

var value = await AsyncStorage.getItem('STORAGE_KEY');

My react native version is 0.15.0.

Do I need to add some configuration to use async/await?

Body:
After reading this comment on the react-native GitHub issues, the following worked for me:

Add the following npm module:

npm install babel-preset-react-native-stage-0 --save

Add the following configuration to your .babelrc file:

{ presets: ['react-native-stage-0'] }

Clear your cache:

$ watchman watch-del-all
$ ./node_modules/react-native/packager/packager.sh --reset-cache


问:
Shader that renders transparent instead of a color
I'm totally new to shaders, I never made one

I was wondering if it's possibile to have a shader that renders an unlit texture normally except a specific color, which should be rendered as transparent

kinda like a greenscreen thing and i want to make the shader to render rgba(0,0,0,0) instead of rgba(0,1,0,1)

I know i could just use a texture with alpha, but i need this for a videotexture on mobile, so i thought this was the only option

Thank you in advance for any hint or answer provided

答:
You're looking for a chroma key shader.

There are some details in this Unity forum thread and I think this one will do what you're asking, although another solution might be "more better" depending on what you can do with your video source, etc. Give the thread a read if you can.

```<code>Shader "Matte/RGB Color"
{

Properties {
   _MainTex ("Base (RGB)", 2D) = "white" {}
   _Matte ("Matte Color", Color) = (1,0,1,1)
   _Thresh ("Threshold", Range (0,1)) = 0.0
   _Cutoff ("Cutoff", Range (0,1)) = .5
}

SubShader {

   Pass {
      AlphaTest Less [_Cutoff]
CGPROGRAM
#pragma fragment frag
#include "UnityCG.cginc"

struct v2f {
    float4 pos : POSITION;
    float4 uv : TEXCOORD0;
};

sampler2D _MainTex;
uniform half4 _Matte;
uniform float _Thresh;
uniform float _Cutoff;

half4 frag (v2f i) : COLOR
{
    //return _Matte;
    half4 color = tex2D(_MainTex, i.uv.xy);

    half3 keyMinus = half3( (_Matte.r - _Thresh), (_Matte.g - _Thresh), (_Matte.b - _Thresh) );
    half3 keyPlus = half3( (_Matte.r + _Thresh), (_Matte.g + _Thresh), (_Matte.b + _Thresh) );

    if ( ((color.r > keyMinus.r)  (color.r < keyPlus.r))  ((color.g > keyMinus.g)  (color.g < keyPlus.g))  ((color.b > keyMinus.b)  (color.b < keyPlus.b)) )
    {
        return _Cutoff;
    }

    return float4(color.rgb, max(0, _Cutoff-0.01));
}

ENDCG
      } // pass
   } // subshader
   //Fallback "Transparent/Diffuse"
} // shader
</code>```

There are also assets on the asset store, such as this one ($8) which may work better or which may not.

Body:
You're looking for a chroma key shader.

There are some details in this Unity forum thread and I think this one will do what you're asking, although another solution might be "more better" depending on what you can do with your video source, etc. Give the thread a read if you can.

Shader "Matte/RGB Color"
{

Properties {
   _MainTex ("Base (RGB)", 2D) = "white" {}
   _Matte ("Matte Color", Color) = (1,0,1,1)
   _Thresh ("Threshold", Range (0,1)) = 0.0
   _Cutoff ("Cutoff", Range (0,1)) = .5
}

SubShader {

   Pass {
      AlphaTest Less [_Cutoff]
CGPROGRAM
#pragma fragment frag
#include "UnityCG.cginc"

struct v2f {
    float4 pos : POSITION;
    float4 uv : TEXCOORD0;
};

sampler2D _MainTex;
uniform half4 _Matte;
uniform float _Thresh;
uniform float _Cutoff;

half4 frag (v2f i) : COLOR
{
    //return _Matte;
    half4 color = tex2D(_MainTex, i.uv.xy);

    half3 keyMinus = half3( (_Matte.r - _Thresh), (_Matte.g - _Thresh), (_Matte.b - _Thresh) );
    half3 keyPlus = half3( (_Matte.r + _Thresh), (_Matte.g + _Thresh), (_Matte.b + _Thresh) );

    if ( ((color.r > keyMinus.r)  (color.r < keyPlus.r))  ((color.g > keyMinus.g)  (color.g < keyPlus.g))  ((color.b > keyMinus.b)  (color.b < keyPlus.b)) )
    {
        return _Cutoff;
    }

    return float4(color.rgb, max(0, _Cutoff-0.01));
}

ENDCG
      } // pass
   } // subshader
   //Fallback "Transparent/Diffuse"
} // shader

There are also assets on the asset store, such as this one ($8) which may work better or which may not.


问:
WPF - Binding problem
Why after clicking the button the text in the textblock doesn't change ?

XAML:

```<code> <Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <TextBlock Text="{Binding Name}"/>
    <Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button>
</Grid>
</code>```

Code behind:

```<code>  public partial class Window1 : Window, INotifyPropertyChanged
{
    private Person _myPerson;
    public Person MyPerson
    {
        get { return _myPerson; }
        set
        {
            _myPerson = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("MyPerson"));
            }
        }
    }

    public Window1()
    {
        MyPerson = new Person { Name = "A" };
        DataContext = MyPerson;
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyPerson = new Person { Name = "B" };
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}
</code>```

答:
```<code><TextBlock Text="{Binding Name}"/>
</code>```

In above code you bind property Name with text box and in following code:

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    MyPerson = new Person { Name = "B" };
}
</code>```

You set MyPerson to new person.

Is that intended? And does Person class implement INotifyPropertyChanged event?

You are only updating MyPerson property. DataContext still has a reference to the object you create using following line:

```<code>MyPerson = new Person { Name = "A" };
</code>```

in constructor. You need to update DataContext as well.

Instead, use following code:

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    MyPerson = new Person { Name = "B" };
    DataContext = MyPerson;
}
</code>```

Title: WPF - Binding problem

Body:
Why after clicking the button the text in the textblock doesn't change ?

XAML:

 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <TextBlock Text="{Binding Name}"/>
    <Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button>
</Grid>

Code behind:

  public partial class Window1 : Window, INotifyPropertyChanged
{
    private Person _myPerson;
    public Person MyPerson
    {
        get { return _myPerson; }
        set
        {
            _myPerson = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("MyPerson"));
            }
        }
    }

    public Window1()
    {
        MyPerson = new Person { Name = "A" };
        DataContext = MyPerson;
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyPerson = new Person { Name = "B" };
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

Body:
<TextBlock Text="{Binding Name}"/>

In above code you bind property Name with text box and in following code:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyPerson = new Person { Name = "B" };
}

You set MyPerson to new person.

Is that intended? And does Person class implement INotifyPropertyChanged event?

You are only updating MyPerson property. DataContext still has a reference to the object you create using following line:

MyPerson = new Person { Name = "A" };

in constructor. You need to update DataContext as well.

Instead, use following code:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyPerson = new Person { Name = "B" };
    DataContext = MyPerson;
}