问:
Android 5.0 android:elevation Works for View, but not Button?
In the Android 5.0 samples from the SDK Manager, there is the ElevationBasic sample. It shows two View objects: a circle and a square. The circle has android:elevation set to 30dp:

```<code><?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright 2014 The Android Open Source Project

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent">
    <View
            android:id="@+id/floating_shape"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_marginRight="40dp"
            android:background="@drawable/shape"
            android:elevation="30dp"
            android:layout_gravity="center"/>
    <View
            android:id="@+id/floating_shape_2"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_marginLeft="25dp"
            android:background="@drawable/shape2"
            android:layout_gravity="center"/>
</FrameLayout>
</code>```

On a Nexus 9, running the sample as-is, we get a drop shadow on the circle:

If we change the widget class to Button, leaving all other attributes as-is, we lose the drop shadow on the circle:

The questions:

Why is the android:elevation behavior changing? It cannot be due to the background, because it is the same background in both cases.

Which classes support android:elevation, and which do not? For example, using TextView instead of View or Button still gives us the drop shadow, so this change in behavior is not introduced at the TextView level, but rather at the Button level.

As seen in this question from yesterday, how do we get android:elevation to be honored on a Button? Is there some android:allowElevationToWorkAsDocumented="true" value that we have to put in a theme or something?

答:
This solution works for all the API versions of Android

Create a shadow @android:drawable/dialog_holo_light_frame & if you want to customize the color of the background instead of white then create a layer-list background with customizable color on top of the shadow as shown below

Create a separate drawable file white_background_shadow.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!--the shadow comes from here-->
    <item
        android:bottom="0dp"
        android:drawable="@android:drawable/dialog_holo_light_frame"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp">

    </item>

    <item
        android:bottom="0dp"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp">
        <!--whatever you want in the background, here i preferred solid white -->
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />

        </shape>
    </item>
</layer-list>
</code>```

and use this drawable as the background like this

```<code>android:background="@drawable/shadow"
</code>```

Body:
In the Android 5.0 samples from the SDK Manager, there is the ElevationBasic sample. It shows two View objects: a circle and a square. The circle has android:elevation set to 30dp:

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent">
    <View
            android:id="@+id/floating_shape"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_marginRight="40dp"
            android:background="@drawable/shape"
            android:elevation="30dp"
            android:layout_gravity="center"/>
    <View
            android:id="@+id/floating_shape_2"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_marginLeft="25dp"
            android:background="@drawable/shape2"
            android:layout_gravity="center"/>
</FrameLayout>

On a Nexus 9, running the sample as-is, we get a drop shadow on the circle:

If we change the widget class to Button, leaving all other attributes as-is, we lose the drop shadow on the circle:

The questions:

Why is the android:elevation behavior changing? It cannot be due to the background, because it is the same background in both cases.

Which classes support android:elevation, and which do not? For example, using TextView instead of View or Button still gives us the drop shadow, so this change in behavior is not introduced at the TextView level, but rather at the Button level.

As seen in this question from yesterday, how do we get android:elevation to be honored on a Button? Is there some android:allowElevationToWorkAsDocumented="true" value that we have to put in a theme or something?

Body:
This solution works for all the API versions of Android

Create a shadow @android:drawable/dialog_holo_light_frame & if you want to customize the color of the background instead of white then create a layer-list background with customizable color on top of the shadow as shown below

Create a separate drawable file white_background_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!--the shadow comes from here-->
    <item
        android:bottom="0dp"
        android:drawable="@android:drawable/dialog_holo_light_frame"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp">

    </item>

    <item
        android:bottom="0dp"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp">
        <!--whatever you want in the background, here i preferred solid white -->
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />

        </shape>
    </item>
</layer-list>

and use this drawable as the background like this

android:background="@drawable/shadow"


来源: stackexchange

问:
how create 2d array in javascript with row and cel [[2,4,6], [4,16,32],[8,64,128]];?
How do I create a 2d array in JavaScript with row and cel?

Example output [[2,4,6], [4,16,32],[8,64,128]];

var matrix = [],
    row = [],

for(var i = 0; i < 3; i++) {
  row = [];
  for(var j = 2; j <= 6; j++) {
    row.push(j++);

  }
  matrix.push(row);

}
console.log('matrix', matrix[0],matrix[1],matrix[2]);

for(var i = 0; i < 3; i++) {
  for(var j = 0; j < 3; j++) {
 console.log(matrix[i][j]);
  }
}```

答:
please use var matrix = [], row = []; instead of var matrix = [],
    row = [],</p>

ContentLicense: CC BY-SA 3.0


问:
errors: Cannot convert value of type 'Section' to expected argument type 'String' and cannot assign value of type '[string]' to 'string?'
the first code is responsible for my first view controller attached in the linked picture, it runs just fine until I add the commented bit which enables user to be push to the next view whereby study units should be displayed according to the selected yearOfStudy e.g by tapping on FEEYear3 as in the pic, units of that study year under the respective course are displayed. When I uncomment, I get an error saying:" Cannot convert value of type 'Section' to expected argument type 'String' ". I should add that 'Section' under var sections is set as a struct.

```<code>import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, ExpandableHeaderViewDelegate{

    @IBOutlet var tableView: UITableView!

    var sections=[

        Section (courses: "Electrical Engineering",
                 yearOfStudy:["FEEYear1","FEEYear2","FEEYear3","FEEYear4","FEEYear5"],
                 expanded: false),

        Section (courses: "Civil Engineering",
                 yearOfStudy:["FCEYear1","FCEYear2","FCEYear3","FCEYear4","FCEYear5"],
                 expanded: false),

        Section (courses: "Geospatial Engineering",
                 yearOfStudy:["FGEYear1","FGEYear2","FGEYear3","FGEYear4","FGEYear5"],
                 expanded: false),

        Section (courses: "Mechanical Engineering",
                 yearOfStudy:["FMEYear1","FMEYear2","FMEYear3","FMEYear4","FMEYear5"],
                 expanded: false),

        Section (courses: "Biosystems Engineering",
                 yearOfStudy:["FBEYear1","FBEYear2","FBEYear3","FBEYear4","FBEYear5"],
                 expanded: false)
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].yearOfStudy.count
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (sections[indexPath.section].expanded){return 44}
        else{return 0}
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 2
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header=ExpandableHeaderView()
        header.customInit(title: sections[section].courses, section: section, delegate: self)
        return header
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "labelCell")!
       cell.textLabel?.text = sections[indexPath.section].yearOfStudy[indexPath.row]
        return cell
    }

    func toggleSection(header: ExpandableHeaderView, section: Int) {
        sections[section].expanded = !sections[section].expanded
        tableView.beginUpdates()
        for i in 0..<sections[section].yearOfStudy.count{
            tableView.reloadRows(at: [IndexPath(row:i,section:section)], with: .automatic)
        }
        tableView.endUpdates()
    }

 /*   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let unitsVC = UnitsVC()
        unitsVC.customInit(sectionsIndex: indexPath.row, title: sections[indexPath.row])
        self.navigationController?.pushViewController(unitsVC, animated: true)
        tableView.deselectRow(at: indexPath, animated: true)
    }
    */
}
</code>```

The image is for the first page of my project app

In the second code, which has the functionality of the second ViewController that displays the units of various studyYears accordingly depending on which is selected I get an error on the line written: " cell.textLabel?.text = unitsData[sectionsIndex][indexPath.row] "
which says, " cannot assign value of type '[string]' to 'string?' ". How do  I get rid of these errors?

```<code>import UIKit

class UnitsVC: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableView: UITableView!

    let unitsData = [
        [["fee101","fee111","fee121","fee131","fee141","fee151","fee161","fee102","fee112","fee122","fee132","fee142","fee152","fee162"],["fee201","fee221","fee231","fee241","fee251","fee261","fee271","fee281","fee202","fee222","fee232","fee242","fee252","fee262","fee272","fee282"],["fee301","fee321","fee331","fee341","fee351","fee361","fee371","fee381","fee302","fee322","fee332","fee342","fee352","fee362","fee372","fee382"],["fee401","fee411","fee421","fee431","fee441","fee451","fee471","fee481","fee402","fee412","fee422","fee432","fee442","fee452","fee472","fee482"],["fee501","fee511","fee521","fee531","fee541","fee551","fee560","fee571","fee591","fee502","fee512","fee522","fee532","fee542","fee552","fee560","fee582","fee592"]],

        [["fce101","fce131","fce161","fce163","fce165","fce181","fce103","fce132","fce162","fce164","fce166","fce182"],
         ["fce201","fce231","fce211","fce245","fce251","fce261","fce265","fce232","fce242","fce222","fce246","fce262","fce272"],
         ["fce301","fce311","fce321","fce331","fce341","fce351","fce361","fce302","fce312","fce322","fce332","fce342","fce352","fce362","fce392"],
         ["fce401","fce411","fce421","fce425","fce431","fce451","fce461","fce481","fce402","fce412","fce422","fce426","fce432","fce446","fce472"],
         ["fce581","fce511","fce525","fce531","fce545","fce571","fce564","fce590","fce512","fce526","fce532","fce572","fce552"]],

        [["fme169","fme111","fme151","fme161","fme171","fme173","fme112","fme152","fme165","fme166","fme167","fme168","fme172","fme174","fme182"],["fme201","fme211","fme251","fme261","fme271","fme281","fme291","fme202","fme212","fme222","fme244","fme252","fme262","fme272"],["fme301","fme311","fme321","fme331","fme343","fme351","fme371","fme363","fme391","fme302","fme312","fme322","fme332","fme344","fme352","fme362","fme372"],["fme411","fme431","fme432","fme452","fme471","fme472","fme492","fme401","fme421","fme422","fme441","fme442","fme461","fme462"],["fme511","fme521","fme531","fme541","fme551","fme561","fme581","fme502","fme503","fme504","fme513","fme523","fme524","fme525","fme533","fme524","fme542","fme543","fme544","fme545","fme552"]]

    ]

    var sectionsIndex: Int!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.dataSource = self
        self.tableView.delegate = self

        let nib = UINib(nibName:"UnitsCell", bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: "unitsCell")

        // Do any additional setup after loading the view.
    }

    func customInit(sectionsIndex:Int, title: String ) {

        self.sectionsIndex=sectionsIndex
        self.title=title//attribute for navigation controller bar
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return unitsData[sectionsIndex].count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "unitsCell", for: indexPath) as! UnitsCell
       cell.textLabel?.text = unitsData[sectionsIndex][indexPath.row]//line with error
        return cell

    }
</code>```

