问:
Initialize and declare variable in if-else condition in JAVA
I'm trying to initialize and declare variable in if-else condition in JAVA, but it is not executing, can someone please help me in below code?

This is the method, which I'm calling from main method. But it's not executing the initialization under if condition and failing.

```<code>    public static void getData(String funct) {
            try {
                    if ("lob".equals(funct)) {
                            String sql1= String.format("select distinct lob_name from BPUSH_lobs order by lob_name");
                    }
                    else {
                            String sql1= String.format("select distinct env_type from BPUSH_environments order by env_type");
                    }
                    Connection conn=DriverManager.getConnection
                    ("jdbc:oracle:thin:@172.23.240.41:1521:BCTOOLS","AMCOPR","AMCOPR");

                    Statement stmt = conn.createStatement();
                    ResultSet rst;

                    System.out.println(funct);

                    rst = stmt.executeQuery(sql1);

                    while (rst.next()) {
                            String lobName = rst.getString("lob_name");
                            System.out.format("%s\n",lobName);
                    }

                    conn.close();
            }
            catch (Exception e) {
                    System.err.println("Got an exception! ");
                    System.err.println(e.getMessage());
            }
    }
</code>```

}

PLEASE HELP :)
Thanks,

答:
Declare sql1 outside if-else as below,</p>

```<code>    String sql1= "";

    if ("lob".equals(funct)) {
       sql1= String.format("select distinct lob_name from BPUSH_lobs order by lob_name");
    } else {
       sql1= String.format("select distinct env_type from BPUSH_environments order by env_type");
    }
</code>```

Body:
I'm trying to initialize and declare variable in if-else condition in JAVA, but it is not executing, can someone please help me in below code?

This is the method, which I'm calling from main method. But it's not executing the initialization under if condition and failing.

    public static void getData(String funct) {
            try {
                    if ("lob".equals(funct)) {
                            String sql1= String.format("select distinct lob_name from BPUSH_lobs order by lob_name");
                    }
                    else {
                            String sql1= String.format("select distinct env_type from BPUSH_environments order by env_type");
                    }
                    Connection conn=DriverManager.getConnection
                    ("jdbc:oracle:thin:@172.23.240.41:1521:BCTOOLS","AMCOPR","AMCOPR");

                    Statement stmt = conn.createStatement();
                    ResultSet rst;

                    System.out.println(funct);

                    rst = stmt.executeQuery(sql1);

                    while (rst.next()) {
                            String lobName = rst.getString("lob_name");
                            System.out.format("%s\n",lobName);
                    }

                    conn.close();
            }
            catch (Exception e) {
                    System.err.println("Got an exception! ");
                    System.err.println(e.getMessage());
            }
    }

}

PLEASE HELP :)
Thanks,

Body:
Declare sql1 outside if-else as below,

    String sql1= "";

    if ("lob".equals(funct)) {
       sql1= String.format("select distinct lob_name from BPUSH_lobs order by lob_name");
    } else {
       sql1= String.format("select distinct env_type from BPUSH_environments order by env_type");
    }


来源: stackexchange

问:
Scenarios where automated testing is unhelpful
What are some situations where unit testing and TDD and the like are more trouble than they're worth?

Some things I've come up with are:

When generating test data is tricky: Sometimes, being able to come up with valid, non trivial test data is a challenge in itself.

When the only practical way of verifying correctness of the code is to run it.

When you're testing visual elements of the design.

What are some other cases?

答:
I wouldn't say there are any cases where automated testing is unhelpful.

There are certainly those where it s less helpful.  I don't think creating fixture data is one of them.  There are tools to help, like factory_girl (in Ruby, at least).  In fact, if your model is so complicated that you need to create a dozen objects with all sorts of associations, I'd consider that a code smell and maybe the model isn't as concise as it could be.

That said, there are a couple cases where the drawbacks possibly outweigh the benefits.  I wrote some code the other day that forks an external process.  I don't care about the output, I don't care about the return code, I don't even care if it worked right, it's totally fire and forget and another process will come clean up if something didn't work right, later.

In that case I didn't bother writing any tests because the benefit wasn't worth the time of setting up a fake external program to verify my arguments, etc, etc.

OwnerDisplayName: Shalmanese

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Otto


问:
php user rights to write onto server during sessions
I need an advice for the following scenario:

I've build an admin section for a website which provides functions to update a website when new content is entered in a text file on the server. The admin section has a button, which calls a function so the text file gets parsed and a html file is written.

The issue is that the folder in which the html is written needs to be chmod 777, because the called script is available through an url.

What I want to avoid is to set every folder in which something gets written to 777, because the root folder also needs 777, but I don't have the rights to set chmod for the root folder.

My idea is to make a login which connects to the ftp account, so that the person who has entered the right login data is registered as the ftp user and so the 777 chmod could be turned into 755.
Is this possible? How long does a session last when I use ftp_connect (when I redirect to another php srcipt which also needs user rights)?
Is there a more common solution for this kind of problem?

答:
You simply need to change the owner of the folder to match the user:group that the webserver is running as.

For instance, if you're running Apache HTTPD on ubuntu, apache will be running as the www-data user and group.

You can then run:

```<code>$  chown www-data:www-data /var/www/html/yourwebapp/folder_you_want_to_write_in
$  chmod 755 /var/www/html/yourwebapp/folder_you_want_to_write_in
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You simply need to change the owner of the folder to match the user:group that the webserver is running as.

For instance, if you're running Apache HTTPD on ubuntu, apache will be running as the www-data user and group.

You can then run:

$  chown www-data:www-data /var/www/html/yourwebapp/folder_you_want_to_write_in
$  chmod 755 /var/www/html/yourwebapp/folder_you_want_to_write_in


问:
How do I fix " 'tuple' object does not support item assignment " in my code?
```<code>import math
def ListSqrRoot(nums):
    n=len(nums)
    for i in range(n):
        nums[i]=math.sqrt(nums[i])

def main():
    nums=eval(input("Please enter a list of numbers:"))
    print( "Before calling the function your list is:")
    print (nums)
    ListSqrRoot(nums)
    print ("After calling the function your list is:")
    print (nums)

main()
</code>```

答:
The problem is that eval(input("Please enter a list of numbers:")) returns a tuple which is immutable and you're trying to modify it here:

```<code>nums[i] = math.sqrt(nums[i])
</code>```

It can be fixed by creating a list instead:

```<code>nums = [x for x in eval(input("Please enter a list of numbers:"))]
</code>```

Warning: eval is evil!

ContentLicense: CC BY-SA 3.0

Body:
The problem is that eval(input("Please enter a list of numbers:")) returns a tuple which is immutable and you're trying to modify it here:

nums[i] = math.sqrt(nums[i])

It can be fixed by creating a list instead:

nums = [x for x in eval(input("Please enter a list of numbers:"))]

Warning: eval is evil!


问:
android different marker touch event to each marker
I'm trying to add different marker touch event for each marker on google map. I  have created separate object to each marker and added touch event listener to each of them. But when i click on each of the marker the output is the same for each of the marker. Need help!!!

答:
First of all you don't need to create separate objects of every marker , you can identify marker in "OnMarkerClickListener()" listener ,use conditional statements (if ,else-if,else) and do whatever you wanna do in those conditions.
create an array of different titles of marker & use it while you are adding marker to the map by looping or whatever you prefer.    </p>

```<code> mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
      @Override
      public boolean onMarkerClick(Marker marker) {
       if (marker.getTitle().toString().equals("Current Location"))
         {
           //do code here for current location marker.
          }else if(marker.getTitle().toString().equals("Secondary Location")){
             //do code here for Secondary location marker.
           }
            return true;
        }
    });
</code>```

Body:
First of all you don't need to create separate objects of every marker , you can identify marker in "OnMarkerClickListener()" listener ,use conditional statements (if ,else-if,else) and do whatever you wanna do in those conditions.
create an array of different titles of marker & use it while you are adding marker to the map by looping or whatever you prefer.

 mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
      @Override
      public boolean onMarkerClick(Marker marker) {
       if (marker.getTitle().toString().equals("Current Location"))
         {
           //do code here for current location marker.
          }else if(marker.getTitle().toString().equals("Secondary Location")){
             //do code here for Secondary location marker.
           }
            return true;
        }
    });


问:
Lift Web Framework query string generator
How do you create a link with query string parameters:

```<code>/path/to/view?param=358&name=Something+with+spaces
</code>```

in Lift? I know you can simply write it, I am looking for a wise approach, which encode spaces and other special characters. For example:

```<code>Link("path/to/view").param("param", 358).param("name", "Something with spaces")
</code>```

Thanks in advance,
Etam.

答:
There is appendParams method in net.liftweb.util.HttpHelpers trait:

```<code>import net.liftweb._
import util.Helpers._

val url = appendParams("/path/to/view",
                      ("param" -> "358") ::
                      ("name" -> "Something with spaces") :: Nil)
</code>```

Reply from Scala REPL:

```<code>url: String = /path/to/view?param=358&name=Something+with+spaces
</code>```

As you can see, it gets URL as a String, Seq of param tuples and finally returns String.

Body:
How do you create a link with query string parameters:

/path/to/view?param=358&name=Something+with+spaces

in Lift? I know you can simply write it, I am looking for a wise approach, which encode spaces and other special characters. For example:

Link("path/to/view").param("param", 358).param("name", "Something with spaces")

Thanks in advance,
Etam.

Body:
There is appendParams method in net.liftweb.util.HttpHelpers trait:

import net.liftweb._
import util.Helpers._

val url = appendParams("/path/to/view",
                      ("param" -> "358") ::
                      ("name" -> "Something with spaces") :: Nil)

Reply from Scala REPL:

url: String = /path/to/view?param=358&name=Something+with+spaces

As you can see, it gets URL as a String, Seq of param tuples and finally returns String.


问:
Split a comma delimited string which may contain commas and escaped quotes between single quotes
How do you split a comma delimiter string. The string is a series of comma delimited numbers and words. Words are quoted with single quotes and numbers are not. Words may contain non-delimiting commas which should be fine inside quotes. Words may contain other kinds of quotes which must be escaped by a preceding backslash like so:

```<code>'','some-mail@some-domain.org','f4c1bfd5-969d-\'4,7\"2a-,b1\'29-42de49eb4406',2827,1378614418
</code>```

I have tried to use a regex [^\'] to split but that also picks up escaped commas.

I have tried literally counting the characters as an alternative but that is deathly slow.

Also python's csv reader splits the string on the non-delimiting commas if there are escaped slashes in the string. Perhaps it's not valid CSV?

The sub-string list I should have as a result is:

```<code>[
'', # empty string
'some-mail@some-domain.org', # text like email
'f4c1bfd5-969d-\'4,7\"2a-,b1\'29-42de49eb4406', # text, comma and escaped quotes
2827, # number
1378614418 # number
]
</code>```

This is how I have used the csv module:

```<code>reader = csv.reader(StringIO(values_string), delimiter=',', quotechar="'", quoting=csv.QUOTE_ALL,skipinitialspace=True)
</code>```

But I get:

```<code>['', 'some-mail@some-domain.org', 'f4c1bfd5-969d-\\4', '7\\"2a-', "b1\\'29-42de49eb4406'", '2827', '1378614418']
</code>```

答:
```<code>with open(file_name) as fp:
    reader = csv.reader(fp, quotechar="'", doublequote=False, escapechar='\\')