答:
Looks like you have an array of array's. So, based on your image, lets say you want to select year 3 from Electrical Engineering.

(I'm assuming your using TableView Sections for this answer since you didn't provide additional code.)

To grab year 3, you would simply access like let year3Data = unitsData[0][2]

Body:
the first code is responsible for my first view controller attached in the linked picture, it runs just fine until I add the commented bit which enables user to be push to the next view whereby study units should be displayed according to the selected yearOfStudy e.g by tapping on FEEYear3 as in the pic, units of that study year under the respective course are displayed. When I uncomment, I get an error saying:" Cannot convert value of type 'Section' to expected argument type 'String' ". I should add that 'Section' under var sections is set as a struct.

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, ExpandableHeaderViewDelegate{

    @IBOutlet var tableView: UITableView!

    var sections=[

        Section (courses: "Electrical Engineering",
                 yearOfStudy:["FEEYear1","FEEYear2","FEEYear3","FEEYear4","FEEYear5"],
                 expanded: false),

        Section (courses: "Civil Engineering",
                 yearOfStudy:["FCEYear1","FCEYear2","FCEYear3","FCEYear4","FCEYear5"],
                 expanded: false),

        Section (courses: "Geospatial Engineering",
                 yearOfStudy:["FGEYear1","FGEYear2","FGEYear3","FGEYear4","FGEYear5"],
                 expanded: false),

        Section (courses: "Mechanical Engineering",
                 yearOfStudy:["FMEYear1","FMEYear2","FMEYear3","FMEYear4","FMEYear5"],
                 expanded: false),

        Section (courses: "Biosystems Engineering",
                 yearOfStudy:["FBEYear1","FBEYear2","FBEYear3","FBEYear4","FBEYear5"],
                 expanded: false)
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].yearOfStudy.count
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (sections[indexPath.section].expanded){return 44}
        else{return 0}
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 2
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header=ExpandableHeaderView()
        header.customInit(title: sections[section].courses, section: section, delegate: self)
        return header
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "labelCell")!
       cell.textLabel?.text = sections[indexPath.section].yearOfStudy[indexPath.row]
        return cell
    }

    func toggleSection(header: ExpandableHeaderView, section: Int) {
        sections[section].expanded = !sections[section].expanded
        tableView.beginUpdates()
        for i in 0..<sections[section].yearOfStudy.count{
            tableView.reloadRows(at: [IndexPath(row:i,section:section)], with: .automatic)
        }
        tableView.endUpdates()
    }

 /*   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let unitsVC = UnitsVC()
        unitsVC.customInit(sectionsIndex: indexPath.row, title: sections[indexPath.row])
        self.navigationController?.pushViewController(unitsVC, animated: true)
        tableView.deselectRow(at: indexPath, animated: true)
    }
    */
}

The image is for the first page of my project app

In the second code, which has the functionality of the second ViewController that displays the units of various studyYears accordingly depending on which is selected I get an error on the line written: " cell.textLabel?.text = unitsData[sectionsIndex][indexPath.row] "
which says, " cannot assign value of type '[string]' to 'string?' ". How do  I get rid of these errors?

import UIKit

class UnitsVC: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableView: UITableView!

    let unitsData = [
        [["fee101","fee111","fee121","fee131","fee141","fee151","fee161","fee102","fee112","fee122","fee132","fee142","fee152","fee162"],["fee201","fee221","fee231","fee241","fee251","fee261","fee271","fee281","fee202","fee222","fee232","fee242","fee252","fee262","fee272","fee282"],["fee301","fee321","fee331","fee341","fee351","fee361","fee371","fee381","fee302","fee322","fee332","fee342","fee352","fee362","fee372","fee382"],["fee401","fee411","fee421","fee431","fee441","fee451","fee471","fee481","fee402","fee412","fee422","fee432","fee442","fee452","fee472","fee482"],["fee501","fee511","fee521","fee531","fee541","fee551","fee560","fee571","fee591","fee502","fee512","fee522","fee532","fee542","fee552","fee560","fee582","fee592"]],

        [["fce101","fce131","fce161","fce163","fce165","fce181","fce103","fce132","fce162","fce164","fce166","fce182"],
         ["fce201","fce231","fce211","fce245","fce251","fce261","fce265","fce232","fce242","fce222","fce246","fce262","fce272"],
         ["fce301","fce311","fce321","fce331","fce341","fce351","fce361","fce302","fce312","fce322","fce332","fce342","fce352","fce362","fce392"],
         ["fce401","fce411","fce421","fce425","fce431","fce451","fce461","fce481","fce402","fce412","fce422","fce426","fce432","fce446","fce472"],
         ["fce581","fce511","fce525","fce531","fce545","fce571","fce564","fce590","fce512","fce526","fce532","fce572","fce552"]],

        [["fme169","fme111","fme151","fme161","fme171","fme173","fme112","fme152","fme165","fme166","fme167","fme168","fme172","fme174","fme182"],["fme201","fme211","fme251","fme261","fme271","fme281","fme291","fme202","fme212","fme222","fme244","fme252","fme262","fme272"],["fme301","fme311","fme321","fme331","fme343","fme351","fme371","fme363","fme391","fme302","fme312","fme322","fme332","fme344","fme352","fme362","fme372"],["fme411","fme431","fme432","fme452","fme471","fme472","fme492","fme401","fme421","fme422","fme441","fme442","fme461","fme462"],["fme511","fme521","fme531","fme541","fme551","fme561","fme581","fme502","fme503","fme504","fme513","fme523","fme524","fme525","fme533","fme524","fme542","fme543","fme544","fme545","fme552"]]

    ]

    var sectionsIndex: Int!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.dataSource = self
        self.tableView.delegate = self

        let nib = UINib(nibName:"UnitsCell", bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: "unitsCell")

        // Do any additional setup after loading the view.
    }

    func customInit(sectionsIndex:Int, title: String ) {

        self.sectionsIndex=sectionsIndex
        self.title=title//attribute for navigation controller bar
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return unitsData[sectionsIndex].count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "unitsCell", for: indexPath) as! UnitsCell
       cell.textLabel?.text = unitsData[sectionsIndex][indexPath.row]//line with error
        return cell

    }


问:
Size of file differs when downloading via curl
I wrote some php code to download a xml file sent via mail from Google Adwords to put the data into a mysql database.

One of the functions downloads the file to a webspace, but the size of the file differs from the file, I manually downloaded via chrome (1,8MB vs 1,6MB). Visually there is no difference between them.

The file which has been manually downloaded can be processed, but the file, which has been downloaded via curl can't be processed by simplexml.

Here is the code of the download function:

```<code>function downloadUrlToFile( $url, $outFileName ) {
    if ( is_file( $url ) ) {
        copy( $url, $outFileName );
    } else {
        $options = array(
            CURLOPT_FILE => fopen( $outFileName, 'w' ),
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HEADER => false,
            CURLOPT_TIMEOUT => 28800,
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => array(
                'Host   hostname',
                'User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0',
                'Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language    en-US,en;q=0.5',
                'Accept-Encoding    gzip, deflate',
                'Connection keep-alive', )

        );
        $ch = curl_init();
        curl_setopt_array( $ch, $options );
        curl_exec( $ch );
    }
}
</code>```

Edit:

Here the new code which does not work, too. I added the : to the header. But now the file is empty (2kb).

```<code>function downloadUrlToFile( $url, $outFileName ) {
    if ( is_file( $url ) ) {
        copy( $url, $outFileName );
    } else {
        $options = array(
            CURLOPT_FILE => fopen( $outFileName, 'w' ),
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HEADER => false,
            CURLOPT_TIMEOUT => 28800,
            CURLOPT_URL => $url,

            CURLOPT_HTTPHEADER => array(
                'Host: '.gethostname(),
                'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0',
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language:    en-US,en;q=0.5',
                'Accept-Encoding:    gzip, deflate',
                'Connection: keep-alive', )

        );

        $ch = curl_init();
        curl_setopt_array( $ch, $options );
        curl_exec( $ch );
    }
}
</code>```

答:
Now it works.

The xml files weren't the same, although I first thought so.

Google sends the xml files in english language when downloaded by a server. When downloaded manually, they are sent in the browser's language.

Body:
I wrote some php code to download a xml file sent via mail from Google Adwords to put the data into a mysql database.

One of the functions downloads the file to a webspace, but the size of the file differs from the file, I manually downloaded via chrome (1,8MB vs 1,6MB). Visually there is no difference between them.

The file which has been manually downloaded can be processed, but the file, which has been downloaded via curl can't be processed by simplexml.

Here is the code of the download function:

function downloadUrlToFile( $url, $outFileName ) {
    if ( is_file( $url ) ) {
        copy( $url, $outFileName );
    } else {
        $options = array(
            CURLOPT_FILE => fopen( $outFileName, 'w' ),
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HEADER => false,
            CURLOPT_TIMEOUT => 28800,
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => array(
                'Host   hostname',
                'User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0',
                'Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language    en-US,en;q=0.5',
                'Accept-Encoding    gzip, deflate',
                'Connection keep-alive', )

        );
        $ch = curl_init();
        curl_setopt_array( $ch, $options );
        curl_exec( $ch );
    }
}

Edit:

Here the new code which does not work, too. I added the : to the header. But now the file is empty (2kb).

function downloadUrlToFile( $url, $outFileName ) {
    if ( is_file( $url ) ) {
        copy( $url, $outFileName );
    } else {
        $options = array(
            CURLOPT_FILE => fopen( $outFileName, 'w' ),
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HEADER => false,
            CURLOPT_TIMEOUT => 28800,
            CURLOPT_URL => $url,

            CURLOPT_HTTPHEADER => array(
                'Host: '.gethostname(),
                'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0',
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language:    en-US,en;q=0.5',
                'Accept-Encoding:    gzip, deflate',
                'Connection: keep-alive', )

        );

        $ch = curl_init();
        curl_setopt_array( $ch, $options );
        curl_exec( $ch );
    }
}


问:
Perform join on two tables in HQL
Consider table A and B. Entire column in table A and only one column in table B need to be taken.Previously,a named query is created with which entire column values of table A are taken. Now i need to include one column of table B too.

In DAO class,below is code

```<code>X x=null
 Query query = getEntityManager().createNamedQuery("AAA").setParameter("serialID",val);
 x=(X) query.getSingleResult()
</code>```

And in DTO class, AAA is part of class X which refers to table A. The query of AAA is below:

```<code>select X from A X where COLUMNVAL= serialID;
</code>```

Now, table B also has COLUMNVAL too and i need to consider value of xyz column from that table.Consider xyz is mapped in class Q.

I tried the below query for which i got classcast exception as java.lang.object cannot be cast to A

```<code>select X, Q.xyz from A X, B Q where X.COLUMNVAL = Q.COLUMNVAL AND X.COLUMNVAL=serialID
</code>```

Please favour how to proceed further. A has huge number of columns so ResultList is not preferred.

答:
Create a ResultDTO class, which extends entity class A thus having all fields from class A and have its own required field(xyz) of the entity class B. Now you can do this to get ResultDTO:

```<code>String queryString = "select a, b.xyz from A a join B b on(a.field = b.field)"
            + " where a.serialID = :serialID";

return (List<ResultDTO>) entityManager.createQuery(queryString)
    .setParameter("serialID", serialId);
    .unwrap(org.hibernate.query.Query.class)
    .setResultTransformer(Transformers.aliasToBean(ResultDTO.class))
    .getResultList();
</code>```

Moreover, I would suggest you to read this post The best way to map a projection query to a DTO (Data Transfer Object) with JPA and Hibernate

Title: Perform join on two tables in HQL

Body:
Consider table A and B. Entire column in table A and only one column in table B need to be taken.Previously,a named query is created with which entire column values of table A are taken. Now i need to include one column of table B too.

In DAO class,below is code

X x=null
 Query query = getEntityManager().createNamedQuery("AAA").setParameter("serialID",val);
 x=(X) query.getSingleResult()

And in DTO class, AAA is part of class X which refers to table A. The query of AAA is below:

select X from A X where COLUMNVAL= serialID;

Now, table B also has COLUMNVAL too and i need to consider value of xyz column from that table.Consider xyz is mapped in class Q.

I tried the below query for which i got classcast exception as java.lang.object cannot be cast to A

select X, Q.xyz from A X, B Q where X.COLUMNVAL = Q.COLUMNVAL AND X.COLUMNVAL=serialID

Please favour how to proceed further. A has huge number of columns so ResultList is not preferred.

Body:
Create a ResultDTO class, which extends entity class A thus having all fields from class A and have its own required field(xyz) of the entity class B. Now you can do this to get ResultDTO:

String queryString = "select a, b.xyz from A a join B b on(a.field = b.field)"
            + " where a.serialID = :serialID";

return (List<ResultDTO>) entityManager.createQuery(queryString)
    .setParameter("serialID", serialId);
    .unwrap(org.hibernate.query.Query.class)
    .setResultTransformer(Transformers.aliasToBean(ResultDTO.class))
    .getResultList();

Moreover, I would suggest you to read this post The best way to map a projection query to a DTO (Data Transfer Object) with JPA and Hibernate


问:
Ajax script does not update DOM
I have a little Ajax script that executes a POST and returns the result on screen.
I debugged the script and I can see that the POST is successful, however I cannot get the result displayed on screen. It looks like I need an extra refresh or something. Any ideas what's wrong?

Thanks in advance
Regards

```<code>$(document).ready(function() {

    $("#vehicleMessages").submit(function(event) {
        event.preventDefault();
        ajaxPost();

    });

});

function ajaxPost() {

    var form = $("#vehicleMessages");

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: form.attr("action") + "?tripId=" + $("#tripId").val() + "&partitionKey=" + $("#partitionKey").val(),
        dataType: 'json',
        success: function(result) {
            if (result.status == "Done") {
                $("#postResult").html("Result: " + result.data);
            }
        }
    });
}
</code>```

答:
You have to be sure that the result.status is "Done".

You have to be sure that the result.data is text or HTML-text

I suggest you to try this:

```<code> $.ajax({
     type: "POST",
     contentType: "application/json",
     url: form.attr("action") + "?tripId=" + $("#tripId").val() + "&partitionKey=" + $("#partitionKey").val(),
     dataType: 'json'
 }).then(function (result) {
     if (result.status == "Done") {
         $("#postResult").html("Result: " + result.data);
     }
 });
</code>```

Title: Ajax script does not update DOM

Body:
I have a little Ajax script that executes a POST and returns the result on screen.
I debugged the script and I can see that the POST is successful, however I cannot get the result displayed on screen. It looks like I need an extra refresh or something. Any ideas what's wrong?

Thanks in advance
Regards

$(document).ready(function() {

    $("#vehicleMessages").submit(function(event) {
        event.preventDefault();
        ajaxPost();

    });

});

function ajaxPost() {

    var form = $("#vehicleMessages");

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: form.attr("action") + "?tripId=" + $("#tripId").val() + "&partitionKey=" + $("#partitionKey").val(),
        dataType: 'json',
        success: function(result) {
            if (result.status == "Done") {
                $("#postResult").html("Result: " + result.data);
            }
        }
    });
}

Body:
You have to be sure that the result.status is "Done".

You have to be sure that the result.data is text or HTML-text

I suggest you to try this:

 $.ajax({
     type: "POST",
     contentType: "application/json",
     url: form.attr("action") + "?tripId=" + $("#tripId").val() + "&partitionKey=" + $("#partitionKey").val(),
     dataType: 'json'
 }).then(function (result) {
     if (result.status == "Done") {
         $("#postResult").html("Result: " + result.data);
     }
 });


问:
Adding instance store volume to AWS C5 instance
Trying to run some HammerDB benchmarks and it appears that the new AWS C5 instances have no store volume. Is there any way to attach some?</p>

答:
C5 is not supported for instance store. See: Amazon EC2 Instance Store

Even if your instance type supports instance store:

If you need additional instance store volumes, you must add them to
  the instance as you launch it.

See: Adding Instance Store Volumes to an Instance?


问:
Reading a file and adding NewLine after every ";"
I have a hobby CNC machine with a strangely written software. In order to use it, I need to take my file that is outputted by a CAD software and add a new line (CRLF) after every ";". I wanted to make a python script that would do this instead, but I can't get it to work. Can anyone point me in the right direction?</p>

```<code>import os
import sys

if not (len(sys.argv) == 2 and os.path.isfile(sys.argv[1])):
    print(__doc__)
    sys.exit(1)

file_in = open(sys.argv[1], "r+")
currentChar = file_in.read(1)
i = 0
while not currentChar:
    if (currentChar == ";"):
        file_in.seek(i)
        file_in.write("\n")
    currentChar = file_in.read(1)
    i += 1
file_in.close()
</code>```

答:
As mentioned by CristiFati's comment, you should read the file, close it and then open it for writing:

```<code>import sys

file_in = open(sys.argv[1],'r')
content = file_in.read()
file_in.close()
file_out = open(sys.argv[1],'w')
file_out.write(content.replace(';',';\n'))
file_out.close()
</code>```

Optionally you can change the output filename to be something different so that you don't overwrite your original file.

Body:
I have a hobby CNC machine with a strangely written software. In order to use it, I need to take my file that is outputted by a CAD software and add a new line (CRLF) after every ";". I wanted to make a python script that would do this instead, but I can't get it to work. Can anyone point me in the right direction?

import os
import sys

if not (len(sys.argv) == 2 and os.path.isfile(sys.argv[1])):
    print(__doc__)
    sys.exit(1)

file_in = open(sys.argv[1], "r+")
currentChar = file_in.read(1)
i = 0
while not currentChar:
    if (currentChar == ";"):
        file_in.seek(i)
        file_in.write("\n")
    currentChar = file_in.read(1)
    i += 1
file_in.close()

Body:
As mentioned by CristiFati's comment, you should read the file, close it and then open it for writing:

import sys

file_in = open(sys.argv[1],'r')
content = file_in.read()
file_in.close()
file_out = open(sys.argv[1],'w')
file_out.write(content.replace(';',';\n'))
file_out.close()

Optionally you can change the output filename to be something different so that you don't overwrite your original file.


问:
Storing multiple grep parameters in a bash variable
I want to store multiple grep parameters in a bash variable, so I can define the parameters in the configuration section at the top of my file, and use it in multiple locations.

How do I need to define the variable and write the grep command?

Details

My first attempt

```<code># CONFIG: grep parameters to further filter ...
GREP_PARAM="-E .*"

# ...

grep "^Stop " $1 | grep $GREP_PARAM | sed "..." >>$TFILE
</code>```

results in

grep: ..: Is a directory

Using .\* or .\\* instead causes grep to not match anything, instead of everything.

Using grep "$GREP_PARAM" instead only works if GREP_PARAM contains a single parameter, but not otherwise; e.g. if it contains -v .*SAT.* or -v .\*SAT.\* or -v .\\*SAT.\\*, I get

grep: invalid option --

答:
This is exactly what arrays were introduced to handle.</p>

```<code>grep_options=(-E '.*')

grep "^Stop " "$1" | grep "${grep_options[@]}" | sed "..." >> "$TFILE"
</code>```

Body:
I want to store multiple grep parameters in a bash variable, so I can define the parameters in the configuration section at the top of my file, and use it in multiple locations.

How do I need to define the variable and write the grep command?

Details

My first attempt

# CONFIG: grep parameters to further filter ...
GREP_PARAM="-E .*"

# ...

grep "^Stop " $1 | grep $GREP_PARAM | sed "..." >>$TFILE

results in

grep: ..: Is a directory

Using .\* or .\\* instead causes grep to not match anything, instead of everything.

Using grep "$GREP_PARAM" instead only works if GREP_PARAM contains a single parameter, but not otherwise; e.g. if it contains -v .*SAT.* or -v .\*SAT.\* or -v .\\*SAT.\\*, I get

grep: invalid option --

Body:
This is exactly what arrays were introduced to handle.

grep_options=(-E '.*')

grep "^Stop " "$1" | grep "${grep_options[@]}" | sed "..." >> "$TFILE"


问:
Check Whether A field of a table has been filled by BLOB
I set up a table(blob_table) with 2 column: blob_name, blob_file.

The column blob_file was set NULL as default, and to be stored with BLOB.

After populate some rows with blob and some not, I try to run PHP below:

```<code><?php

$con = new mysqli('localhost','root','root','database');
if ($con->connect_error) {die("error!");}

echo "<div><table><tr><th>Blob Not Yet Upload</th></tr>";

$sql = $con->prepare("SELECT blob_name FROM blob_table WHERE blob_file IS NULL");
$sql->execute();
$result = $sql->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr><td>".$row['blob_name']."</td></tr>";
}
echo "</table></div>";
mysqli_close($con);
?>
</code>```