</code>```

Body:
How do you split a comma delimiter string. The string is a series of comma delimited numbers and words. Words are quoted with single quotes and numbers are not. Words may contain non-delimiting commas which should be fine inside quotes. Words may contain other kinds of quotes which must be escaped by a preceding backslash like so:

'','some-mail@some-domain.org','f4c1bfd5-969d-\'4,7\"2a-,b1\'29-42de49eb4406',2827,1378614418

I have tried to use a regex [^\'] to split but that also picks up escaped commas.

I have tried literally counting the characters as an alternative but that is deathly slow.

Also python's csv reader splits the string on the non-delimiting commas if there are escaped slashes in the string. Perhaps it's not valid CSV?

The sub-string list I should have as a result is:

[
'', # empty string
'some-mail@some-domain.org', # text like email
'f4c1bfd5-969d-\'4,7\"2a-,b1\'29-42de49eb4406', # text, comma and escaped quotes
2827, # number
1378614418 # number
]

This is how I have used the csv module:

reader = csv.reader(StringIO(values_string), delimiter=',', quotechar="'", quoting=csv.QUOTE_ALL,skipinitialspace=True)

But I get:

['', 'some-mail@some-domain.org', 'f4c1bfd5-969d-\\4', '7\\"2a-', "b1\\'29-42de49eb4406'", '2827', '1378614418']


问:
Status bar color changed to white in custom navigation drawer in iOS?
I have created a custom navigation drawer in swift. I have used the window from app delegate & added a view on winddow. After i hide show the view on button click.

Below code to create drawer.

```<code>func setupSideMenu(){

        windowSideMenu = ((UIApplication.shared.delegate?.window)!)!
        windowSideMenu.backgroundColor = UIColor.black
        if customView == nil {
            print("custom view nil")
            // Register Swipe gesture for opening slideMenu
            let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.openSideMenu))
            swipeRight.direction = UISwipeGestureRecognizerDirection.right
            self.view.addGestureRecognizer(swipeRight)

            /// Register Drawable NIB here only for once
            customView = SideView.instanceFromNib() as! SideView
            customView.configureDrawer()
            customView.navigationController = self.navigationController
            customView.frame = CGRect(x: -customView.frame.size.width, y: -10, width: self.view.bounds.size.width - 30, height:UIScreen.main.bounds.height)
            customView.drawerDelegate = self

            /// BackView (DimView)
            backView.frame = self.view.frame
            backView.backgroundColor = UIColor.black
            backView.alpha = 0.4
            backView.isHidden = true
            self.view.addSubview(backView)
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.closeSideMenu))
            backView.addGestureRecognizer(tapGesture)
            customView.isHidden = true
            windowSideMenu.addSubview(customView)
            windowSideMenu.makeKeyAndVisible()

        }
    }
</code>```

On hide & show i change the window level UIWindowLevel.

```<code>  override func openSideMenu() {
        super.openSideMenu()
        self.windowSideMenu.windowLevel = UIWindowLevelStatusBar
    }

    override func closeSideMenu() {
        super.closeSideMenu()
        self.windowSideMenu.windowLevel = UIWindowLevelNormal

    }
</code>```

But when i change the windowlevel to UIWindowLevelStatusBar then the color of status bar is setting white.

Here is the screen shot for drawer

Sorry i had to change some colors as i can't show the whole design.

答:
For your answer different possibilities is there..

POSSIBLE WAY : 1

If you are using xcode 9.0+ so iPhone X is available in simulator and new concept of safe view is there, so you give top constraint to the safe view so this white strip available behind the status bar. (If mention detail related to you so solution is give constraints to the main view not to the safeView) or you can also try below code..

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        UIApplication.shared.statusBarView?.backgroundColor = UIColor.black

        return true
    }
</code>```

POSSIBLE WAY : 2

And one library is available for this slide effect. It's name is SlideMenuControllerSwift

In this library different option is available so from them you can change status bar.

```<code>SlideMenuOptions.contentViewScale = 1.0
        SlideMenuOptions.leftViewWidth = UIScreen.main.bounds.size.width * 0.6

        let leftVC = UIStoryboard().getViewController(viewController: "LeftView") as! LeftView
        let mainVC = UIStoryboard().getViewController(viewController: "MenuView")

        let slideMenuController = SlideMenuController(mainViewController: mainVC, leftMenuViewController: leftVC)
        SlideMenuOptions.hideStatusBar = false

        self.window?.rootViewController = slideMenuController
        self.window?.makeKeyAndVisible()
</code>```

POSSIBLE WAY : 3

So add this into info.plist and then apply below changes as per your requirement.

So from this 3 ways try any one may it help you to solve your problem.
Happy coding : )

Body:
I have created a custom navigation drawer in swift. I have used the window from app delegate & added a view on winddow. After i hide show the view on button click.

Below code to create drawer.

func setupSideMenu(){

        windowSideMenu = ((UIApplication.shared.delegate?.window)!)!
        windowSideMenu.backgroundColor = UIColor.black
        if customView == nil {
            print("custom view nil")
            // Register Swipe gesture for opening slideMenu
            let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.openSideMenu))
            swipeRight.direction = UISwipeGestureRecognizerDirection.right
            self.view.addGestureRecognizer(swipeRight)

            /// Register Drawable NIB here only for once
            customView = SideView.instanceFromNib() as! SideView
            customView.configureDrawer()
            customView.navigationController = self.navigationController
            customView.frame = CGRect(x: -customView.frame.size.width, y: -10, width: self.view.bounds.size.width - 30, height:UIScreen.main.bounds.height)
            customView.drawerDelegate = self

            /// BackView (DimView)
            backView.frame = self.view.frame
            backView.backgroundColor = UIColor.black
            backView.alpha = 0.4
            backView.isHidden = true
            self.view.addSubview(backView)
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.closeSideMenu))
            backView.addGestureRecognizer(tapGesture)
            customView.isHidden = true
            windowSideMenu.addSubview(customView)
            windowSideMenu.makeKeyAndVisible()

        }
    }

On hide & show i change the window level UIWindowLevel.

  override func openSideMenu() {
        super.openSideMenu()
        self.windowSideMenu.windowLevel = UIWindowLevelStatusBar
    }

    override func closeSideMenu() {
        super.closeSideMenu()
        self.windowSideMenu.windowLevel = UIWindowLevelNormal

    }

But when i change the windowlevel to UIWindowLevelStatusBar then the color of status bar is setting white.

Here is the screen shot for drawer

Sorry i had to change some colors as i can't show the whole design.

Body:
For your answer different possibilities is there..

POSSIBLE WAY : 1

If you are using xcode 9.0+ so iPhone X is available in simulator and new concept of safe view is there, so you give top constraint to the safe view so this white strip available behind the status bar. (If mention detail related to you so solution is give constraints to the main view not to the safeView) or you can also try below code..

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        UIApplication.shared.statusBarView?.backgroundColor = UIColor.black

        return true
    }

POSSIBLE WAY : 2

And one library is available for this slide effect. It's name is SlideMenuControllerSwift

In this library different option is available so from them you can change status bar.

SlideMenuOptions.contentViewScale = 1.0
        SlideMenuOptions.leftViewWidth = UIScreen.main.bounds.size.width * 0.6

        let leftVC = UIStoryboard().getViewController(viewController: "LeftView") as! LeftView
        let mainVC = UIStoryboard().getViewController(viewController: "MenuView")

        let slideMenuController = SlideMenuController(mainViewController: mainVC, leftMenuViewController: leftVC)
        SlideMenuOptions.hideStatusBar = false

        self.window?.rootViewController = slideMenuController
        self.window?.makeKeyAndVisible()

POSSIBLE WAY : 3

So add this into info.plist and then apply below changes as per your requirement.

So from this 3 ways try any one may it help you to solve your problem.
Happy coding : )


问:
Self-defined function in PHP not working
Self-defined function in PHP not working for some cases.

Code:

```<code><?php
function short_format_indian_c($n) {
    $precision = 3;
    $n_format = number_format($n / 1000, $precision);
    $n_format = number_format($n_format, 2);
    $n_format = $n_format + 0;
    $n_format = $n_format . ' K';
    return $n_format;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
    var checkState = function(){
        var tq = jQuery('#tq');
        tq.html(18000);
    }
    checkState();
    setInterval(checkState, 1000);
</script>
<?php $tq = '<span id="tq"></span>';?><?php echo short_format_indian_c($tq); ?>
</code>```

If I use echo short_format_indian_c(1800) it is giving me the result as 18 K.

But when I use echo short_format_indian_c($tq) it is giving me the result as 0 K, where $tq is also 18000

答:
Well, your function expects one parameter. When you call it in your code

```<code><?php echo short_format_indian_c($tq); ?>
</code>```

You pass $tq as an argument. $tq at the moment is equal to ""

```<code><?php $tq = '<span id="tq"></span>';?>
</code>```

Inside of your function you perform a division on argument which in this case is a string. As a result of that process string will be casted to int and will be equal to 0. So you will get 0 K.

On the other hand, when you pass 18000 as an argument everything will work as you expect.

Body:
Self-defined function in PHP not working for some cases.

Code:

<?php
function short_format_indian_c($n) {
    $precision = 3;
    $n_format = number_format($n / 1000, $precision);
    $n_format = number_format($n_format, 2);
    $n_format = $n_format + 0;
    $n_format = $n_format . ' K';
    return $n_format;
}
?>

<?php $tq = '';?><?php echo short_format_indian_c($tq); ?>

If I use echo short_format_indian_c(1800) it is giving me the result as 18 K.

But when I use echo short_format_indian_c($tq) it is giving me the result as 0 K, where $tq is also 18000

Body:
Well, your function expects one parameter. When you call it in your code

<?php echo short_format_indian_c($tq); ?>

You pass $tq as an argument. $tq at the moment is equal to ""

<?php $tq = '<span id="tq"></span>';?>

Inside of your function you perform a division on argument which in this case is a string. As a result of that process string will be casted to int and will be equal to 0. So you will get 0 K.

On the other hand, when you pass 18000 as an argument everything will work as you expect.


问:
Count no of records as per the date from table and format the date using PHP and MySQL
I need to etch no of records as per the date filed and after fetching the data I need to format the date using PHP and MySQL. I am explaining my table below.

db_audit:

```<code>id        auditname         date
 1          xxxx            2017-12-01 12:26:49
 2          sss             2017-12-01 12:20:00
 3         fff              2017-12-01 12:00:00
 4        hhh              2017-12-02 12:27:49
 5        ttt              2017-12-02 11:26:49
 6       yyy               2017-12-03 10:26:49
</code>```

Here I need to fetch no of records as per the date only. Here for 2017-12-01 there are 3 records present. I need to push all data into an array like this key format {'no_records'=>3,'date'=>2017-12-01}. Here also I need to formatted the database date field value from 2017-12-03 10:26:49 to 2017-12-03 and it should be in string format. Here I need the query to retrieve these type of value.

答:
You can query like below to get date in the required format

```<code>select count(*), DATE_FORMAT(dateTimeColumnName,'%Y-%m-%d') as date from tableName group by DATE_FORMAT(dateTimeColumnName,'%Y-%m-%d');
</code>```

This will give you result number of rows per day

Example

```<code>+-------+------------+
| count | date       |
+-------+------------+
|     3 | 2017-12-03 |
|     1 | 2017-12-04 |
|     1 | 2017-12-05 |
+-------+------------+
</code>```

Body:
I need to etch no of records as per the date filed and after fetching the data I need to format the date using PHP and MySQL. I am explaining my table below.

db_audit:

id        auditname         date
 1          xxxx            2017-12-01 12:26:49
 2          sss             2017-12-01 12:20:00
 3         fff              2017-12-01 12:00:00
 4        hhh              2017-12-02 12:27:49
 5        ttt              2017-12-02 11:26:49
 6       yyy               2017-12-03 10:26:49

Here I need to fetch no of records as per the date only. Here for 2017-12-01 there are 3 records present. I need to push all data into an array like this key format {'no_records'=>3,'date'=>2017-12-01}. Here also I need to formatted the database date field value from 2017-12-03 10:26:49 to 2017-12-03 and it should be in string format. Here I need the query to retrieve these type of value.

Body:
You can query like below to get date in the required format

select count(*), DATE_FORMAT(dateTimeColumnName,'%Y-%m-%d') as date from tableName group by DATE_FORMAT(dateTimeColumnName,'%Y-%m-%d');

This will give you result number of rows per day

Example

+-------+------------+
| count | date       |
+-------+------------+
|     3 | 2017-12-03 |
|     1 | 2017-12-04 |
|     1 | 2017-12-05 |
+-------+------------+


问:
How to render image/pdf in Http Module
I have two website (Web1 and Web2) and one domain (www.web1.com). Domain is mapped to Web1.

I have one http Module registered in Web1. When Request comes to Web1 and web page exist on Web1, it will display the Page. Otherwise page not found (404) on Web1, then module will send request to Web2 and get the response from Web2 and write to display.

Here is my http Module code:

```<code>    public class Testmodule : IHttpModule
{
    public void Dispose()
    {
        //clean-up code here.
    }
    public void Init(HttpApplication context)
    {
        context.PreSendRequestContent += context_PreSendRequestContent;
    }
    private void context_PreSendRequestContent(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        if (context.Response.StatusCode == 404)//On 404 on Web1 it will pass the the condition.
        {
            string strSite = WebConfigurationManager.AppSettings["Web2SiteURL"];
            string requestURL = ((HttpApplication)sender).Request.Url.ToString();
            string sourceURL = requestURL.Replace("http://" + HttpContext.Current.Request.Url.Authority, strSite);

            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(sourceURL);
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

            string WebResp_html = string.Empty;
            using (StreamReader sr = new StreamReader(WebResp.GetResponseStream()))
            {
                WebResp_html = sr.ReadToEnd();
            }
            string strCurrentUrl = "http://" + HttpContext.Current.Request.Url.Authority + "/";

            //Replacing the image src Relative URL to Absolute URL in the html source code.
            //If I comment below Replacement code Page is rendering but images are not rendering from Web2 site.
            //Actually  the image/pdf/swg files from html source code with relative path not rendering properly.
            WebResp_html = WebResp_html.Replace(strSite, strCurrentUrl);

            context.Response.Write(WebResp_html);
            context.Response.Flush();
            context.Response.Close();

        }
    }
}
</code>```

Below is code of my code for Web2 Page2

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        This is my Page 2 on Web2.
        <br/>
    <p><img width="312" height="312" class="images" alt="" src="Images/Img1.jpg"/></p>
    </div>
    </form>
</body>
</html>
</code>```

It works fine for html tag. But could not render images with relative path. If I make the image src to absolute path then it render properly.

If I comment below Replacement code Page is rendering but images are not rendering from Web2 site (with relative path).

```<code>WebResp_html = WebResp_html.Replace(strSite, strCurrentUrl); //converting image src from relative to absolute path.
</code>```

Question : How can I render image on web page with relative path?
  Please help me..

答: Page from Website 2 will be a cross-origin request for Website1. So, You must refer absolute paths to be able to render images from Website2. if you want to refer relative paths, those images must be part of Website1.</p>

Title: How to render image/pdf in Http Module

Body:
I have two website (Web1 and Web2) and one domain (www.web1.com). Domain is mapped to Web1.

I have one http Module registered in Web1. When Request comes to Web1 and web page exist on Web1, it will display the Page. Otherwise page not found (404) on Web1, then module will send request to Web2 and get the response from Web2 and write to display.

Here is my http Module code:

    public class Testmodule : IHttpModule
{
    public void Dispose()
    {
        //clean-up code here.
    }
    public void Init(HttpApplication context)
    {
        context.PreSendRequestContent += context_PreSendRequestContent;
    }
    private void context_PreSendRequestContent(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        if (context.Response.StatusCode == 404)//On 404 on Web1 it will pass the the condition.
        {
            string strSite = WebConfigurationManager.AppSettings["Web2SiteURL"];
            string requestURL = ((HttpApplication)sender).Request.Url.ToString();
            string sourceURL = requestURL.Replace("http://" + HttpContext.Current.Request.Url.Authority, strSite);

            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(sourceURL);
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

            string WebResp_html = string.Empty;
            using (StreamReader sr = new StreamReader(WebResp.GetResponseStream()))
            {
                WebResp_html = sr.ReadToEnd();
            }
            string strCurrentUrl = "http://" + HttpContext.Current.Request.Url.Authority + "/";

            //Replacing the image src Relative URL to Absolute URL in the html source code.
            //If I comment below Replacement code Page is rendering but images are not rendering from Web2 site.
            //Actually  the image/pdf/swg files from html source code with relative path not rendering properly.
            WebResp_html = WebResp_html.Replace(strSite, strCurrentUrl);

            context.Response.Write(WebResp_html);
            context.Response.Flush();
            context.Response.Close();

        }
    }
}

Below is code of my code for Web2 Page2

    <title></title>

    <form id="form1" runat="server">

        This is my Page 2 on Web2.

    </form>

It works fine for html tag. But could not render images with relative path. If I make the image src to absolute path then it render properly.

If I comment below Replacement code Page is rendering but images are not rendering from Web2 site (with relative path).

WebResp_html = WebResp_html.Replace(strSite, strCurrentUrl); //converting image src from relative to absolute path.

Question : How can I render image on web page with relative path?
  Please help me..


问:
SQL Server 2008 R2: Get first not null values from column
I have following tables to display the expected result.

Table:

```<code>CREATE TABLE Family
(
    ID int,
    Name varchar(20),
    Gender char(1)
);

INSERT INTO Family VALUES
(1,'Ram','M'),
(2,'Suraj','M'),
(3,'Sunitha','F'),
(4,'Deepika','F'),
(5,'Minakshi','F'),
(6,'Somu','M');

CREATE TABLE Child_parent
(
    Child_ID int,
    Parent_ID int
);

INSERT INTO Child_parent VALUES
(1,2),
(1,3),
(4,5),
(4,6);
</code>```

Expected Result:

```<code>Child_ID    ChildName   FatherName  MotherName
-----------------------------------------------
1           Ram         Suraj       Sunitha
4           Deepika     Somu        Minakshi
</code>```

My try:

```<code>SELECT  cp.Child_ID,
        f1.Name as ChildName,
        CASE WHEN f2.Gender = 'M' THEN f2.Name END FatherName,
        CASE WHEN f2.Gender = 'F' THEN f2.Name END MotherName
FROM Child_parent cp
LEFT JOIN Family f1
ON cp.Child_ID = f1.ID
LEFT JOIN Family f2
ON cp.Parent_ID = f2.ID
</code>```

But getting result shows:

```<code>Child_ID    ChildName   FatherName  MotherName
----------------------------------------------
1           Ram         Suraj       NULL
1           Ram         NULL        Sunitha
4           Deepika     NULL        Minakshi
4           Deepika     Somu        NULL
</code>```

答:
This is an alternative solution with single JOIN.

```<code>SELECT CP.Child_ID,
    MAX(CASE WHEN CP.Parent_ID <> F.ID THEN F.Name END) ChildName,
    MAX(CASE WHEN CP.Parent_ID = F.ID AND F.Gender ='M' THEN F.Name END) FatherName,
    MAX(CASE WHEN CP.Parent_ID = F.ID AND F.Gender ='F' THEN F.Name END) MotherName
FROM
    Child_parent CP
    LEFT JOIN Family F ON CP.Parent_ID = F.ID OR CP.Child_ID = F.ID
GROUP BY
    Child_ID