It didn't return anything, why? I am expecting that those blob_name for those NULL in blob_file column returned...

答:
use this</p>

```<code>   <?php

    $con = new mysqli('localhost','root','root','database');
    if ($con->connect_error) {die("error!");}

    echo "<div><table><tr><th>Blob Not Yet Upload</th></tr>";

    $sql = $con->query("SELECT blob_name FROM blob_table WHERE blob_file = '' ");

    while ($row = $sql->fetch_assoc()) {
    echo "<tr><td>".$row['blob_name']."</td></tr>";
    }
    echo "</table></div>";
    mysqli_close($con);
    ?>
</code>```

Body:
I set up a table(blob_table) with 2 column: blob_name, blob_file.

The column blob_file was set NULL as default, and to be stored with BLOB.

After populate some rows with blob and some not, I try to run PHP below:

<?php

$con = new mysqli('localhost','root','root','database');
if ($con->connect_error) {die("error!");}

echo "

Blob Not Yet Upload
";

$sql = $con->prepare("SELECT blob_name FROM blob_table WHERE blob_file IS NULL");
$sql->execute();
$result = $sql->get_result();
while ($row = $result->fetch_assoc()) {
echo "
".$row['blob_name']."
";
}
echo "

";
mysqli_close($con);
?>

It didn't return anything, why? I am expecting that those blob_name for those NULL in blob_file column returned...

Body:
use this

   <?php

    $con = new mysqli('localhost','root','root','database');
    if ($con->connect_error) {die("error!");}

    echo "<div><table><tr><th>Blob Not Yet Upload</th></tr>";

    $sql = $con->query("SELECT blob_name FROM blob_table WHERE blob_file = '' ");

    while ($row = $sql->fetch_assoc()) {
    echo "<tr><td>".$row['blob_name']."</td></tr>";
    }
    echo "</table></div>";
    mysqli_close($con);
    ?>

ContentLicense: CC BY-SA 4.0


问:
ASP.NET Core with form tag - validate form onsubmit and prevent submission
I have an ASP.NET Core 2.0 project where I use the form tag for a submission. Now I want to add some client side validation on my form submission. So I use the onsubmit tag on my form like this:

<form id="formId" asp-action="ActionName" onsubmit="validationFunction(Event)">
```

<p>and I have a function like this:</p>

<pre class="lang-js prettyprint-override"><code>function validationFunction(e) {
    //CheckStuff
    e.preventDefault();
}
</code>```

Now when I submit my form, the function is triggered properly but the e.preventDefault() doesn't stop the submission. Nor does return false.

How can I prevent my submission from completing?

PS. I know that I could probably handle the case with the button click and submit my form when I complete my validation but I was wondering why doesn't the above work in ASP.NET Core or what am I missing?

答:
If you want to do it "correct" and easiest way set the validation in the class ex:

```<code>public class Movie
{
public int ID { get; set; }

[StringLength(60, MinimumLength = 3)]
[Required]
public string Title { get; set; }

[Display(Name = "Release Date")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }

[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
[StringLength(30)]
public string Genre { get; set; }

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[StringLength(5)]
[Required]
public string Rating { get; set; }
}
</code>```

https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation

Or with JavaScript
and even HTML

Body:
I have an ASP.NET Core 2.0 project where I use the form tag for a submission. Now I want to add some client side validation on my form submission. So I use the onsubmit tag on my form like this:

<form id="formId" asp-action="ActionName" onsubmit="validationFunction(Event)">

and I have a function like this:

function validationFunction(e) {
    //CheckStuff
    e.preventDefault();
}

Now when I submit my form, the function is triggered properly but the e.preventDefault() doesn't stop the submission. Nor does return false.

How can I prevent my submission from completing?

PS. I know that I could probably handle the case with the button click and submit my form when I complete my validation but I was wondering why doesn't the above work in ASP.NET Core or what am I missing?

Body:
If you want to do it "correct" and easiest way set the validation in the class ex:

public class Movie
{
public int ID { get; set; }

[StringLength(60, MinimumLength = 3)]
[Required]
public string Title { get; set; }

[Display(Name = "Release Date")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }

[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
[StringLength(30)]
public string Genre { get; set; }

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[StringLength(5)]
[Required]
public string Rating { get; set; }
}

https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation

Or with JavaScript
and even HTML


问:
Serverless Nested Stack - An error occurred: LogStack
I use serverless for deploying my application (NodeJS) to AWS. Until yesterday i had totaly 55 endpoints & 4 Lambda functions it was working fine. Now I have 64 endpoints & 5 lambda functions I got below error

```<code>**The Cloud Formation template is invalid: Template format error: Number of resources, 232, is greater than maximum allowed, 200**
</code>```

So i tried serverless-nested-stack plugin now I get below errors

```<code>**An error occurred: APIStack - Template format error: Number of resources, 221, is greater than maximum allowed, 200**

**An error occurred: LogStack - Embedded stack arn:aws:cloudformation:eu-central-1:943203963451:stack/premierxnew-dev-LogStack-1GT5J43EL92T9/de4913a0-db05-11e7-909b-50a68ae71462 was not successfully c
reated: The following resource(s) failed to create: [AppOtherLogGroup, AppFaqLogGroup, AppUserLogGroup, AppOrderLogGroup, AppEventLogGroup]. .**
</code>```

Please let me know how to fix this issue.

答:
You've reached a hard limit of CloudFormation template. The doc says you should split your resources between multiple nested stacks to workaround this limit. I assume you use the serverless deploy command which, as the doc tells:

"[...] translates all syntax in serverless.yml to a single AWS
  CloudFormation template".

But there is hope, there's actually a GitHub issue on this subject: https://github.com/serverless/serverless/issues/2995.

And users in the thread are suggesting the use of this plugin: https://github.com/dougmoscrop/serverless-plugin-split-stacks.

The goal of this plugin is to split some resources off in to nested
  stacks to work around the 200 CloudFormation resource limit.

Hope it helps.

Body:
I use serverless for deploying my application (NodeJS) to AWS. Until yesterday i had totaly 55 endpoints & 4 Lambda functions it was working fine. Now I have 64 endpoints & 5 lambda functions I got below error

**The Cloud Formation template is invalid: Template format error: Number of resources, 232, is greater than maximum allowed, 200**

So i tried serverless-nested-stack plugin now I get below errors

**An error occurred: APIStack - Template format error: Number of resources, 221, is greater than maximum allowed, 200**

**An error occurred: LogStack - Embedded stack arn:aws:cloudformation:eu-central-1:943203963451:stack/premierxnew-dev-LogStack-1GT5J43EL92T9/de4913a0-db05-11e7-909b-50a68ae71462 was not successfully c
reated: The following resource(s) failed to create: [AppOtherLogGroup, AppFaqLogGroup, AppUserLogGroup, AppOrderLogGroup, AppEventLogGroup]. .**

Please let me know how to fix this issue.


问:
Index Out Of Bounds on List.Contains
A piece of code in the CMS I'm using (DNN) throws the following exception:

"Index was outside the bounds of the array."

With the stacktrace saying:

```<code> at System.Collections.Generic.List`1.Contains(T item)
</code>```

It is an issue that only happens sometimes (I suspect it has something to do with the cache getting broken) and only in production. This means I can't consistently reproduce it. I'm mostly interested in how it might happen.

How is it possible that a call to 'Contains' triggers an index out of bounds?

Extra info

The code calling the Contains works the following way (I've simplified the code to make the important parts more readable. The links lead to the exact classes and linenumbers)

CustomUrlDictController.cs

```<code> List<int> urlPortals;
 var cc = new CacheController();
 cc.GetFriendlyUrlIndexFromCache(out urlPortals);
 var boolean = urlPortals.Contains(portalId); // This is where the exception happens.
</code>```

CacheController.cs

```<code>void GetFriendlyUrlIndexFromCache(out List<int> urlPortals)
{
    urlPortals = null;
    object rawPortals = DataCache.GetCache(UrlPortalsKey);
    if (rawPortals != null)
    {
        urlPortals = (List<int>)rawPortals;
    }
}
</code>```

DataCache (1, 2)

```<code>object GetCache(string CacheKey)
{
    return Cache[cacheKey];
}
</code>```

Full stack trace

```<code>InnerMessage:Index was outside the bounds of the array.
InnerStackTrace:
at System.Collections.Generic.List`1.Contains(T item)
   at DotNetNuke.Entities.Urls.CustomUrlDictController.FetchCustomUrlDictionary(Int32 portalId, Boolean forceRebuild, Boolean bypassCache, FriendlyUrlSettings settings, SharedDictionary`2& customAliasForTabs, Guid parentTraceId)
   at DotNetNuke.Entities.Urls.TabPathHelper.GetTabPath(TabInfo tab, FriendlyUrlSettings settings, FriendlyUrlOptions options, Boolean ignoreCustomRedirects, Boolean homePageSiteRoot, Boolean isHomeTab, String cultureCode, Boolean isDefaultCultureCode, Boolean hasPath, Boolean& dropLangParms, String& customHttpAlias, Boolean& isCustomPath, Guid parentTraceId)
   at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.ImproveFriendlyUrlWithMessages(TabInfo tab, String friendlyPath, String pageName, PortalSettings portalSettings, Boolean ignoreCustomRedirects, FriendlyUrlSettings settings, List`1& messages, Boolean cultureSpecificAlias, Guid parentTraceId)
   at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.ImproveFriendlyUrl(TabInfo tab, String friendlyPath, String pageName, PortalSettings portalSettings, Boolean ignoreCustomRedirects, Boolean cultureSpecificAlias, FriendlyUrlSettings settings, Guid parentTraceId)
   at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.FriendlyUrlInternal(TabInfo tab, String path, String pageName, String portalAlias, PortalSettings portalSettings)
   at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.FriendlyUrl(TabInfo tab, String path, String pageName, PortalSettings portalSettings)
   at DotNetNuke.Services.Url.FriendlyUrl.DNNFriendlyUrlProvider.FriendlyUrl(TabInfo tab, String path, String pageName, PortalSettings settings)
   at DotNetNuke.Common.Globals.NavigateURL(Int32 tabID, Boolean isSuperTab, PortalSettings settings, String controlKey, String language, String pageName, String[] additionalParameters)
   at DotNetNuke.Common.Globals.NavigateURL(Int32 tabID, String controlKey, String[] additionalParameters)
   at Ventrian.SimpleGallery.RandomPhoto.GetAlbumUrl(String albumID)
   at Ventrian.SimpleGallery.RandomPhoto.BindPhoto(PlaceHolder phPhoto, PhotoInfo objPhoto)
   at Ventrian.SimpleGallery.RandomPhoto.dlGallery_OnItemDataBound(Object sender, DataListItemEventArgs e)
   at System.Web.UI.WebControls.DataList.OnItemDataBound(DataListItemEventArgs e)
   at System.Web.UI.WebControls.DataList.CreateItem(Int32 itemIndex, ListItemType itemType, Boolean dataBind, Object dataItem)
   at System.Web.UI.WebControls.DataList.CreateControlHierarchy(Boolean useDataSource)
   at System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e)
   at System.Web.UI.WebControls.BaseDataList.DataBind()
   at Ventrian.SimpleGallery.RandomPhoto.Page_Load(Object sender, EventArgs e)
</code>```

答:
I have a pull request open with a fix to this issue within DNN. We were experiencing this issue, and after making the change we have not seen this stack trace in our error logs.

https://github.com/dnnsoftware/Dnn.Platform/pull/1932

Title: Index Out Of Bounds on List.Contains

Body:
A piece of code in the CMS I'm using (DNN) throws the following exception:

"Index was outside the bounds of the array."

With the stacktrace saying:

 at System.Collections.Generic.List`1.Contains(T item)

It is an issue that only happens sometimes (I suspect it has something to do with the cache getting broken) and only in production. This means I can't consistently reproduce it. I'm mostly interested in how it might happen.

How is it possible that a call to 'Contains' triggers an index out of bounds?

Extra info

The code calling the Contains works the following way (I've simplified the code to make the important parts more readable. The links lead to the exact classes and linenumbers)

CustomUrlDictController.cs

 List<int> urlPortals;
 var cc = new CacheController();
 cc.GetFriendlyUrlIndexFromCache(out urlPortals);
 var boolean = urlPortals.Contains(portalId); // This is where the exception happens.

CacheController.cs

void GetFriendlyUrlIndexFromCache(out List<int> urlPortals)
{
    urlPortals = null;
    object rawPortals = DataCache.GetCache(UrlPortalsKey);
    if (rawPortals != null)
    {
        urlPortals = (List<int>)rawPortals;
    }
}

DataCache (1, 2)

object GetCache(string CacheKey)
{
    return Cache[cacheKey];
}

Full stack trace

InnerMessage:Index was outside the bounds of the array.
InnerStackTrace:
at System.Collections.Generic.List`1.Contains(T item)
   at DotNetNuke.Entities.Urls.CustomUrlDictController.FetchCustomUrlDictionary(Int32 portalId, Boolean forceRebuild, Boolean bypassCache, FriendlyUrlSettings settings, SharedDictionary`2& customAliasForTabs, Guid parentTraceId)
   at DotNetNuke.Entities.Urls.TabPathHelper.GetTabPath(TabInfo tab, FriendlyUrlSettings settings, FriendlyUrlOptions options, Boolean ignoreCustomRedirects, Boolean homePageSiteRoot, Boolean isHomeTab, String cultureCode, Boolean isDefaultCultureCode, Boolean hasPath, Boolean& dropLangParms, String& customHttpAlias, Boolean& isCustomPath, Guid parentTraceId)
   at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.ImproveFriendlyUrlWithMessages(TabInfo tab, String friendlyPath, String pageName, PortalSettings portalSettings, Boolean ignoreCustomRedirects, FriendlyUrlSettings settings, List`1& messages, Boolean cultureSpecificAlias, Guid parentTraceId)
   at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.ImproveFriendlyUrl(TabInfo tab, String friendlyPath, String pageName, PortalSettings portalSettings, Boolean ignoreCustomRedirects, Boolean cultureSpecificAlias, FriendlyUrlSettings settings, Guid parentTraceId)
   at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.FriendlyUrlInternal(TabInfo tab, String path, String pageName, String portalAlias, PortalSettings portalSettings)
   at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.FriendlyUrl(TabInfo tab, String path, String pageName, PortalSettings portalSettings)
   at DotNetNuke.Services.Url.FriendlyUrl.DNNFriendlyUrlProvider.FriendlyUrl(TabInfo tab, String path, String pageName, PortalSettings settings)
   at DotNetNuke.Common.Globals.NavigateURL(Int32 tabID, Boolean isSuperTab, PortalSettings settings, String controlKey, String language, String pageName, String[] additionalParameters)
   at DotNetNuke.Common.Globals.NavigateURL(Int32 tabID, String controlKey, String[] additionalParameters)
   at Ventrian.SimpleGallery.RandomPhoto.GetAlbumUrl(String albumID)
   at Ventrian.SimpleGallery.RandomPhoto.BindPhoto(PlaceHolder phPhoto, PhotoInfo objPhoto)
   at Ventrian.SimpleGallery.RandomPhoto.dlGallery_OnItemDataBound(Object sender, DataListItemEventArgs e)
   at System.Web.UI.WebControls.DataList.OnItemDataBound(DataListItemEventArgs e)
   at System.Web.UI.WebControls.DataList.CreateItem(Int32 itemIndex, ListItemType itemType, Boolean dataBind, Object dataItem)
   at System.Web.UI.WebControls.DataList.CreateControlHierarchy(Boolean useDataSource)
   at System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e)
   at System.Web.UI.WebControls.BaseDataList.DataBind()
   at Ventrian.SimpleGallery.RandomPhoto.Page_Load(Object sender, EventArgs e)