</code>```

Body:
I have following tables to display the expected result.

Table:

CREATE TABLE Family
(
    ID int,
    Name varchar(20),
    Gender char(1)
);

INSERT INTO Family VALUES
(1,'Ram','M'),
(2,'Suraj','M'),
(3,'Sunitha','F'),
(4,'Deepika','F'),
(5,'Minakshi','F'),
(6,'Somu','M');

CREATE TABLE Child_parent
(
    Child_ID int,
    Parent_ID int
);

INSERT INTO Child_parent VALUES
(1,2),
(1,3),
(4,5),
(4,6);

Expected Result:

Child_ID    ChildName   FatherName  MotherName
-----------------------------------------------
1           Ram         Suraj       Sunitha
4           Deepika     Somu        Minakshi

My try:

SELECT  cp.Child_ID,
        f1.Name as ChildName,
        CASE WHEN f2.Gender = 'M' THEN f2.Name END FatherName,
        CASE WHEN f2.Gender = 'F' THEN f2.Name END MotherName
FROM Child_parent cp
LEFT JOIN Family f1
ON cp.Child_ID = f1.ID
LEFT JOIN Family f2
ON cp.Parent_ID = f2.ID

But getting result shows:

Child_ID    ChildName   FatherName  MotherName
----------------------------------------------
1           Ram         Suraj       NULL
1           Ram         NULL        Sunitha
4           Deepika     NULL        Minakshi
4           Deepika     Somu        NULL

Body:
This is an alternative solution with single JOIN.

SELECT CP.Child_ID,
    MAX(CASE WHEN CP.Parent_ID <> F.ID THEN F.Name END) ChildName,
    MAX(CASE WHEN CP.Parent_ID = F.ID AND F.Gender ='M' THEN F.Name END) FatherName,
    MAX(CASE WHEN CP.Parent_ID = F.ID AND F.Gender ='F' THEN F.Name END) MotherName
FROM
    Child_parent CP
    LEFT JOIN Family F ON CP.Parent_ID = F.ID OR CP.Child_ID = F.ID
GROUP BY
    Child_ID


答:
If you declare a variable inside of block, you cannot access that from outside.

Declare String sql1 outside if statement and change the value.

Title: Initialize and declare variable in if-else condition in JAVA

Body:
I'm trying to initialize and declare variable in if-else condition in JAVA, but it is not executing, can someone please help me in below code?

This is the method, which I'm calling from main method. But it's not executing the initialization under if condition and failing.

    public static void getData(String funct) {
            try {
                    if ("lob".equals(funct)) {
                            String sql1= String.format("select distinct lob_name from BPUSH_lobs order by lob_name");
                    }
                    else {
                            String sql1= String.format("select distinct env_type from BPUSH_environments order by env_type");
                    }
                    Connection conn=DriverManager.getConnection
                    ("jdbc:oracle:thin:@172.23.240.41:1521:BCTOOLS","AMCOPR","AMCOPR");

                    Statement stmt = conn.createStatement();
                    ResultSet rst;

                    System.out.println(funct);

                    rst = stmt.executeQuery(sql1);

                    while (rst.next()) {
                            String lobName = rst.getString("lob_name");
                            System.out.format("%s\n",lobName);
                    }

                    conn.close();
            }
            catch (Exception e) {
                    System.err.println("Got an exception! ");
                    System.err.println(e.getMessage());
            }
    }

}

PLEASE HELP :)
Thanks,


问:
Node js App stoping When Console is closed
Am new to node , created my first express based app and deployed in my development server.

```<code>node app.js
</code>```

given above command no errors and working properly , after logoff my putty application seems to be stopped ,how can i solve this issue .

Is there any other way for running node apps.

答:
You can install a PM2 module and start your application using PM2.

npm install pm2 -g

pm2 start app.js --name "Your App name"

To see your app

pm2 list

Body:
Am new to node , created my first express based app and deployed in my development server.

node app.js

given above command no errors and working properly , after logoff my putty application seems to be stopped ,how can i solve this issue .

Is there any other way for running node apps.


问:
Uncaught ReferenceError: require is not defined react rails
I just fixed two errors like this.

Uncaught ReferenceError: $ is not defined
Uncaught ReferenceError: React is not defined

Now I get this. I just keep getting these errors. I am just trying to implement react with rails for the first time and I am trying to say a simple "Hello React" from a react component through a html div class. I am not able to.

application.js

```<code>//= require rails-ujs
//= require_tree .
//= require jquery
//= require jquery_ujs
//= require react
</code>```

index.html.erb

```<code><div id="react"></div>
</code>```

main.jsx

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

import React from 'react';
import ReactDOM from 'react-dom';

let documentReady = () => {
    React.render(
        <h1>Hello React</h1>,
        document.getElementById('react')
    );
};

$(documentReady);
</code>```

答:
Move require_tree . at the end in application.js like:

```<code>//= require rails-ujs
//= require jquery
//= require jquery_ujs
//= require react
//= require_tree .
</code>```

Body:
I just fixed two errors like this.

Uncaught ReferenceError: $ is not defined
Uncaught ReferenceError: React is not defined

Now I get this. I just keep getting these errors. I am just trying to implement react with rails for the first time and I am trying to say a simple "Hello React" from a react component through a html div class. I am not able to.

application.js

//= require rails-ujs
//= require_tree .
//= require jquery
//= require jquery_ujs
//= require react

index.html.erb

main.jsx

import React from 'react';
import ReactDOM from 'react-dom';

let documentReady = () => {
    React.render(

Hello React
,
        document.getElementById('react')
    );
};

$(documentReady);

Body:
Move require_tree . at the end in application.js like:

//= require rails-ujs
//= require jquery
//= require jquery_ujs
//= require react
//= require_tree .


问:
How to set Content-Type for auto-delivered file in GlassFish?
When deploying a .war file to a GlassFish Server (4.1 currently), the GF server automatically delivers files from the WEB-INF/ folder. (Unless I override their addresses by specifying a Servlet, that is.)

Actually when deploying the .war file to the GF server, it extracts those files under WEB-INF/ to {gf-home}/glassfish/domains/domain1/applications/{app-name}.
Then it delivers them when accessing http://{hostname}:8080/{app-name}/{path}.

Now when accessing .json files, the server does NOT send the HTTP Content-Type: application/json header.
This results in the page not loading properly, FireFox console showing me a XML Parsing Error: not well-formed exception, even though the file contents are exactly the same.
So my guess is that it's the missing Content-Type tag.

How can I change this mime-mapping for the app/project itself?

From the pages I have seen so far, it is possible to redefine this behaviour in the {gf-home}/glassfish/domains/domain1/default-web.xml file, defining the mime-mapping. But presuming I cannot access that file, only upload .war files. Is there any solution? Is it possible to pack a default-web.xml somewhere into the .war file?

The other solution I can think of at the moment is to override the specific .json files' addresses with a servlet and adding the Content-Type header in Java. But I'm not sure if there is a foolproof way of accessing and reading the .json files at runtime, but without moving them anywhere in the Java source code, but leaving them in the WEB-INF/ folder? Any suggestions?

答:
How can I change this mime-mapping for the app/project itself?

By declaring the <mime-mapping> entries in webapp's own /WEB-INF/web.xml.

Since Servlet version 3.0, the web.xml file became optional. That'll perhaps explain why you could find no one. You can just supply your own in the webapp. GlassFish 4.1 is a Servlet 3.1 capable container, so the below Servlet 3.1 compatible web.xml should get you started:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

</web-app>
```

<p>In your specific case, you'll need the below mime mapping in there:</p>

<pre class="lang-xml prettyprint-override"><code>    <mime-mapping>
        <extension>json</extension>
        <mime-type>application/json</mime-type>
    </mime-mapping>
</code>```

See also:

What is conf/web.xml used for in Tomcat as oppsed to the one in WEB-INF?

How to set the content type on the servlet

How to find servlet API version for glassfish server?

Servlet 3.1 specification (PDF) chapter 10.13

Body:
How can I change this mime-mapping for the app/project itself?

By declaring the <mime-mapping> entries in webapp's own /WEB-INF/web.xml.

Since Servlet version 3.0, the web.xml file became optional. That'll perhaps explain why you could find no one. You can just supply your own in the webapp. GlassFish 4.1 is a Servlet 3.1 capable container, so the below Servlet 3.1 compatible web.xml should get you started:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <!-- Config here. -->
</web-app>

In your specific case, you'll need the below mime mapping in there:

    <mime-mapping>
        <extension>json</extension>
        <mime-type>application/json</mime-type>
    </mime-mapping>

See also:

What is conf/web.xml used for in Tomcat as oppsed to the one in WEB-INF?

How to set the content type on the servlet

How to find servlet API version for glassfish server?

Servlet 3.1 specification (PDF) chapter 10.13


问:
How to filter out 2 ids in c#?
I have below code which is filtering out menu id value 8

```<code>oListVM = oListVM.Where(x => x.MenuID != 8).ToList();  //filter out menu id 8
</code>```

But I wanted to filter out menu id 8 and 13 so I decided to write the code like this. Is this the right way to filter out both 8 and 13 menu id? I recently started working with c# and
.net.

```<code>oListVM = oListVM.Where(x => (x.MenuID != 8 && x.MenuID!=13)).ToList();  //filter out menu id 8 and 13
</code>```

答:
You could also do

```<code>oListVM = oListVM
    .Where(x => x.MenuID != 8)
    .Where(x => x.MenuID != 13)
    .ToList();  //filter out menu id 8 and 13
</code>```

Link is evaluated when it is "accessed" - by .ToList() you access and persist the whole iteration at once. It makes no difference for the Linq-Statement if you cram all conditions into one Where conditional or if you chain them.

If you decide to also block 14, 18, 22 you could also use another linq to check if any is (not) in a list of things:

```<code>var doNotShow = new [] {8, 13, 14, 18, 22};
oListVM = oListVM
    .Where(x => ! doNotShow.Any(d => x == d))
    .ToList();
</code>```

Title: How to filter out 2 ids in c#?

Body:
I have below code which is filtering out menu id value 8

oListVM = oListVM.Where(x => x.MenuID != 8).ToList();  //filter out menu id 8

But I wanted to filter out menu id 8 and 13 so I decided to write the code like this. Is this the right way to filter out both 8 and 13 menu id? I recently started working with c# and
.net.

oListVM = oListVM.Where(x => (x.MenuID != 8 && x.MenuID!=13)).ToList();  //filter out menu id 8 and 13

Body:
You could also do

oListVM = oListVM
    .Where(x => x.MenuID != 8)
    .Where(x => x.MenuID != 13)
    .ToList();  //filter out menu id 8 and 13

Link is evaluated when it is "accessed" - by .ToList() you access and persist the whole iteration at once. It makes no difference for the Linq-Statement if you cram all conditions into one Where conditional or if you chain them.

If you decide to also block 14, 18, 22 you could also use another linq to check if any is (not) in a list of things:

var doNotShow = new [] {8, 13, 14, 18, 22};
oListVM = oListVM
    .Where(x => ! doNotShow.Any(d => x == d))
    .ToList();


答:
```<code><?php
echo short_format_indian_c($tq); // There $tq not have any number only value thats why this not give a proper output.

?>

    <?php
    //This code run only server side.

    function short_format_indian_c($n) {
        $precision = 3;
        $n_format = number_format($n / 1000, $precision);
        $n_format = number_format($n_format, 2);
        $n_format = $n_format + 0;
        $n_format = $n_format . ' K';
        return $n_format;
    }
   // As per User need.

   function kFormatter($num) {
      // return ($num > 999) ?(round(($num/1000),2).'K':$num; //Not return K for less than 1000 ;
      return round(($num/1000),2).'K'; // work for all numbers

    }
    ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        //This part only run at client side.
        function kFormatter(num) {
          // return num > 999 ? (num/1000).toFixed(1) + 'K' : num; //Not return K for less than 1000 ;
          return (num/1000).toFixed(1) + 'K'; // work for all numbers

        }
        // Function for all format indian Currency.

       function short_format_indian_c(num) {

if(num < 1000)
      {
        return num; // For Less then 1000
      }
      else if(num >= 1000 && num < 99999)
      {
        return (num/1000).toFixed(1) + 'K'; // for 1000 multiplier till 99999
      }
      else if(num >= 100000 && num < 9999999)
      {
        return (num/100000).toFixed(1) + 'L'; // for 100000 multiplier till 9999999
      }
      else if(num >= 10000000 && num < 999999999)
      {
        return (num/10000000).toFixed(1) + 'C'; // for 10000000 multiplier till 999999999
      }
      else
      {
        return num; // For all other num instead
      }

    }
        var checkState = function(){
            var tq = jQuery('#tq');

            tq.html(short_format_indian_c(18000));
            // This will provide an output as 18K in element have id is tq;

        }
    checkState();
    setInterval(checkState, 1000);
    </script>
    <?php
    $tq = '<span id="tq"></span>'; // Wrong way to assign html value in a php variable.
    $tq  = '18000'; // this will work instead.

    ?>
    <?php
    echo short_format_indian_c($tq); // There $tq not have any number only value thats why this not give a proper output.

    ?>
</code>```