问:
Parsing Buffered Bytes into Integers with sscanf - C
I am receiving Serial commands, and I would like to be able to parse out data from between the comas.  An example, would be "SET,1,3,1" and then be able to parse out the 1,3,1 as integers.  After doing some reading I tried to accomplish this with a sscanf, but when I monitor the variables, they are not being set properly.

Here is my code:

```<code>if (strncmp(command_buf, "SET,1,3,1", 9) == 0) {

              u32_t port_number;
              u32_t pin_number;
              u32_t logic_level;

              sscanf(command_buf + 4, "%u,%u,%u", &port_number, &pin_number, &logic_level);
            }
</code>```

I have also tried this for example, but the variable is 0

```<code>u32_t port_number = command_buf[5];
</code>```

答:
```<code>sscanf(command_buf + 4, "%lu,%lu,%lu", &port_number, &pin_number, &logic_level);
</code>```

You just need to parse the input string like this. This would work. (u32_t is 32 bit unsigned long).

You can do it using sscanf. Because you wanted to parse from string not a  stream.

Also you should check the return value of sscanf to check whether it is getting the inputs right.

Body:
I am receiving Serial commands, and I would like to be able to parse out data from between the comas.  An example, would be "SET,1,3,1" and then be able to parse out the 1,3,1 as integers.  After doing some reading I tried to accomplish this with a sscanf, but when I monitor the variables, they are not being set properly.

Here is my code:

if (strncmp(command_buf, "SET,1,3,1", 9) == 0) {

              u32_t port_number;
              u32_t pin_number;
              u32_t logic_level;

              sscanf(command_buf + 4, "%u,%u,%u", &port_number, &pin_number, &logic_level);
            }

I have also tried this for example, but the variable is 0

u32_t port_number = command_buf[5];

Body:
sscanf(command_buf + 4, "%lu,%lu,%lu", &port_number, &pin_number, &logic_level);

You just need to parse the input string like this. This would work. (u32_t is 32 bit unsigned long).

You can do it using sscanf. Because you wanted to parse from string not a  stream.

Also you should check the return value of sscanf to check whether it is getting the inputs right.


问:
Git for windows seems to automatically fall back to credential helper "manager" if everything else fails. How do I prevent this?
I'm trying to integrate a custom web page with git. In my PHP scripts, I use the option "-c credential.helper="store --file=..." so that the web page does not stop and wait for a password to be input. The User ID is specifically designated for automated tasks like this. As part of the web interface, I have some code that will update the credentials file when the password expires.

During development, when I issue the git commands at the windows command prompt (the "terminal" for you *NIX readers :) they all work fine. However, when I put the commands inside my PHP script and run it via the web server, they fail. I've managed to capture the output of the git task, and it's waiting for someone to type in a user ID.

It seems that git on windows will automatically drop back to the "manager" helper, if all other mechanisms fail. The following sequence of commands illustrates this:

```<code>C:\TFS\Train>git config --get --show-origin credential.helper

C:\TFS\Train>type .git\.git_web_credentials
http://Promote5:[.....]@tocgnxt1pv%3a8080

C:\TFS\Train>git -c credential.helper="store --file=C:\TFS\Train\.git\.git_credentials" tag -a -m "Testing tags from the command line" Who_created_this_tag2

C:\TFS\Train>git show Who_created_this_tag2
tag Who_created_this_tag2
Tagger: JimHyslop <jim.hyslop@xxx.xxx>
Date:   Wed Dec 6 18:13:27 2017 -0500

[... remainder of output elided ...]

C:\TFS\Train>git --version
git version 2.13.0.windows.1
</code>```

As you can see, the "tagger" line indicates that I'm the one who applied the tag.

I've even tried deleting the credentials file completely, but it still falls back to using my identity.

Is there any way to suppress this automatic fall back to using my Windows credentials? It's making it very difficult to debug my PHP script: I never know from the command prompt whether the command succeeded because it was able to use the credentials file, or because it fell back to using my own ID (which the web service cannot do).

Edit to add: The password is actually in the credentials file, I masked it out. The file was initially created by entering the ID and password from a Cygwin shell, which is running a slightly newer version of git: 2.15.0. I'm running a WAMP stack for my web service.

答:
After more investigation, I realized that the 'tagger' line is pulled from the configuration information under the [user] section. The user information shown in the log is unrelated to the authorization/credentials method.

The real question is: why is git ignoring the command-line option "-c credential.helper="? Or, if it's not ignoring the option, how can I figure out exactly what is failing with the credential helper?

Body:
I'm trying to integrate a custom web page with git. In my PHP scripts, I use the option "-c credential.helper="store --file=..." so that the web page does not stop and wait for a password to be input. The User ID is specifically designated for automated tasks like this. As part of the web interface, I have some code that will update the credentials file when the password expires.