Note! if there you required a result at client side then you need to write this function for javascript also; Fiddle

Title: Self-defined function in PHP not working

Body:
<?php
echo short_format_indian_c($tq); // There $tq not have any number only value thats why this not give a proper output.

?>

    <?php
    //This code run only server side.

    function short_format_indian_c($n) {
        $precision = 3;
        $n_format = number_format($n / 1000, $precision);
        $n_format = number_format($n_format, 2);
        $n_format = $n_format + 0;
        $n_format = $n_format . ' K';
        return $n_format;
    }
   // As per User need.

   function kFormatter($num) {
      // return ($num > 999) ?(round(($num/1000),2).'K':$num; //Not return K for less than 1000 ;
      return round(($num/1000),2).'K'; // work for all numbers

    }
    ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        //This part only run at client side.
        function kFormatter(num) {
          // return num > 999 ? (num/1000).toFixed(1) + 'K' : num; //Not return K for less than 1000 ;
          return (num/1000).toFixed(1) + 'K'; // work for all numbers

        }
        // Function for all format indian Currency.

       function short_format_indian_c(num) {

if(num < 1000)
      {
        return num; // For Less then 1000
      }
      else if(num >= 1000 && num < 99999)
      {
        return (num/1000).toFixed(1) + 'K'; // for 1000 multiplier till 99999
      }
      else if(num >= 100000 && num < 9999999)
      {
        return (num/100000).toFixed(1) + 'L'; // for 100000 multiplier till 9999999
      }
      else if(num >= 10000000 && num < 999999999)
      {
        return (num/10000000).toFixed(1) + 'C'; // for 10000000 multiplier till 999999999
      }
      else
      {
        return num; // For all other num instead
      }

    }
        var checkState = function(){
            var tq = jQuery('#tq');

            tq.html(short_format_indian_c(18000));
            // This will provide an output as 18K in element have id is tq;

        }
    checkState();
    setInterval(checkState, 1000);
    </script>
    <?php
    $tq = '<span id="tq"></span>'; // Wrong way to assign html value in a php variable.
    $tq  = '18000'; // this will work instead.

    ?>
    <?php
    echo short_format_indian_c($tq); // There $tq not have any number only value thats why this not give a proper output.

    ?>

Note! if there you required a result at client side then you need to write this function for javascript also; Fiddle


问:
How can I use several media queries?
I have this code and I have tried to figure out why it's not working. I have read several answers to quite similar questions, but I just don't get any wiser. Is the code in let us say (max-width:480) applying to all the other larger media queries? The only thing I can see working is the (max-width:1000)

@media screen and (max-width: 1000px) {
  .figur {
    display: none;
  }
  #about {
    width: 100%;
  }
  #map {
    width: 100%;
  }
}
@media screen and (max-width: 720px) {
  .parallax {
    background-image: url("../img/bamseLiten.jpeg");
  }
  .row .column {
    width: 100%;
    height: 200px;
  }
}
@media all and (max-width: 480px) {
  #logo {
    display: block;
    width: 70%;
    align-self: center;
  }
  .menu li {
    display: block;
    width: 100%;
  }
}```

答:
For maximum device comparability and adopting you can use bootstrap 4+ like Media Query

```<code>// Small devices (landscape phones, 576px and up)
@media (max-width: 575px) {
}

// Medium devices (tablets, 768px and up)
@media (max-width: 767px) {

}

// Large devices (desktops, 992px and up)
@media (max-width: 991px) {

}

// Extra large devices (large desktops, 1200px and up)
 @media (max-width: 1199px) {

 }
</code>```

For ultra mobile first you can use min-width instead of max-width which is like this -

```<code>// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) {

}

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) {

}

// Large devices (desktops, 992px and up)
@media (min-width: 992px) {
}

// Extra large devices (large desktops, 1200px and up)
 @media (min-width: 1200px) {

 }
</code>```

Hope you will get a better responsive layout using one of this media query.. Thanks

Title: How can I use several media queries?

Body:
For maximum device comparability and adopting you can use bootstrap 4+ like Media Query

// Small devices (landscape phones, 576px and up)
@media (max-width: 575px) {
}

// Medium devices (tablets, 768px and up)
@media (max-width: 767px) {

}

// Large devices (desktops, 992px and up)
@media (max-width: 991px) {

}

// Extra large devices (large desktops, 1200px and up)
 @media (max-width: 1199px) {

 }

For ultra mobile first you can use min-width instead of max-width which is like this -

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) {

}

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) {

}

// Large devices (desktops, 992px and up)
@media (min-width: 992px) {
}

// Extra large devices (large desktops, 1200px and up)
 @media (min-width: 1200px) {

 }

Hope you will get a better responsive layout using one of this media query.. Thanks


问:
Retrofit 2.0 Multipart Request, send boolean type in form data including file
I am trying to upload a file using retrofit 2.0. Apart from file, I have few other params to be send with form data which include a boolean type also. My request declaration is -

```<code>@Multipart
    @POST("/upload/abc")
    Call<UploadResponse> uploadToServer(@Part("img_file\";filename=\"image") RequestBody file,
                                             @Part("access_token") RequestBody sessionKey,
                                             @Part("is_final") Boolean isFinal,
                                             @Part("sequence_id") Integer sequenceId,
                                             @Part("entity_id") RequestBody entityId,
                                             @Part("image_type") RequestBody imageType);
</code>```

I am using GsonConverterFactory. I tried 2 approaches -

(1) Instead of @Part("is_final") Boolean isFinal I used @Part("is_final") RequestBody isFinal and sending it with RequestBody.create(MediaType.parse("text/plain"), String.valueOf(true))

(2) Using @Part("is_final") Boolean isFinal and sending with Boolean.true.

In both the cases, "is_final" received on server side is Unicode or as a String instead of boolean value.

What is the best way to achieve this

答:
I made it work by -

Add compile 'com.squareup.retrofit2:converter-scalars:2.1.0' to the gradle file.

While creating retrofit instance, add

```<code>Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("url")
                .client(builder.build())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
</code>```

Now you can safely send primitive types with the request.

Example Request

```<code>Call<UploadResponse> uploadFile(@Part("img\"; filename=\"image") RequestBody file,
                                @Part("session_key") String sessionKey,
                                @Part("is_final") Boolean isFinal);
</code>```

Call this method using -

```<code>RequestBody fBody = RequestBody.create(null, someFile);
service.uploadFile(fBody, "some_string_session", true);
</code>```

Body:
I am trying to upload a file using retrofit 2.0. Apart from file, I have few other params to be send with form data which include a boolean type also. My request declaration is -

@Multipart
    @POST("/upload/abc")
    Call<UploadResponse> uploadToServer(@Part("img_file\";filename=\"image") RequestBody file,
                                             @Part("access_token") RequestBody sessionKey,
                                             @Part("is_final") Boolean isFinal,
                                             @Part("sequence_id") Integer sequenceId,
                                             @Part("entity_id") RequestBody entityId,
                                             @Part("image_type") RequestBody imageType);

I am using GsonConverterFactory. I tried 2 approaches -

(1) Instead of @Part("is_final") Boolean isFinal I used @Part("is_final") RequestBody isFinal and sending it with RequestBody.create(MediaType.parse("text/plain"), String.valueOf(true))

(2) Using @Part("is_final") Boolean isFinal and sending with Boolean.true.

In both the cases, "is_final" received on server side is Unicode or as a String instead of boolean value.

What is the best way to achieve this

Body:
I made it work by -

Add compile 'com.squareup.retrofit2:converter-scalars:2.1.0' to the gradle file.

While creating retrofit instance, add

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("url")
                .client(builder.build())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

Now you can safely send primitive types with the request.

Example Request

Call<UploadResponse> uploadFile(@Part("img\"; filename=\"image") RequestBody file,
                                @Part("session_key") String sessionKey,
                                @Part("is_final") Boolean isFinal);

Call this method using -

RequestBody fBody = RequestBody.create(null, someFile);
service.uploadFile(fBody, "some_string_session", true);


问:
How do I create a query that list the name of students who took fewer than three classes or have a null value for class
I have a "database" with two tables a student,and enroll. The student table has stuid, lastname, firstname. The enroll table has stuid classnumber and grade.

I have to return a list that looks like this

Last Name

Burns
Jones
Lee
McCarthy
Rivera
Smith

First Name

Edward
Mary
Perry
Owen
Jane
Tom

I attempted to do a statement like this

Select lastname, firstname
Where Not exists (Select stuid from enroll e where e.stuid = s.stuid)
Having count(*) < 3
Group By lastname, firstname;

I understand that I need two merge the two tables basically so that I get the results of people who have classes < 3 and people who are also not currently enrolled in a class.

答:
Your "where clause " needs to come after your "from clause". Then try this !</p>

```<code> select firstname , lastname
 from student s join enroll e
 on s.stuid = e.stuid
 Where e.classnumber < 3 and e.classnumber is null
</code>```

Body:
Your "where clause " needs to come after your "from clause". Then try this !

 select firstname , lastname
 from student s join enroll e
 on s.stuid = e.stuid
 Where e.classnumber < 3 and e.classnumber is null


问:
HTTPListener vs Native HTTP performance
Quick Background: I understand that HTTPListener uses http.sys kernel driver which supposedly makes it a great performer. However, when doing some performance benchmarks between a managed http server and a native vc++ server I am seeing approx 15 MB/s increase on the native side. Test setup is two lab machines freshly formatted with 1gb nics. On the native side I am seeing about 110 MB/s which is close to 100% of the nic minus overhead, when using HTTPListener I am seeing ~94 MB/s (max 100).

The tests are apples to apples,

both send the same payload (~120 mb)

I am using the same managed client app to test both servers

For Managed I have disabled Nagle (But tested both ways, result is the same)

I run a batch of tests and calculate the throughput, interesting note is that the Managed std deviation is higher, i.e. the results are not as consistent compared to the native.

Overall I expect that I should be able to get close to the 110 MB/s of the native server via HTTPListener, 15 MB/s seems pretty costly.

Questions:
1. Are there other optimizations for managed that I am missing?
2. What are some potential bottlenecks, I looked at the HTTPResponseStream via reflector, looks like there is some marshaling going on, but no glaring issues, In fact when using chunking it produces an identical chunk array as my native server.

Any ideas are appreciated,

答:
The fact that it uses Http.sys doesn't mean that there isn't a native-to-managed transition.  From the above-mentioned MSDN article:

HTTP.sys provides connection management, bandwidth throttling, and Web server logging.

By virtue of the fact that you are running managed code, you have interop (native to managed, not to be confused with COM interop), you have garbage collection, etc.  It's never going to be as fast as a pure native c++ implementation.

EDIT: To make this clearer, you are still running a .NET process, you are just hooking into IIS in kernel mode, not in user mode.  A great article on this is here: http://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.asp

Title: HTTPListener vs Native HTTP performance


问:
Serverless web socket server?
Are there any serverless technologies that allow a serverless websocket server to be built?

I know the nature of long running connections is that they are stateful, but if the only state is the connection itself at the transport layer then it seems like there could be a serverless product that abstracts this away so you only deal with the application layer. Is there a cloud provider (AWS, Azure, etc) that allows this? I can't see a way for AWS Lambda or Azure Functions to achieve this.

Anyone got any ideas? Just checking.

Thanks

答:
Fanout can do this. It works as a proxy that can translate WebSocket client activity into a series of HTTP requests. This allows FaaS backends like Lambda to manage raw WebSockets. The function is invoked only when there is activity to react to.

Docs: https://fanout.io/docs/devguide.html#custom-websocket-api

WebSocket-over-HTTP protocol: http://pushpin.org/docs/protocols/websocket-over-http/

Python helper library: https://github.com/fanout/python-faas-grip

Title: Serverless web socket server?


问:
Django IntegrityError null value in column "author_id" violates not-null constraint
I am trying to save a form where I take user inputs. I am getting Integrity error. Can anyone please help me out here? I see that people have used request.user.username but I don't see how to use this in my forms. Please don't mind the code as I am still trying to figure out things in Django.

Below are my files:

```<code>models.py

class CommonModel(models.Model):

    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=400)
    comments = models.TextField(blank=True)
    requirements = JSONField(default = {})
    specs = JSONField(default= {})
    created_date = models.DateTimeField(default=timezone.now)
    updated_date = models.DateTimeField(blank=True, null=True)

    class Meta:
       abstract = True

    def update(self):
        self.updated_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Item(CommonModel):

    HW = 'HW'
    NW = 'NW'
    SW = 'SW'
    VM = 'VM'
    WI = 'WI'
    SI = 'SI'
    ITEM_TYPES = (
        (HW, 'Hardware'),
        (NW, 'Network'),
        (SW, 'Software'),
        (VM, 'Virtual Machine'),
        (WI, 'Work Item'),
        (SI, 'Support Item'),
    )

    UNIT_LOE = 'LOE'
    UNIT_USD = 'USD'
    UNIT_TYPES = (
        (UNIT_LOE, 'LOE,MD'),
        (UNIT_USD, 'USD'),
    )

    item_type = models.CharField(default='HW', max_length=5, choices=ITEM_TYPES)
    unit_type = models.CharField(default='USD', max_length=5, choices=UNIT_TYPES)
    otc_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
    annual_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
    gp_code = models.TextField(default='Unknown')
    class Meta:
       abstract = True

class ItemTemplate(Item):
    pass
   # Need ID here to relate to estimate

class ItemObject(Item):
    pass
</code>```

Here is my admin.py

```<code>class CommonAdmin(admin.ModelAdmin):

    formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
    }

    def otc_price(self,obj):
        return json_prettified(obj.otc_price)
    def annual_price(self,obj):
        return json_prettified(obj.annual_price)

from reversion.admin import VersionAdmin

@admin.register(ItemTemplate)
class ItemTemplateAdmin(VersionAdmin):
     list_display = ('title', 'item_type', 'unit_type', 'otc_price','annual_price')
     formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
     }

@admin.register(ItemObject)
class ItemObjectAdmin(VersionAdmin):
     list_display = ('title', 'item_type', 'unit_type', 'otc_price','annual_price')
     formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
     }
</code>```

And finally the views.py.

```<code>def order_create(request):
        cart = ItemObject.objects.all()

        if request.method == 'POST':
            form = ItemObjectCreateForm(request.POST)
            if form.is_valid():
                form.save()
                for item in cart:
                    annual_price = 122
                    otc_price=100
                    # Logic to calculate the price and put it in estimate table
                    ItemObject.objects.create(
                                             requirements=item.requirements,
                                             specs=item.specs,
                                             annual_price = annual_price,

                    )
                # clear the cart
                #cart.clear()
                order_created()
                # redirect to the payment
                return redirect('success.html')

        else:
            form = ItemObjectCreateForm()
        return render(request,
                      'index.html',
                      {'cart': cart, 'form': form})
</code>```

Here I am trying to store data to ItemObject but while submitting the form, I am getting error.

```<code>IntegrityError: null value in column "author_id" violates not-null constraint
DETAIL:  Failing row contains
</code>```

Also my forms.py is like below

```<code>class ItemObjectCreateForm(forms.ModelForm):
    class Meta:
        model = ItemObject
        fields = ['title','requirements', 'gp_code', 'specs','author', 'item_type', 'unit_type','comments', 'id'
                  ]
</code>```

Attaching DB

答:
While form save, set commit argument to false to prevent the object being saved immediately, </p>

```<code>item = form.save(commit=False)
item.author = request.user
item.save()
</code>```

<p>And modify </p>

```<code>ItemObject.objects.create( author=request.user, requirements=item.requirements, specs=item.specs, annual_price = annual_price, )
</code>```

Body:
I am trying to save a form where I take user inputs. I am getting Integrity error. Can anyone please help me out here? I see that people have used request.user.username but I don't see how to use this in my forms. Please don't mind the code as I am still trying to figure out things in Django.

Below are my files:

models.py

class CommonModel(models.Model):

    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=400)
    comments = models.TextField(blank=True)
    requirements = JSONField(default = {})
    specs = JSONField(default= {})
    created_date = models.DateTimeField(default=timezone.now)
    updated_date = models.DateTimeField(blank=True, null=True)

    class Meta:
       abstract = True

    def update(self):
        self.updated_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Item(CommonModel):

    HW = 'HW'
    NW = 'NW'
    SW = 'SW'
    VM = 'VM'
    WI = 'WI'
    SI = 'SI'
    ITEM_TYPES = (
        (HW, 'Hardware'),
        (NW, 'Network'),
        (SW, 'Software'),
        (VM, 'Virtual Machine'),
        (WI, 'Work Item'),
        (SI, 'Support Item'),
    )

    UNIT_LOE = 'LOE'
    UNIT_USD = 'USD'
    UNIT_TYPES = (
        (UNIT_LOE, 'LOE,MD'),
        (UNIT_USD, 'USD'),
    )

    item_type = models.CharField(default='HW', max_length=5, choices=ITEM_TYPES)
    unit_type = models.CharField(default='USD', max_length=5, choices=UNIT_TYPES)
    otc_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
    annual_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
    gp_code = models.TextField(default='Unknown')
    class Meta:
       abstract = True

class ItemTemplate(Item):
    pass
   # Need ID here to relate to estimate

class ItemObject(Item):
    pass

Here is my admin.py

class CommonAdmin(admin.ModelAdmin):

    formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
    }

    def otc_price(self,obj):
        return json_prettified(obj.otc_price)
    def annual_price(self,obj):
        return json_prettified(obj.annual_price)

from reversion.admin import VersionAdmin

@admin.register(ItemTemplate)
class ItemTemplateAdmin(VersionAdmin):
     list_display = ('title', 'item_type', 'unit_type', 'otc_price','annual_price')
     formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
     }

@admin.register(ItemObject)
class ItemObjectAdmin(VersionAdmin):
     list_display = ('title', 'item_type', 'unit_type', 'otc_price','annual_price')
     formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
     }

And finally the views.py.

def order_create(request):
        cart = ItemObject.objects.all()

        if request.method == 'POST':
            form = ItemObjectCreateForm(request.POST)
            if form.is_valid():
                form.save()
                for item in cart:
                    annual_price = 122
                    otc_price=100
                    # Logic to calculate the price and put it in estimate table
                    ItemObject.objects.create(
                                             requirements=item.requirements,
                                             specs=item.specs,
                                             annual_price = annual_price,

                    )
                # clear the cart
                #cart.clear()
                order_created()
                # redirect to the payment
                return redirect('success.html')

        else:
            form = ItemObjectCreateForm()
        return render(request,
                      'index.html',
                      {'cart': cart, 'form': form})

Here I am trying to store data to ItemObject but while submitting the form, I am getting error.

IntegrityError: null value in column "author_id" violates not-null constraint
DETAIL:  Failing row contains

Also my forms.py is like below

class ItemObjectCreateForm(forms.ModelForm):
    class Meta:
        model = ItemObject
        fields = ['title','requirements', 'gp_code', 'specs','author', 'item_type', 'unit_type','comments', 'id'
                  ]

Attaching DB

Body:
While form save, set commit argument to false to prevent the object being saved immediately,

item = form.save(commit=False)
item.author = request.user
item.save()

And modify

ItemObject.objects.create( author=request.user, requirements=item.requirements, specs=item.specs, annual_price = annual_price, )


问:
Is it possible to verify a saved SSL session against public key of server
Here is what I am trying to do:

I am working on an app where people will be able to track prices of products.

I want their phones be able to crawl some of the sites where this product appears (with their consent), twice a day.

I don't want to redundantly do this, if two users are watching the product, I want to only use one of them to do the crawling.

Once crawling a product is complete, the crawling result will be pushed to server (to prevent redundant crawling).

In the last step, the data is pushed from an "untrusted" source. Someone can reverse engineer the network traffic and potentially push garbage to the end point. I want the crawled "HTML" be authentic, and coming from the merchant site it is intended to.

Here is the question:
- I was thinking it may be achieved by storing encrypted SSL traffic for a particular request, and on the server side, I could validate the it against the public key of the merchant certificate (let's say, newegg).

However, I am not entirely sure if this is going to work, and i am stuck with coding it. Code snippets for would be appreciated (as long as it's not straight out of openssl commands :))

答:
It should in theory be possible to verify a captured TLS handshake against the servers certificate (i.e. public key inside the certificate) in order to be sure that this handshake was created with the server. But, this alone is no proof that the decrypted data and the TLS handshake belong to the same TLS session. For this you would also need the (pre-)master secret of the connection.

Note that modifying the bot that it will extract the (pre-)master secret from the internal SSL state and the encrypted traffic, store this secret and the encrypted traffic together with the plain traffic and write some code to verify that all this belongs together is not a trivial task. Depending on the SSL library used it might be necessary to dig deep into the internals and use undocumented (non-API) functions to do this or grab the information directly from some internal structures.

Code snippets for would be appreciated (as long as it's not straight out of openssl commands :))

Latest version of OpenSSL have a SSL_SESSION_get_master_key function. But I'm not aware of any API in OpenSSL which can be used to verify and decrypt a sniffed session. You might have a look at the source code of Wireshark for this.

If you can trust the bot itself then it will be much simpler to just let the bot sign the decrypted traffic so that you can detect bogus data.


问:
conversion of decimal formatted date into date in sql
I want to convert the decimal format date into normal date format in sql.
Below is the example -
I am having the date in decimal format like  '1512137620000' , I want to convert it into normal standard format MM/DD/YYYY.
Many thanks for your help.</p>

答:
Depending on what your base date is, and what your decimal number represents (milliseconds, seconds), you can do it like this:

```<code>SELECT DATEADD(MILLISECOND, 1512137620000, '19000101')
</code>```

With your given decimal number, this statement will produce an arithmetic overflow (the second parameter for DATEADD is an integer); I would divide the decimal number by 1.000 and try

```<code>SELECT DATEADD(SECOND, 1512137620, '19000101')
</code>```

This results in 1947-12-02 14:13:40.000  so I suspect your base date is maybe 19700101, then the result would be 2017-12-01 14:13:40.000.

Then for converting into MM/DD/YYYY:

```<code>SELECT CONVERT(varchar(10), DATEADD(SECOND, 1512137620, '19700101'), 103)
</code>```

Body:
Depending on what your base date is, and what your decimal number represents (milliseconds, seconds), you can do it like this:

SELECT DATEADD(MILLISECOND, 1512137620000, '19000101')

With your given decimal number, this statement will produce an arithmetic overflow (the second parameter for DATEADD is an integer); I would divide the decimal number by 1.000 and try

SELECT DATEADD(SECOND, 1512137620, '19000101')

This results in 1947-12-02 14:13:40.000  so I suspect your base date is maybe 19700101, then the result would be 2017-12-01 14:13:40.000.

Then for converting into MM/DD/YYYY:

SELECT CONVERT(varchar(10), DATEADD(SECOND, 1512137620, '19700101'), 103)


问:
Does google one tap sign up works when user is not logged into his google account?
Below code works fine but when opened from an incognito windows console only shows

```<code>GoogleYolo loaded.
No credentials
</code>```

<title>My Yolo Login example</title>

```