During development, when I issue the git commands at the windows command prompt (the "terminal" for you *NIX readers :) they all work fine. However, when I put the commands inside my PHP script and run it via the web server, they fail. I've managed to capture the output of the git task, and it's waiting for someone to type in a user ID.

It seems that git on windows will automatically drop back to the "manager" helper, if all other mechanisms fail. The following sequence of commands illustrates this:

C:\TFS\Train>git config --get --show-origin credential.helper

C:\TFS\Train>type .git\.git_web_credentials
http://Promote5:[.....]@tocgnxt1pv%3a8080

C:\TFS\Train>git -c credential.helper="store --file=C:\TFS\Train\.git\.git_credentials" tag -a -m "Testing tags from the command line" Who_created_this_tag2

C:\TFS\Train>git show Who_created_this_tag2
tag Who_created_this_tag2
Tagger: JimHyslop <jim.hyslop@xxx.xxx>
Date:   Wed Dec 6 18:13:27 2017 -0500

[... remainder of output elided ...]

C:\TFS\Train>git --version
git version 2.13.0.windows.1

As you can see, the "tagger" line indicates that I'm the one who applied the tag.

I've even tried deleting the credentials file completely, but it still falls back to using my identity.

Is there any way to suppress this automatic fall back to using my Windows credentials? It's making it very difficult to debug my PHP script: I never know from the command prompt whether the command succeeded because it was able to use the credentials file, or because it fell back to using my own ID (which the web service cannot do).

Edit to add: The password is actually in the credentials file, I masked it out. The file was initially created by entering the ID and password from a Cygwin shell, which is running a slightly newer version of git: 2.15.0. I'm running a WAMP stack for my web service.


问:
Find all records NOT in a many-to-many association
In Rails 3 with ActiveRecord, I have 2 models (Users and Tasks). These models are linked together with a has_many :through association on another model, Assignments. How can I find all Tasks that are NOT associated to a particular user?</p>

```<code>class User < ActiveRecord::Base
  has_many :assignments
  has_many :tasks, :through => :assignments
end

class Tasks < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignments
end

class Assignments < ActiveRecord::Base
  belongs_to :users
  belongs_to :tasks
end
</code>```

答:
I'm going to assume you want those tasks without any associated user, rather than not associated to a user in particular.</p>

```<code>Tasks.joins('left outer join assignments on assignments.task_id = tasks.id').where('assignments.* is null')
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In Rails 3 with ActiveRecord, I have 2 models (Users and Tasks). These models are linked together with a has_many :through association on another model, Assignments. How can I find all Tasks that are NOT associated to a particular user?

class User < ActiveRecord::Base
  has_many :assignments
  has_many :tasks, :through => :assignments
end

class Tasks < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignments
end

class Assignments < ActiveRecord::Base
  belongs_to :users
  belongs_to :tasks
end

Body:
I'm going to assume you want those tasks without any associated user, rather than not associated to a user in particular.

Tasks.joins('left outer join assignments on assignments.task_id = tasks.id').where('assignments.* is null')


问:
What's the difference between "includes" and "joins" in ActiveRecord query?
What's the difference between "includes" and "joins" in ActiveRecord query? Can anyone explain to me with the following two associated models?

```<code>class Car < ActiveRecord::Base
  belongs_to :store
end

class Store < ActiveRecord::Base
  belongs_to :owner
  has_one :car
end
</code>```

Body:
What's the difference between "includes" and "joins" in ActiveRecord query? Can anyone explain to me with the following two associated models?

class Car < ActiveRecord::Base
  belongs_to :store
end

class Store < ActiveRecord::Base
  belongs_to :owner
  has_one :car
end

Body:
TL; DR

Joins:

a.joins(:b).to_sql
=> "SELECT \"a\".* FROM \"a\" INNER JOIN \"b\" ON \"b\".\"id\" = \"a\".\"b_id\""

Includes:

a.includes(:b).to_sql
=> "SELECT \"a\".* FROM \"a\"

Both:

a.includes(:b).joins(:b).to_sql
=> "SELECT \"a\".\"id\" AS t0_r0, \"a\".\"a_field_1\" AS t0_r1, \"a\".\"a_field_2\" AS t0_r2, \"a\".\"a_field_3\" AS t0_r3, \"b\".\"a_field_1\" AS t1_r1, \"b\".\"a_field_2\" AS t1_r2, \"b\".\"a_field_3\" AS t1_r3 FROM \"a\" INNER JOIN \"b\" ON \"b\".\"id\" = \"a\".\"plan_id\""


问:
Django Dropdown POST
... I'm new in django and I have this problem: When I want to show the data selected on my dropdown, it doesn't work ... this is the code

index.html

```<code><form method="post" action="/getdata/">
    <select name="Lista">
        <option selected="selected" disabled>Objects on page:</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
        <option value="40">40</option>
        <option value="50">50</option>
    </select>
    <input type="submit" value="Select">
</form>
</code>```

views.py

def index(request):

```<code>if request.method == 'POST':

    Lista = request.POST.get('Lista')
    print Lista

    context = {
        Lista: 'Lista'
    }

    return render(request, 'showdata.html', context)
else:
    template = loader.get_template('index.html')
    return HttpResponse(template.render())
</code>```

getdata.html

```<code><form method="post" action="/getdata/">
    <table>
        <tr>
            <td>Numero:</td>
            <td><strong>{{ Lista }}</strong></td>
    </table>
</form>
</code>```

urls.py

```<code>urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # url(r'^', views.home, name="home"),
    #define the url getdata that we have written inside form
    url(r'^getdata/', views.index),
    # defining the view for root URL
    url(r'^$', views.index),
]
</code>```

when I executed the server i just see the following "Numero: " without any number selected ...

Thanks for your help ...

答:
This is because in the context you are storing the value as the key:

```<code>Lista = request.POST.get('Lista')
print Lista

context = {
    Lista: 'Lista'
}
</code>```

If Lista is 50, then in your template you would be able to access it as {{ 50 }}	, and the output would be 'Lista'	. But this is probably not what you want.

Instead, assign the key in your view like this:

```<code>context = {
    'Lista': Lista
}
</code>```

Title: Django Dropdown POST

Body:
... I'm new in django and I have this problem: When I want to show the data selected on my dropdown, it doesn't work ... this is the code

index.html

<form method="post" action="/getdata/">
    <select name="Lista">
        <option selected="selected" disabled>Objects on page:</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
        <option value="40">40</option>
        <option value="50">50</option>
    </select>
    <input type="submit" value="Select">
</form>

views.py

def index(request):

if request.method == 'POST':

    Lista = request.POST.get('Lista')
    print Lista

    context = {
        Lista: 'Lista'
    }

    return render(request, 'showdata.html', context)
else:
    template = loader.get_template('index.html')
    return HttpResponse(template.render())

getdata.html

<form method="post" action="/getdata/">

            Numero:
            {{ Lista }}

</form>

urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # url(r'^', views.home, name="home"),
    #define the url getdata that we have written inside form
    url(r'^getdata/', views.index),
    # defining the view for root URL
    url(r'^$', views.index),
]

when I executed the server i just see the following "Numero: " without any number selected ...

Thanks for your help ...

Body:
This is because in the context you are storing the value as the key:

Lista = request.POST.get('Lista')
print Lista

context = {
    Lista: 'Lista'
}

If Lista is 50, then in your template you would be able to access it as <td><strong>{{ 50 }}</strong></td>, and the output would be <td><strong>'Lista'</strong></td>. But this is probably not what you want.

Instead, assign the key in your view like this:

context = {
    'Lista': Lista
}


问:
How o create a cronjob that import data into mongodb from remote csv/xml webservice?
Hi there i need to create a cronjob that run every 30 minutes a mongodbimport command on mi server. Basically i need to sync a RESTAPI webservice with my MongoDB server. How i can do this task?
Webservice returns thousands of products in csv or xml format.</p>

答: You need to write script/program (you can use languages like PHP, Python, JavaScript (NodeJS), ...), which will parse CSV/XML and puts the data into MongoDB. Then run this script/program via cron.</p>


问:
Rails Migration Create Table Primary Key
I am writing a migration script to create a table with a primary key column that is named guid and is a VARCHAR(25). The issue is I feel like I am having to double my effort to achieve what should be possible in one step.

If I run:

```<code>create_table(:global_feeds, :primary_key => 'guid') do |t|
  t.string :guid, :limit => 25
  t.text :title
  t.text :subtitle

  ...

  t.timestamps
end
</code>```

I get a table with a primary key called guid no column called id (which is what I want). However, the issue is the guid column is an INT(11) with auto increment turned on. So I have to run one additional command:

```<code>change_column :global_feeds, :guid, :string, :limit => 25
</code>```

Seems a bit convoluted to have to basically run two SQL commands to get what I believe should be possible in one.

Any suggestions on how to optimize this?

答:
I suppose you're using mySQL, so here is what you can try

```<code>create_table :global_feeds, {:id => false} do |t|
  t.string :guid
  t.text :title
  t.text :subtitle
  t.timestamps
end
execute "ALTER TABLE global_feeds ADD PRIMARY KEY (guid);"
</code>```

If you're not on mySQL you should change the query in the execute command to work on your DB engine. I'm not sure if you can do that on SQLite though. And don't forget to put this line somewhere in global_feed.rb model:

```<code>set_primary_key :guid
</code>```

Anyway you're getting the most out of Rails while you're sticking to its conventions. Changing primary key name and type might not be a very good idea.

Body:
I am writing a migration script to create a table with a primary key column that is named guid and is a VARCHAR(25). The issue is I feel like I am having to double my effort to achieve what should be possible in one step.

If I run:

create_table(:global_feeds, :primary_key => 'guid') do |t|
  t.string :guid, :limit => 25
  t.text :title
  t.text :subtitle

  ...

  t.timestamps
end

I get a table with a primary key called guid no column called id (which is what I want). However, the issue is the guid column is an INT(11) with auto increment turned on. So I have to run one additional command:

change_column :global_feeds, :guid, :string, :limit => 25

Seems a bit convoluted to have to basically run two SQL commands to get what I believe should be possible in one.

Any suggestions on how to optimize this?

Body:
I suppose you're using mySQL, so here is what you can try

create_table :global_feeds, {:id => false} do |t|
  t.string :guid
  t.text :title
  t.text :subtitle
  t.timestamps
end
execute "ALTER TABLE global_feeds ADD PRIMARY KEY (guid);"

If you're not on mySQL you should change the query in the execute command to work on your DB engine. I'm not sure if you can do that on SQLite though. And don't forget to put this line somewhere in global_feed.rb model:

set_primary_key :guid

Anyway you're getting the most out of Rails while you're sticking to its conventions. Changing primary key name and type might not be a very good idea.


问:
Azure Container Instances stuck in "Creating" state
Whether I have the azure agent plugin for Jenkins make my container, or if I do it manually, it seems like either way it never enters a running state.

```<code>az container create \
    --os-type Windows \
    --location eastus \
    --registry-login-server SERVER.azurecr.io \
    --registry-password PASSWORD \
    --registry-username USERNAME \
    --image namespace/image \
    --name jenkins-permanent \
    --resource-group devops-aci \
    --cpu 2 \
    --memory 3.5 \
    --restart-policy Always \
    --command-line "-jnlpUrl http://host:8080/computer/NAME/slave-agent.jnlp -secret SECRET -workDir \"C:\\jenkins\""
</code>```

I've gone through all the troubleshooting steps that apply, tried a different region, but to no avail.

Here's a current event that I got which seems to be the most progress I've had yet:

```<code>          {
            "count": 1,
            "firstTimestamp": "2017-12-07T03:02:56+00:00",
            "lastTimestamp": "2017-12-07T03:02:56+00:00",
            "message": "Failed to pull image \"MYREPO.azurecr.io/my-company/windows-agent:latest\": Error response from da
emon: {\"message\":\"Get https://MYREPO.azurecr.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout
exceeded while awaiting headers)\"}",
            "name": "Failed",
            "type": "Warning"
          }
</code>```

The funny thing is, this event happens before and after one case of the instance working (but unfortunately my entrypoint command was wrong, so it never started).

I really feel like Azure is punting on this and I just have no way to change the order I do anything.  It's simply one command.

答:
Figured it out, turns out the backslashes in the command in my executable path were not having their escapes honoured.  Either because I was calling az from bash, or because something Azure side isn't handling the escaping correctly, or not escaping them itself.

My solution has been to just use forward slashes in the paths.  Windows seems to be handling them correctly, and I prefer to not be bothered with its odd preference for backslashes.

Related to my issue is that the speed of the service makes troubleshooting very difficult. It takes a long time to go round trip with any fixes.  So if you're using Azure Container Instances and want better performance, go upvote this feedback item that I've created.

Body:
Whether I have the azure agent plugin for Jenkins make my container, or if I do it manually, it seems like either way it never enters a running state.

az container create \
    --os-type Windows \
    --location eastus \
    --registry-login-server SERVER.azurecr.io \
    --registry-password PASSWORD \
    --registry-username USERNAME \
    --image namespace/image \
    --name jenkins-permanent \
    --resource-group devops-aci \
    --cpu 2 \
    --memory 3.5 \
    --restart-policy Always \
    --command-line "-jnlpUrl http://host:8080/computer/NAME/slave-agent.jnlp -secret SECRET -workDir \"C:\\jenkins\""

I've gone through all the troubleshooting steps that apply, tried a different region, but to no avail.

Here's a current event that I got which seems to be the most progress I've had yet:

          {
            "count": 1,
            "firstTimestamp": "2017-12-07T03:02:56+00:00",
            "lastTimestamp": "2017-12-07T03:02:56+00:00",
            "message": "Failed to pull image \"MYREPO.azurecr.io/my-company/windows-agent:latest\": Error response from da
emon: {\"message\":\"Get https://MYREPO.azurecr.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout
exceeded while awaiting headers)\"}",
            "name": "Failed",
            "type": "Warning"
          }

The funny thing is, this event happens before and after one case of the instance working (but unfortunately my entrypoint command was wrong, so it never started).

I really feel like Azure is punting on this and I just have no way to change the order I do anything.  It's simply one command.


问:
Migrating data from one database to another using LEFT JOIN
Let me start by saying I am relatively new to MySQL. I am trying to migrate data from one database to another. Let us call one database DB1 and the other DB2.

DB2 has tables the following tables.

Patient: id, person_id and start_regimen_id

Regimen: id, code

Visit: id, patient_id, regimen_id,next_appointment_date

DB1 has the following tables:

Patient: id,medical_record_number,current_regimen, start_regimen nextappointment

Now:

regimen_id data should be inserted to current_regimen

start_regimen_id data should be inserted to start_regimen

next_appointment_date should be inserted to nextappointment

This is what I have now:

```<code>                 SELECT
                    p.person_id AS medical_record_number,
                    r.code AS start_regimen,
                    ??? AS current_regimen,
                    DATE_FORMAT(v.next_appointment_date, '%Y-%m-%d') AS
                    nextappointment,
                FROM patient p
                LEFT JOIN regimen r ON r.id = p.start_regimen_id
                LEFT JOIN (
                    SELECT patient_id, MAX(next_appointment_date) as next_appointment_date
                    FROM visit
                    WHERE next_appointment_date IS NOT NULL
                    GROUP BY patient_id
                ) v ON v.patient_id = p.id
</code>```

I have remained to migrate regimen_id (visit) on DB2 to current_regimen (patient) on DB1. I don't know how to use two LEFT JOIN to get data from two tables for one table.

Any assistance will be greatly appreciated because I am really stuck.

答:
Seems like we would want to include regimen_id in the GROUP BY from the visit table, and then match that to id from the regimen table.  Given the outer join, it appears that patient may not have any regimen associated, so I would include matching of NULL values of regimen_id.

```<code>    LEFT
    JOIN ( SELECT vv.patient_id
                , vv.regimen_id
                , MAX(vv.next_appointment_date) AS next_appointment_date
             FROM visit vv
            WHERE vv.next_appointment_date IS NOT NULL
            GROUP
               BY vv.patient_id
                , vv.regimen_id
         ) v
      ON v.patient_id = p.id
     AND v.regimen_id <=> r.id
</code>```

But that's just a guess. Without a specification (preferably illustrated by example data and and expected output) we're just guessing.

Note:

```<code>foo <=> bar
</code>```

is a NULL-safe comparison, a shorthand equivalent to

```<code>( foo = bar OR ( foo IS NULL AND bar IS NULL ) )
</code>```

Body:
Let me start by saying I am relatively new to MySQL. I am trying to migrate data from one database to another. Let us call one database DB1 and the other DB2.

DB2 has tables the following tables.

Patient: id, person_id and start_regimen_id

Regimen: id, code

Visit: id, patient_id, regimen_id,next_appointment_date

DB1 has the following tables:

Patient: id,medical_record_number,current_regimen, start_regimen nextappointment

Now:

regimen_id data should be inserted to current_regimen

start_regimen_id data should be inserted to start_regimen

next_appointment_date should be inserted to nextappointment

This is what I have now:

                 SELECT
                    p.person_id AS medical_record_number,
                    r.code AS start_regimen,
                    ??? AS current_regimen,
                    DATE_FORMAT(v.next_appointment_date, '%Y-%m-%d') AS
                    nextappointment,
                FROM patient p
                LEFT JOIN regimen r ON r.id = p.start_regimen_id
                LEFT JOIN (
                    SELECT patient_id, MAX(next_appointment_date) as next_appointment_date
                    FROM visit
                    WHERE next_appointment_date IS NOT NULL
                    GROUP BY patient_id
                ) v ON v.patient_id = p.id

I have remained to migrate regimen_id (visit) on DB2 to current_regimen (patient) on DB1. I don't know how to use two LEFT JOIN to get data from two tables for one table.

Any assistance will be greatly appreciated because I am really stuck.

Body:
Seems like we would want to include regimen_id in the GROUP BY from the visit table, and then match that to id from the regimen table.  Given the outer join, it appears that patient may not have any regimen associated, so I would include matching of NULL values of regimen_id.

    LEFT
    JOIN ( SELECT vv.patient_id
                , vv.regimen_id
                , MAX(vv.next_appointment_date) AS next_appointment_date
             FROM visit vv
            WHERE vv.next_appointment_date IS NOT NULL
            GROUP
               BY vv.patient_id
                , vv.regimen_id
         ) v
      ON v.patient_id = p.id
     AND v.regimen_id <=> r.id

But that's just a guess. Without a specification (preferably illustrated by example data and and expected output) we're just guessing.

Note:

foo <=> bar

is a NULL-safe comparison, a shorthand equivalent to

( foo = bar OR ( foo IS NULL AND bar IS NULL ) )


问:
Page fadeOut when links are clicked, except mailto: links
in the below code, I am fading out any page, and then fading in the new page, when any  tag is clicked. However, there are certain instances where we don't want to fade the page out on click, for example, when an  tag is set to open externally via target="_blank". The code below reflects this and is working successfully.

However, one thing I'm not sure how to achieve, is to prevent the fade out when a link contains a mailto: reference, as obviously this is designed to open a mailing client window. Therefore I don't want the page to fade out?

Thank you.

```<code>$(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
        window.location.reload();
    }
});