How can I know that user doesn't have a google account and redirect/take other action for him to login to his google account.

答:
I'm the product manager at Google for this library. We are working on some better support for users who are not signed in, but in the interim, when no Google Accounts are active and no credentials are available, you can simply show the traditional Google Sign-In button and have the user click to proceed through the flow to activate their Google Account in the browser.

https://developers.google.com/identity/sign-in/web/

Body:
Below code works fine but when opened from an incognito windows console only shows

GoogleYolo loaded.
No credentials

<title>My Yolo Login example</title>

How can I know that user doesn't have a google account and redirect/take other action for him to login to his google account.


问:
Linq join list and table
I have a List<string> of ProductTypes such as Vegetables, Dairy, Meat
 which I receive from a query string in Asp.Net Core.

In the database, there is a Product table which contains a ProductType column that has each product's type in a text field)

I want to select from the Product database table all the Products that are in the ProductTypes list as received.  I did this:

```<code>var Result =  (from p in _context.Product
             join t in ProductTypes on p.ProductType equals t  select p).ToList();
</code>```

My effort above has an (incorrect) empty result except if only one ProductType is passed, in which case it works correctly.

How can I accomplish a correct Result set if multiple  ProductTypes are passed?

答:
You can use Contains instead of a join:

```<code>var result =
    from p in _context.Product
    where ProductTypes.Contains(p.ProductType)
    select p;
</code>```

You rarely need joins in LINQ and in your special case where you have an in memory list and a database table, Contains is the way to go.

Title: Linq join list and table

Body:
I have a List<string> of ProductTypes such as Vegetables, Dairy, Meat
 which I receive from a query string in Asp.Net Core.

In the database, there is a Product table which contains a ProductType column that has each product's type in a text field)

I want to select from the Product database table all the Products that are in the ProductTypes list as received.  I did this:

var Result =  (from p in _context.Product
             join t in ProductTypes on p.ProductType equals t  select p).ToList();

My effort above has an (incorrect) empty result except if only one ProductType is passed, in which case it works correctly.

How can I accomplish a correct Result set if multiple  ProductTypes are passed?

Body:
You can use Contains instead of a join:

var result =
    from p in _context.Product
    where ProductTypes.Contains(p.ProductType)
    select p;

You rarely need joins in LINQ and in your special case where you have an in memory list and a database table, Contains is the way to go.


问:
Count no of records as per the date from table and format the date using PHP and MySQL
I need to etch no of records as per the date filed and after fetching the data I need to format the date using PHP and MySQL. I am explaining my table below.

db_audit:

```<code>id        auditname         date
 1          xxxx            2017-12-01 12:26:49
 2          sss             2017-12-01 12:20:00
 3         fff              2017-12-01 12:00:00
 4        hhh              2017-12-02 12:27:49
 5        ttt              2017-12-02 11:26:49
 6       yyy               2017-12-03 10:26:49
</code>```

Here I need to fetch no of records as per the date only. Here for 2017-12-01 there are 3 records present. I need to push all data into an array like this key format {'no_records'=>3,'date'=>2017-12-01}. Here also I need to formatted the database date field value from 2017-12-03 10:26:49 to 2017-12-03 and it should be in string format. Here I need the query to retrieve these type of value.

答:
First part of the code to select the data according to the queries

```<code><?php
$servername="localhost";
$username="root";
$password="";
$db="";//database name
//connection
$conn=new mysqli($servername,$username,$password,$db);

//query to select data matching the  data
$sql = "SELECT * FROM db_audit where date='2017-12-01' ";
$result = $conn->query($sql);
 $row = mysqli_fetch_array($query)
$count=mysqli_num_rows($result);

 $date=substr($row['date'],0,10);
    $values=array("no of records=> $count","date=>$date");
?>
</code>```

The end part formats the data to the desired output

Body:
I need to etch no of records as per the date filed and after fetching the data I need to format the date using PHP and MySQL. I am explaining my table below.

db_audit:

id        auditname         date
 1          xxxx            2017-12-01 12:26:49
 2          sss             2017-12-01 12:20:00
 3         fff              2017-12-01 12:00:00
 4        hhh              2017-12-02 12:27:49
 5        ttt              2017-12-02 11:26:49
 6       yyy               2017-12-03 10:26:49

Here I need to fetch no of records as per the date only. Here for 2017-12-01 there are 3 records present. I need to push all data into an array like this key format {'no_records'=>3,'date'=>2017-12-01}. Here also I need to formatted the database date field value from 2017-12-03 10:26:49 to 2017-12-03 and it should be in string format. Here I need the query to retrieve these type of value.

Body:
First part of the code to select the data according to the queries

<?php
$servername="localhost";
$username="root";
$password="";
$db="";//database name
//connection
$conn=new mysqli($servername,$username,$password,$db);

//query to select data matching the  data
$sql = "SELECT * FROM db_audit where date='2017-12-01' ";
$result = $conn->query($sql);
 $row = mysqli_fetch_array($query)
$count=mysqli_num_rows($result);

 $date=substr($row['date'],0,10);
    $values=array("no of records=> $count","date=>$date");
?>

The end part formats the data to the desired output