(function($) {
    if (window.history) {
        $(window).on('popstate', function() {
            $("body").show();
        });
    }

    // When links are clicked
    $(document).on("click", "a", function() {
    var $link   = $(this);
    var $href   = $link.attr("href");
    var $target = $link.attr("target");

        // If link exists
        if ($href) {
            // Fade out all links unless set to open in external window target="_blank"
            if ($target !== "_blank") {
                $("body").fadeOut(250, function() {
                    history.pushState($href, null, null);
                    window.location.href = $href;
                });
                return false;
            }
        }
    });

    // On page load, fade in
    $(document).ready(function() {
        $("body").fadeTo(250, 1);
    });
}(window.jQuery));
</code>```

答:
Simply check the link url:

```<code>if($href.indexOf('mailto:') === 0){
  //the url starts with mailto:
  //it is an email link
}
</code>```

More specific to your usecase, extend the if statement where you check for _blank:

```<code>if ($target !== "_blank" && $href.indexOf('mailto:') !== 0) {
  //...
}
</code>```

Body:
in the below code, I am fading out any page, and then fading in the new page, when any  tag is clicked. However, there are certain instances where we don't want to fade the page out on click, for example, when an  tag is set to open externally via target="_blank". The code below reflects this and is working successfully.

However, one thing I'm not sure how to achieve, is to prevent the fade out when a link contains a mailto: reference, as obviously this is designed to open a mailing client window. Therefore I don't want the page to fade out?

Thank you.

$(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
        window.location.reload();
    }
});

(function($) {
    if (window.history) {
        $(window).on('popstate', function() {
            $("body").show();
        });
    }

    // When links are clicked
    $(document).on("click", "a", function() {
    var $link   = $(this);
    var $href   = $link.attr("href");
    var $target = $link.attr("target");

        // If link exists
        if ($href) {
            // Fade out all links unless set to open in external window target="_blank"
            if ($target !== "_blank") {
                $("body").fadeOut(250, function() {
                    history.pushState($href, null, null);
                    window.location.href = $href;
                });
                return false;
            }
        }
    });

    // On page load, fade in
    $(document).ready(function() {
        $("body").fadeTo(250, 1);
    });
}(window.jQuery));

Body:
Simply check the link url:

if($href.indexOf('mailto:') === 0){
  //the url starts with mailto:
  //it is an email link
}

More specific to your usecase, extend the if statement where you check for _blank:

if ($target !== "_blank" && $href.indexOf('mailto:') !== 0) {
  //...
}


问:
How to write documentation tests for an internal API?
I'm writing a library which contains private structs and methods:

```<code>/// Constructs a new `Object`
///
/// Internal API
///
/// # Example
/// ```rust
/// use lib::object::Object;
///
/// let tn = Object::new();
/// ```
</code>```

When I run cargo test, the doctest fails because Object is a private struct.

Is it possible to make it compile and run?

答:
I don't think it is possible if you want the test to compile and run, see this related question.

I you only want to include the code as a sample in the documentation, without trying to compile and run it, you can exclude it from the tests by adding the ignore flag:

```<code>/// ```rust,ignore
/// use lib::object::Object;
///
/// let tn = Object::new();
/// ```
</code>```

Body:
I'm writing a library which contains private structs and methods:

/// Constructs a new `Object`
///
/// Internal API
///
/// # Example
/// ```rust
/// use lib::object::Object;
///
/// let tn = Object::new();
/// ```

When I run cargo test, the doctest fails because Object is a private struct.

Is it possible to make it compile and run?

Body:
I don't think it is possible if you want the test to compile and run, see this related question.

I you only want to include the code as a sample in the documentation, without trying to compile and run it, you can exclude it from the tests by adding the ignore flag:

/// ```rust,ignore
/// use lib::object::Object;
///
/// let tn = Object::new();
/// ```


问:
Reshape array of cells with different column sizes into matrix
I need to reshape a T1 = [1x5] cell array, where each cell is a [5x1] cell array of numbers into a S1 = [m-by-n] matrix of numbers. The problem is the initial cell array T1 may have different number of rows in each cell - meaning I don't have a square shaped array to use " cell2mat " function.

Example:

```<code>T1=[1x5] cell array
T1{1}   T1{2}   T1{3}   T1{4}   T1{5}
 1       2       3       4       5
 6       7       8       9      10
11      12      13      14      15
16      17      18      19      20
21      22      23      24
</code>```

I need to add all of the columns together:

```<code>T2=
 1   2   3   4   5
 6   7   8   9  10
11  12  13  14  15
16  17  18  19  20
21  22  23  24
</code>```

And then reshape the array into [m-by-n] array (always square shaped), in this example S1=[3x8]:

```<code>S1=
 1  2  3  4  5  6  7  8
 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
</code>```

I thought that maybe I could reshape T1 into [x-by-1] array and then reshape that array in to S1=[m-by-n]. But what should i do in order to get results like this:

```<code>T3=
1
2
3
4
...
24
</code>```

And not like

```<code>T3=
1
6
11
16
21
2
...
24
</code>```

Any help would be appreciated.

答:
One strategy would be:

Pad all of the cell array elements with NaN to make them the same size

Concatenate the padded arrays

Remove the NaNs

Reshape

That would look like this...

```<code>% 1. Get maximum size of T elements
%    Pad all elements of T up to maxn values with NaN
maxn = max(cellfun( @numel, T ));
Tpadded = cellfun( @(x) [x; NaN(maxn-numel(x))], T, 'uni', 0);
% 2. Convert to array.
Tpadded = cat( 2, Tpadded{:} );
% 3. Reshape to be one row and remove NaNs
Trow = reshape( Tpadded.', 1, [] );
Trow = Trow(~isnan(Trow));
% 4. Reshape to desired result
Tout = reshape( Trow, 8, 3 ).';
</code>```

Result

```<code>Tout = [1   2  3  4  5  6  7  8
        9  10 11 12 13 14 15 16
        17 18 19 20 21 22 23 24]
</code>```

Body:
I need to reshape a T1 = [1x5] cell array, where each cell is a [5x1] cell array of numbers into a S1 = [m-by-n] matrix of numbers. The problem is the initial cell array T1 may have different number of rows in each cell - meaning I don't have a square shaped array to use " cell2mat " function.

Example:

T1=[1x5] cell array
T1{1}   T1{2}   T1{3}   T1{4}   T1{5}
 1       2       3       4       5
 6       7       8       9      10
11      12      13      14      15
16      17      18      19      20
21      22      23      24

I need to add all of the columns together:

T2=
 1   2   3   4   5
 6   7   8   9  10
11  12  13  14  15
16  17  18  19  20
21  22  23  24

And then reshape the array into [m-by-n] array (always square shaped), in this example S1=[3x8]:

S1=
 1  2  3  4  5  6  7  8
 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24

I thought that maybe I could reshape T1 into [x-by-1] array and then reshape that array in to S1=[m-by-n]. But what should i do in order to get results like this:

T3=
1
2
3
4
...
24

And not like

T3=
1
6
11
16
21
2
...
24

Any help would be appreciated.

Body:
One strategy would be:

Pad all of the cell array elements with NaN to make them the same size

Concatenate the padded arrays

Remove the NaNs

Reshape

That would look like this...

% 1. Get maximum size of T elements
%    Pad all elements of T up to maxn values with NaN
maxn = max(cellfun( @numel, T ));
Tpadded = cellfun( @(x) [x; NaN(maxn-numel(x))], T, 'uni', 0);
% 2. Convert to array.
Tpadded = cat( 2, Tpadded{:} );
% 3. Reshape to be one row and remove NaNs
Trow = reshape( Tpadded.', 1, [] );
Trow = Trow(~isnan(Trow));
% 4. Reshape to desired result
Tout = reshape( Trow, 8, 3 ).';

Result

Tout = [1   2  3  4  5  6  7  8
        9  10 11 12 13 14 15 16
        17 18 19 20 21 22 23 24]


问:
How can I pass my locals and access the variables directly from another function?
Let's say I have this :

```<code>
def a(dict):
  locals().update(dict)
  print size

def b():
  size = 20
  f(locals())
</code>```

What do I have to do to access the size variable directly from the a function? I know of :

```<code>
size = dict["size"]
</code>```

but I think there should be a more direct way. I tried using locals().update(dict) but it didn't work. Is there a betteer way ?

答:
I know, I know, the question is old and the accepted answer is already great.

Just adding two cents because it seems obvious but not mentioned: Make size local by assigning it a (default) value explicitly.

```<code>def a(dict):
    size = 20  # size default value <- quick (and dirty?) fix
    locals().update(dict)
    print (size)

def b():
    size = 20
    a(locals())
</code>```

So, the added line (size = 20) in a() makes size be an actual local variable without the needing for exec, being python3 compatible and without the optimization drawback.

And how could that be useful???

Well, with that we can implement something like def f(x, *args, y=10) in python2 as that raises a syntax error in python2 but just works in python3:

```<code>def f(x, *args, **kwargs):
   y = 10
   locals().update(kwargs)
   print (x, y)
</code>```

The example above works in python2 and python3

Body:
Let's say I have this :

def a(dict):
  locals().update(dict)
  print size

def b():
  size = 20
  f(locals())

What do I have to do to access the size variable directly from the a function? I know of :

size = dict["size"]

but I think there should be a more direct way. I tried using locals().update(dict) but it didn't work. Is there a betteer way ?

Body:
I know, I know, the question is old and the accepted answer is already great.

Just adding two cents because it seems obvious but not mentioned: Make size local by assigning it a (default) value explicitly.

def a(dict):
    size = 20  # size default value <- quick (and dirty?) fix
    locals().update(dict)
    print (size)

def b():
    size = 20
    a(locals())

So, the added line (size = 20) in a() makes size be an actual local variable without the needing for exec, being python3 compatible and without the optimization drawback.

And how could that be useful???

Well, with that we can implement something like def f(x, *args, y=10) in python2 as that raises a syntax error in python2 but just works in python3:

def f(x, *args, **kwargs):
   y = 10
   locals().update(kwargs)
   print (x, y)

The example above works in python2 and python3


问:
Jupyter notebook: How to save a copy of a notebook to a different directory
Is it possible to save a copy of a Jupyter notebook in a different directory?

My scenario is as such: I have jupyterhub set up using the docker spawner to create jupyter containers for users. I want all of these users to have access to a shared notebook, which contains a template for certain types of work. This notebook is served via a read-only volume mount into a /shared directory under /work. Users should then be able to modify and save a copy into the parent directory, to which they have access. However, the 'make a copy' function seems to only want to make a copy in the same directory, which is of course read only. Is there a way to change this functionality?

Alternate solutions also welcome!

(For reference, this is using the r-notebook kernel, but I doubt that makes a difference)

答:
You can use the nbexamples extension

It accomplishes the same task.

You can specify the reviewed directory of nbexamples as your shared read-only directory.

Users will be able to fetch a copy and the copy will get stored inside home directory of user.


问:
Firebase Notification from Android App
I have already read firebase documentation many times, but it does not seem very clear to me.
It's 8 days of work that I can not do this ..

All documentation consists of links that say "go here", "go there", but I can not find anywhere how to send notifications from my application.

The documentation says to make requests to the html-xmpp server, but how?

I also tried with the "cloud functions", I can send notifications, but I can only if I insert the URL in the browser, and with a fixed title and text, in the code of the function.

I apologize for my poor English.
I hope someone can help me. Thank you.

答:
If you will use topic for push, you have to subscribetopic to android app. Call following call in your activity.

```<code>FirebaseMessaging.getInstance().subscribeToTopic("yourtopic");
</code>```

And send push message from fcm console with your topicname.

Title: Firebase Notification from Android App

Body:
If you will use topic for push, you have to subscribetopic to android app. Call following call in your activity.

FirebaseMessaging.getInstance().subscribeToTopic("yourtopic");

And send push message from fcm console with your topicname.