问:
Where is logical error in the given code?
I am trying to add a new node to the linked list. Online tutorials(http://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/) uses a pointer to a pointer and I am not able to understand how it works. So I decided to write my own code but I am having a problem with the push() function. Here is the code.

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

struct node{
    int data;
    struct node* next;
};

void print_list(struct node *head_ptr)
{
    while(head_ptr!=NULL)
    {
        printf("%d->",head_ptr->data);
        head_ptr = head_ptr->next;
    }
}

void push(struct node *head_ptr, int data_val)
{
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node -> data = data_val;

    new_node->next = head_ptr;
    head_ptr = new_node;
}

int main()
{
    struct node *head = (struct node*)malloc(sizeof(struct node));
    struct node *second = (struct node*)malloc(sizeof(struct node));
    struct node *third = (struct node*)malloc(sizeof(struct node));

    head -> data = 1;
    head -> next = second;
    second -> data = 2;
    second -> next = third;
    third -> data = 3;
    third -> next = NULL;

    print_list(head);
    push(head,0);
    printf("\n");
    print_list(head);

    return 0;
}
</code>```

It compiles without error. However, the expected node with value 0 does not get inserted in the beginning of my linked list.

Current Output
1->2->3->
Expected Output
0->1->2->3->

Please help me get the required output without using pointer to a pointer in push() function. Also, share a link to a source which has a good explanation of pointer to a pointer and it relates to the linked list.

答:
You are doing it wrong way.

The thing is when you pass head in push a copy of it is passed to push. The content of them are same. Now what you are doing?

Creating new node. Then you make changes to that copy of the variable. Then the function ends and the lifetime of that variable ends and so is the access to the allocated memory (creating memory leak). And the original head in main() still is same. That's why it prints 1-2-3.

Solution-1

head = push(head,0);

And

```<code>struct node* push(struct node *head_ptr, int data_val)
{
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node -> data = data_val;

    new_node->next = head_ptr;
    head_ptr = new_node;
    return head_ptr;
}
</code>```

Solution-2

```<code>void push(struct node **head_ptr, int data_val)
{
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node -> data = data_val;

    new_node->next = *head_ptr;
    *head_ptr = new_node;

}
</code>```

And call it like

```<code>push(&head,0);
</code>```

Explanation of solution-2

Now here you pass &head to the function meaning you pass the address of it to the function push(). Now in push() you have a variable named head which is a contains the address of the head. Now by dereferencing it you are basically the head of main()and any changes you make to *head will retain because you are changing to the actual variable, whose address was passed.

Explanation of solution-1

Here we don't pass the address. But rather we pass the content of the head variable of main(). Now you allocate memory and you get it's address. You make changes to it. And then you put in the next the address of the head and then you point head to the newnode. And you may ask so it changes the origibal head? Nope. that's why we return it and we store it in the originbal head in main().

Note:

The dynamically allocated memory is have lifetime beyond the scope of the function. That's why you can return it's address and there will not be any problem.

You don't need to cast the return type of malloc. That's not needed.

struct node *new_node = malloc(sizeof(struct node));

Or

more clearly

```<code>struct node *new_node = malloc(sizeof *new_node));
</code>```

Also check the return value of malloc.

Free the dynamically allocated memory when you are done working with it.

Body:
I am trying to add a new node to the linked list. Online tutorials(http://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/) uses a pointer to a pointer and I am not able to understand how it works. So I decided to write my own code but I am having a problem with the push() function. Here is the code.

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

struct node{
    int data;
    struct node* next;
};

void print_list(struct node *head_ptr)
{
    while(head_ptr!=NULL)
    {
        printf("%d->",head_ptr->data);
        head_ptr = head_ptr->next;
    }
}

void push(struct node *head_ptr, int data_val)
{
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node -> data = data_val;

    new_node->next = head_ptr;
    head_ptr = new_node;
}

int main()
{
    struct node *head = (struct node*)malloc(sizeof(struct node));
    struct node *second = (struct node*)malloc(sizeof(struct node));
    struct node *third = (struct node*)malloc(sizeof(struct node));

    head -> data = 1;
    head -> next = second;
    second -> data = 2;
    second -> next = third;
    third -> data = 3;
    third -> next = NULL;

    print_list(head);
    push(head,0);
    printf("\n");
    print_list(head);

    return 0;
}

It compiles without error. However, the expected node with value 0 does not get inserted in the beginning of my linked list.

Current Output
1->2->3->
Expected Output
0->1->2->3->

Please help me get the required output without using pointer to a pointer in push() function. Also, share a link to a source which has a good explanation of pointer to a pointer and it relates to the linked list.

Body:
You are doing it wrong way.

The thing is when you pass head in push a copy of it is passed to push. The content of them are same. Now what you are doing?

Creating new node. Then you make changes to that copy of the variable. Then the function ends and the lifetime of that variable ends and so is the access to the allocated memory (creating memory leak). And the original head in main() still is same. That's why it prints 1-2-3.

Solution-1

head = push(head,0);

And

struct node* push(struct node *head_ptr, int data_val)
{
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node -> data = data_val;

    new_node->next = head_ptr;
    head_ptr = new_node;
    return head_ptr;
}

Solution-2

void push(struct node **head_ptr, int data_val)
{
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node -> data = data_val;

    new_node->next = *head_ptr;
    *head_ptr = new_node;

}

And call it like

push(&head,0);

Explanation of solution-2

Now here you pass &head to the function meaning you pass the address of it to the function push(). Now in push() you have a variable named head which is a contains the address of the head. Now by dereferencing it you are basically the head of main()and any changes you make to *head will retain because you are changing to the actual variable, whose address was passed.

Explanation of solution-1

Here we don't pass the address. But rather we pass the content of the head variable of main(). Now you allocate memory and you get it's address. You make changes to it. And then you put in the next the address of the head and then you point head to the newnode. And you may ask so it changes the origibal head? Nope. that's why we return it and we store it in the originbal head in main().

Note:

The dynamically allocated memory is have lifetime beyond the scope of the function. That's why you can return it's address and there will not be any problem.

You don't need to cast the return type of malloc. That's not needed.

struct node *new_node = malloc(sizeof(struct node));

Or

more clearly

struct node *new_node = malloc(sizeof *new_node));

Also check the return value of malloc.

Free the dynamically allocated memory when you are done working with it.


问:
php parse_str convert plus(+) to spaces
I'm using parse_str to get an array from a string, which is like:

```<code>$str='a=123&b=456&Signature=aaaa/bbb+i8=&Satus=bbbb';
</code>```

I noticed that the function parse_str does convert plus to space, but how can I avoid this things.

new edit:

The $str to a value that I get from a string which is like this:

```<code>YT0xMjMmYj00NTYmU2lnbmF0dXJlPWFhYWEvYmJiK2k4PSZTYXR1cz1iYmJi
</code>```

I get the string and make base64_decode,then get the $str.

答:
```<code><?php
$str='a=123&b=456&Signature=aaaa/bbb+i8=&Satus=bbbb';
$new_string = str_replace('+', '.', $str);
parse_str($new_string,$old_string);
$signature = str_replace('.', '+', $old_string['Signature']);
?>
</code>```

Title: php parse_str convert plus(+) to spaces

Body:
I'm using parse_str to get an array from a string, which is like:

$str='a=123&b=456&Signature=aaaa/bbb+i8=&Satus=bbbb';

I noticed that the function parse_str does convert plus to space, but how can I avoid this things.

new edit:

The $str to a value that I get from a string which is like this:

YT0xMjMmYj00NTYmU2lnbmF0dXJlPWFhYWEvYmJiK2k4PSZTYXR1cz1iYmJi

I get the string and make base64_decode,then get the $str.


问:
SQL: Missing right parenthesis and table or view does not exist errors
I am trying to create 5 tables, however the first 3 drop and create fine with no issues but the last 2 band and fan do not seem to have much luck.

```<code>DROP TABLE festival cascade constraints;
CREATE TABLE festival (
 Festival_ID    VARCHAR2(4) PRIMARY KEY,
 Festival_Organizer     varchar2(30),
 Festival_Location  varchar2(20));

DROP TABLE venue cascade constraints;
CREATE TABLE venue(
 Venue_ID   VARCHAR2(3) PRIMARY KEY,
 Venue_Name     VARCHAR2(25),
 Venue_Location VARCHAR2(15),
 Venue_Contact_Person VARCHAR2(30),
 Venue_Contact_Number NUMERIC(9,2),
 Venue_Type VARCHAR2(15),
 Venue_Size VARCHAR2(6),
 Venue_HirePrice FLOAT(8));

DROP TABLE staff cascade constraints;
CREATE TABLE staff(
 Staff_ID   VARCHAR2(3) PRIMARY KEY,
 Staff_Firstname    VARCHAR2(20),
 Staff_Surname  VARCHAR2(25),
 Staff_Specialism   VARCHAR2(20),
 Staff_Salary   NUMERIC(8,2),
 Staff_Contact_Number   NUMERIC(9,2),
 Staff_Address  VARCHAR2(50),
 Venue_ID   VARCHAR2(5) REFERENCES venue(Venue_ID));

DROP TABLE band cascade constraints;
CREATE TABLE band(
 Band_ID    VARCHAR2(3) PRIMARY KEY,
 Band_Name  VARCHAR2(25),
 Band_ContactNo NUMERIC(8,2),
 Band_PlayDate  DATE NOT NULL,
 Band_PlayTime  TIME (8) NOT NULL,
 Band_Storage_Location  VARCHAR2(30),
 Band_Agent VARCHAR2(25),
 Band_AE    VARCHAR2 (3),
 Venue_ID   VARCHAR2(5) REFERENCES venue(Venue_ID));

DROP TABLE fan cascade constraints;
CREATE TABLE fan(
 Fan_ID VARCHAR(6) PRIMARY KEY,
 Fan_Firstname  VARCHAR2(15),
 Fan_Surname    VARCHAR2(30),
 Fan_Contact_Number NUMERIC(9,2),
 Fan_Address    VARCHAR2(50),
 Fan_DOB    DATE NOT NULL,
 Band_ID    VARCHAR2(5) REFERENCES band(Band_ID));
</code>```

When I run the code I get the following errors:

DROP TABLE band cascade constraints    ORA-00942: table or view does not exist

CREATE TABLE band( Band_ID VARCHAR2(3) PRIMARY KEY, Band_Nam   ORA-00907: missing right parenthesis

DROP TABLE fan cascade constraints ORA-00942: table or view does not exist

CREATE TABLE fan( Fan_ID   VARCHAR(6) PRIMARY KEY, Fan_Firstna ORA-00942: table or view does not exist

答:
Reason is you are trying to drop a table that doesn't exist.

Either comment out the drop table statements or if you want an automated version, Enclose all the drop statements in an Anonymous block and handle only the specific ORA-Error (ORA-00942).

Instead of

```<code>DROP TABLE band cascade constraints;
CREATE TABLE band..
</code>```

Use :

```<code>BEGIN
   EXECUTE IMMEDIATE 'DROP TABLE band cascade constraints';
EXCEPTION
   WHEN OTHERS THEN
      IF SQLCODE <> -942 THEN
         RAISE;
      END IF;
END;
CREATE TABLE band..
</code>```

Body:
I am trying to create 5 tables, however the first 3 drop and create fine with no issues but the last 2 band and fan do not seem to have much luck.

DROP TABLE festival cascade constraints;
CREATE TABLE festival (
 Festival_ID    VARCHAR2(4) PRIMARY KEY,
 Festival_Organizer     varchar2(30),
 Festival_Location  varchar2(20));

DROP TABLE venue cascade constraints;
CREATE TABLE venue(
 Venue_ID   VARCHAR2(3) PRIMARY KEY,
 Venue_Name     VARCHAR2(25),
 Venue_Location VARCHAR2(15),
 Venue_Contact_Person VARCHAR2(30),
 Venue_Contact_Number NUMERIC(9,2),
 Venue_Type VARCHAR2(15),
 Venue_Size VARCHAR2(6),
 Venue_HirePrice FLOAT(8));

DROP TABLE staff cascade constraints;
CREATE TABLE staff(
 Staff_ID   VARCHAR2(3) PRIMARY KEY,
 Staff_Firstname    VARCHAR2(20),
 Staff_Surname  VARCHAR2(25),
 Staff_Specialism   VARCHAR2(20),
 Staff_Salary   NUMERIC(8,2),
 Staff_Contact_Number   NUMERIC(9,2),
 Staff_Address  VARCHAR2(50),
 Venue_ID   VARCHAR2(5) REFERENCES venue(Venue_ID));

DROP TABLE band cascade constraints;
CREATE TABLE band(
 Band_ID    VARCHAR2(3) PRIMARY KEY,
 Band_Name  VARCHAR2(25),
 Band_ContactNo NUMERIC(8,2),
 Band_PlayDate  DATE NOT NULL,
 Band_PlayTime  TIME (8) NOT NULL,
 Band_Storage_Location  VARCHAR2(30),
 Band_Agent VARCHAR2(25),
 Band_AE    VARCHAR2 (3),
 Venue_ID   VARCHAR2(5) REFERENCES venue(Venue_ID));

DROP TABLE fan cascade constraints;
CREATE TABLE fan(
 Fan_ID VARCHAR(6) PRIMARY KEY,
 Fan_Firstname  VARCHAR2(15),
 Fan_Surname    VARCHAR2(30),
 Fan_Contact_Number NUMERIC(9,2),
 Fan_Address    VARCHAR2(50),
 Fan_DOB    DATE NOT NULL,
 Band_ID    VARCHAR2(5) REFERENCES band(Band_ID));

When I run the code I get the following errors:

DROP TABLE band cascade constraints    ORA-00942: table or view does not exist

CREATE TABLE band( Band_ID VARCHAR2(3) PRIMARY KEY, Band_Nam   ORA-00907: missing right parenthesis

DROP TABLE fan cascade constraints ORA-00942: table or view does not exist

CREATE TABLE fan( Fan_ID   VARCHAR(6) PRIMARY KEY, Fan_Firstna ORA-00942: table or view does not exist

Body:
Reason is you are trying to drop a table that doesn't exist.

Either comment out the drop table statements or if you want an automated version, Enclose all the drop statements in an Anonymous block and handle only the specific ORA-Error (ORA-00942).

Instead of

DROP TABLE band cascade constraints;
CREATE TABLE band..

Use :

BEGIN
   EXECUTE IMMEDIATE 'DROP TABLE band cascade constraints';
EXCEPTION
   WHEN OTHERS THEN
      IF SQLCODE <> -942 THEN
         RAISE;
      END IF;
END;
CREATE TABLE band..