问:
Rewrite rule for opening a different page
I'm stuck with some .htaccess rules.

I've got the page /module/slug. I want, when I type slug to see content of /module/slug/ but not redirect to this page. Is it possible? I've tried this rule, but had no luck:

```<code>RewriteRule ^slug/$ /module/slug/ [L]
</code>```

My .htaccess content:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteRule ^calculator/$ /sample-page/ [R=301,L]
</IfModule>

# END WordPress
</code>```

答:
That happens because you don't tell Apache to redirect (R=301).

Add the redirect flag R, and it should work. Also make sure that:

You have set the RewriteBase correctly.

There are not any other rules earlier in the file that match the same URL.

.

```<code>RewriteEngine On
RewriteBase /

RewriteRule ^slug/$ /module/slug/ [R=301,L]
</code>```

Body:
I'm stuck with some .htaccess rules.

I've got the page /module/slug. I want, when I type slug to see content of /module/slug/ but not redirect to this page. Is it possible? I've tried this rule, but had no luck:

RewriteRule ^slug/$ /module/slug/ [L]

My .htaccess content:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteRule ^calculator/$ /sample-page/ [R=301,L]
</IfModule>

# END WordPress

Body:
That happens because you don't tell Apache to redirect (R=301).

Add the redirect flag R, and it should work. Also make sure that:

You have set the RewriteBase correctly.

There are not any other rules earlier in the file that match the same URL.

.

RewriteEngine On
RewriteBase /

RewriteRule ^slug/$ /module/slug/ [R=301,L]

OwnerDisplayName: toscho


来源: stackexchange

问:
First element of NSDictionary is <null> instead of 1
Via Firebase I get data out of Database, see the data on picture

Edited: When I print the snapshot.value like here:

```<code>DBProvider.Instance.dbRef.child("driverLocations").observeSingleEvent(of: .value, with: { (snapshot) in
    print(snapshot.value!)
   }
}
</code>```

I get:

```<code>(
"<null>",
    {
    driverName = chauffeur1;
    latitude = "37.33756603";
    longitude = "-122.04120235";
  }
)
</code>```

Where  stands, It should be 1. Does anybody know this problem?

It only happens when I use 1, when I use 2 or other numbers, I don't get the
I'll be glad to know :)

答: I solved the  problem by using numbers as 01 - 02 - 03 instead of 1 - 2- -3. This solved the problem, really weird workingaround tho..</p>

ContentLicense: CC BY-SA 3.0

Body:
Via Firebase I get data out of Database, see the data on picture

Edited: When I print the snapshot.value like here:

DBProvider.Instance.dbRef.child("driverLocations").observeSingleEvent(of: .value, with: { (snapshot) in
    print(snapshot.value!)
   }
}

I get:

(
"<null>",
    {
    driverName = chauffeur1;
    latitude = "37.33756603";
    longitude = "-122.04120235";
  }
)

Where  stands, It should be 1. Does anybody know this problem?

It only happens when I use 1, when I use 2 or other numbers, I don't get the
I'll be glad to know :)


问:
Golang: map to struct
For some reason (fixed-length data file parsing), I've got a map and I want the elements of the map being saved in a struct.

Let's say:

```<code>type Point struct {X, Y int}
point := make(map[string]int)

point["X"] = 15
point["Y"] = 13

p := Point{point} // doesn't work
</code>```

How do I do that? Or have I taken the wrong path?

答:
If the efficiency is not so important, you can marshal the map into JSON bytes and unmarshal it back to a struct.

```<code>import "encoding/json"

type Point struct {X, Y int}

point := make(map[string]int)
point["X"] = 15
point["Y"] = 13

bytes, err := json.Marshal(point)
var p Point
err = json.Unmarshal(bytes, &p)
</code>```

This maks the code easier to be modified when the struct contains a lot of fields.

Title: Golang: map to struct

Body:
For some reason (fixed-length data file parsing), I've got a map and I want the elements of the map being saved in a struct.

Let's say:

type Point struct {X, Y int}
point := make(map[string]int)

point["X"] = 15
point["Y"] = 13

p := Point{point} // doesn't work

How do I do that? Or have I taken the wrong path?

Body:
If the efficiency is not so important, you can marshal the map into JSON bytes and unmarshal it back to a struct.

import "encoding/json"

type Point struct {X, Y int}

point := make(map[string]int)
point["X"] = 15
point["Y"] = 13

bytes, err := json.Marshal(point)
var p Point
err = json.Unmarshal(bytes, &p)

This maks the code easier to be modified when the struct contains a lot of fields.


问:
Create a binary tree from a sorted array list
I need to program a Huffman compression for Text for an university assignment.
The exercise is split in to multiple points, and one of them is to create a binary tree from a given sorted arrayList which is of type TreeNode, this class looks like this (I removed the method boddies):

```<code>public class TreeNode implements Comparable<TreeNode>, Serializable {

    private byte value;

    private int frequency;

    private TreeNode left, right;

    /** Creates new TreeNode .. must get initialized with value */
    public TreeNode(byte value) {
        this(value, 0, null, null);
    }

    /** Creates new TreeNode with full init */
    public TreeNode(byte value, int frequency, TreeNode left, TreeNode right) {
        this.value = value;
        this.frequency = frequency;
        this.left = left;
        this.right = right;
    public void incFrequency()
    public int getFreq()
    public Byte getValue()
    public TreeNode getLeft()
    public TreeNode getRight()
    public boolean isLeaf()
    public int getSubTreeSize()
    public void toHeap(byte[] heap, int myIndex)
    public void initLookup(long myCode, int myDepth, Map<Byte, BitCode> lookupTable)
    @Override
    public int compareTo(TreeNode o)
    @Override
    public String toString()
    public void printSubTree(PrintStream out, int tabs)
    public void write(BitStream bs)
    public static TreeNode read(BitStream bs)

}
</code>```

I need to create a binary tree from an arrayList of type TreeNode, the arrayList is sorted by value so I can assume that the element with the smalles value is at index position 0.
The tree has to fulfill one important condition:
The element with the next bigger value needs to be appended on the left, and the element with an even bigger value needs to be appended to the right (the tree will be builded always to the right).

My attemp to approach this problem was to iterate over the list, getting the item, and then appending each item with an odd index to the left leave of the previous node and each item with an even index to the right leave.

Is there a more elegant way to approach this?
(I dont ask you to do the homework for me, but I could need some ideas)

EDIT:
I need to keep the SortedList, since it is a part of the exercise specification

答:
Only for the sake of helping you, you could think along the following lines:

select the middle element as the root node

split the array list into two - left starting from 0 to mid-1, and right starting from mid+1 to last

Recursively repeat step 1 till there is only one element left in the array.

Return that element when only one is left.

Editing my answer as i didn't understand the requirements properly initially.

First Edit -
You could do something like this -
0. If no element, return
1. make first element your root.
2. make next element if it exists as the left child.
3. recursively call the function making its result the right child.

Body:
I need to program a Huffman compression for Text for an university assignment.
The exercise is split in to multiple points, and one of them is to create a binary tree from a given sorted arrayList which is of type TreeNode, this class looks like this (I removed the method boddies):

public class TreeNode implements Comparable<TreeNode>, Serializable {

    private byte value;

    private int frequency;

    private TreeNode left, right;

    /** Creates new TreeNode .. must get initialized with value */
    public TreeNode(byte value) {
        this(value, 0, null, null);
    }

    /** Creates new TreeNode with full init */
    public TreeNode(byte value, int frequency, TreeNode left, TreeNode right) {
        this.value = value;
        this.frequency = frequency;
        this.left = left;
        this.right = right;
    public void incFrequency()
    public int getFreq()
    public Byte getValue()
    public TreeNode getLeft()
    public TreeNode getRight()
    public boolean isLeaf()
    public int getSubTreeSize()
    public void toHeap(byte[] heap, int myIndex)
    public void initLookup(long myCode, int myDepth, Map<Byte, BitCode> lookupTable)
    @Override
    public int compareTo(TreeNode o)
    @Override
    public String toString()
    public void printSubTree(PrintStream out, int tabs)
    public void write(BitStream bs)
    public static TreeNode read(BitStream bs)

}

I need to create a binary tree from an arrayList of type TreeNode, the arrayList is sorted by value so I can assume that the element with the smalles value is at index position 0.
The tree has to fulfill one important condition:
The element with the next bigger value needs to be appended on the left, and the element with an even bigger value needs to be appended to the right (the tree will be builded always to the right).

My attemp to approach this problem was to iterate over the list, getting the item, and then appending each item with an odd index to the left leave of the previous node and each item with an even index to the right leave.

Is there a more elegant way to approach this?
(I dont ask you to do the homework for me, but I could need some ideas)

EDIT:
I need to keep the SortedList, since it is a part of the exercise specification


问:
Non-empty validation for String datatype element depending upon other element value - XSD
I want to apply non-empty validation for String datatype element and this is depend on other element value. I know this can be done with assertion but I dont know how to write Xpath expression for same.

This is extension of Optional/mandatory element based on non-sibling element value using xsd:assert? question.

Here I want validation that If 'Msgtyp' value is '103' then 'LclTpInf' should be non-empty or null and for other 'Msgtype' it can be empty or null.

Updated:

XSD:

```<code>   <?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
   vc:minVersion="1.1">

<xs:element name="root" type="root"></xs:element>

<xs:complexType name="root">
<xs:sequence>
    <xs:element name="P1Message"
        type="p1Message">
    </xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="p1Message">
<xs:sequence>
    <xs:element name="Hdr" type="hdr"></xs:element>
    <xs:element name="Inf" type="inf"></xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="hdr">
<xs:sequence>
    <xs:element name="I1Agt" type="i1Agt"></xs:element>
    <xs:element name="SequenceNum" type="xs:string"></xs:element>
    <xs:element name="SessionNum" type="xs:string"></xs:element>
    <xs:element name="MsgTyp" type="xs:string"></xs:element>
    <xs:element name="IntComment" type="xs:string"></xs:element>
</xs:sequence>
<xs:assert test="LclInstrm or not(MsgTyp = '103')"/>
</xs:complexType>

<xs:complexType name="i1Agt">
<xs:sequence>
    <xs:element name="FinInstnId" type="finInstnId"></xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="finInstnId">
<xs:sequence>
    <xs:element name="B1" type="xs:string"></xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="inf">
<xs:sequence>
    <xs:element name="PmtTpInf" type="pmtTpInf"></xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="pmtTpInf">
<xs:sequence>
    <xs:element name="LclInstrm" type="xs:string" minOccurs="0" maxOccurs="1"></xs:element>
    <xs:element name="Svc" type="svc"></xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="svc">
<xs:sequence>
    <xs:element name="Cd" type="xs:string"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>
</code>```

XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<root>
<P1Message>
<Hdr>
<I1Agt>
<FinInstnId>
  <B1>str1234</B1>
</FinInstnId>
</I1Agt>
<SequenceNum>str1234</SequenceNum>
<SessionNum>str1234</SessionNum>
<MsgTyp>123</MsgTyp>
<IntComment>str1234</IntComment>
</Hdr>
<Inf>
<PmtTpInf>
<LclInstrm>str1234</LclInstrm>
<Svc>
  <Cd>str1234</Cd>
</Svc>
</PmtTpInf>
</Inf>
</code>```

答:
After googling I am able to resolve this issue. Below is solution for same, hope it would be helpful for someone:</p>

```<code><xs:assert test="not(Hdr/MsgTyp = '103') or not(Inf/PmtTpInf/LclInstrm eq '')"/>
</code>```

Body:
I want to apply non-empty validation for String datatype element and this is depend on other element value. I know this can be done with assertion but I dont know how to write Xpath expression for same.

This is extension of Optional/mandatory element based on non-sibling element value using xsd:assert? question.

Here I want validation that If 'Msgtyp' value is '103' then 'LclTpInf' should be non-empty or null and for other 'Msgtype' it can be empty or null.

Updated:

XSD:

   <?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
   vc:minVersion="1.1">

<xs:element name="root" type="root"></xs:element>

<xs:complexType name="root">
<xs:sequence>
    <xs:element name="P1Message"
        type="p1Message">
    </xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="p1Message">
<xs:sequence>
    <xs:element name="Hdr" type="hdr"></xs:element>
    <xs:element name="Inf" type="inf"></xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="hdr">
<xs:sequence>
    <xs:element name="I1Agt" type="i1Agt"></xs:element>
    <xs:element name="SequenceNum" type="xs:string"></xs:element>
    <xs:element name="SessionNum" type="xs:string"></xs:element>
    <xs:element name="MsgTyp" type="xs:string"></xs:element>
    <xs:element name="IntComment" type="xs:string"></xs:element>
</xs:sequence>
<xs:assert test="LclInstrm or not(MsgTyp = '103')"/>
</xs:complexType>

<xs:complexType name="i1Agt">
<xs:sequence>
    <xs:element name="FinInstnId" type="finInstnId"></xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="finInstnId">
<xs:sequence>
    <xs:element name="B1" type="xs:string"></xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="inf">
<xs:sequence>
    <xs:element name="PmtTpInf" type="pmtTpInf"></xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="pmtTpInf">
<xs:sequence>
    <xs:element name="LclInstrm" type="xs:string" minOccurs="0" maxOccurs="1"></xs:element>
    <xs:element name="Svc" type="svc"></xs:element>
</xs:sequence>
</xs:complexType>

<xs:complexType name="svc">
<xs:sequence>
    <xs:element name="Cd" type="xs:string"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>

XML:

<?xml version="1.0" encoding="utf-8"?>
<root>
<P1Message>
<Hdr>
<I1Agt>
<FinInstnId>
  <B1>str1234</B1>
</FinInstnId>
</I1Agt>
<SequenceNum>str1234</SequenceNum>
<SessionNum>str1234</SessionNum>
<MsgTyp>123</MsgTyp>
<IntComment>str1234</IntComment>
</Hdr>
<Inf>
<PmtTpInf>
<LclInstrm>str1234</LclInstrm>
<Svc>
  <Cd>str1234</Cd>
</Svc>
</PmtTpInf>
</Inf>

Body:
After googling I am able to resolve this issue. Below is solution for same, hope it would be helpful for someone:

<xs:assert test="not(Hdr/MsgTyp = '103') or not(Inf/PmtTpInf/LclInstrm eq '')"/>


问:
Problems with Octave impz function, in the moment I plot results
I'm very new to the Matlab and Octave "World". I've been suffering for some hours to make a simple script run. Problem is, my teacher wrote it on Matlab, and I can't find a way to make it work on Octave. The script finds the impulse answer for the system and plots the curve. Here it is:

```<code>b = [1]; a = [1, -1, 0.9]; n = [0:100];
h = impz(b,a,n);
stem(n,h);
subplot(1,1,1);
title('Impulse Response'); xlabel('n'); ylabel('h(n)');
</code>```

The error is:

error: stem: inconsistent sizes for X and Y error: called from
      stem>check_stem_arg at line 276 column 11
      stem at line 37 column 40
      stem at line 127 column 8
      questao6_lab2 at line 4 column 1

I understand it is because of the axis difference. Though, I don't understand why octave gives only a single value for h. The function Impz should describe a curve all along thee values of n, but i doesn't.

Thanks

答:
The issue comes from impz returning a scalar in this case

```<code>octave-gui:26> h = impz (1, [1, -1, 0.9], 0:100)
h =  1
</code>```

while you are expecting a vector with 100 elements (which is what Matlab does).  In Matlab, the third argument (N) can be a scalar stating the number of samples of the impulse response, or a vector specifying the values where to compute the impulse response.  In Octave, you can only specify a number of samples.  So do this instead:

```<code>h = impz (1, [1, -1, 0.9], 101);
</code>```

In addition, it seems that Octave returns a row vector instead of a column vector so do this:

```<code>h = impz (1, [1, -1, 0.9], 101)(:);
</code>```

The reason why I am using (:) instead of .' (transpose) is so that it continues working in the next version of the signal package where this will be fixed.  Alternatively, run which impz to find where is the source for Octave's impz function, and fix it there for yourself now.

Body:
I'm very new to the Matlab and Octave "World". I've been suffering for some hours to make a simple script run. Problem is, my teacher wrote it on Matlab, and I can't find a way to make it work on Octave. The script finds the impulse answer for the system and plots the curve. Here it is:

b = [1]; a = [1, -1, 0.9]; n = [0:100];
h = impz(b,a,n);
stem(n,h);
subplot(1,1,1);
title('Impulse Response'); xlabel('n'); ylabel('h(n)');

The error is:

error: stem: inconsistent sizes for X and Y error: called from
      stem>check_stem_arg at line 276 column 11
      stem at line 37 column 40
      stem at line 127 column 8
      questao6_lab2 at line 4 column 1

I understand it is because of the axis difference. Though, I don't understand why octave gives only a single value for h. The function Impz should describe a curve all along thee values of n, but i doesn't.

Thanks

Body:
The issue comes from impz returning a scalar in this case

octave-gui:26> h = impz (1, [1, -1, 0.9], 0:100)
h =  1

while you are expecting a vector with 100 elements (which is what Matlab does).  In Matlab, the third argument (N) can be a scalar stating the number of samples of the impulse response, or a vector specifying the values where to compute the impulse response.  In Octave, you can only specify a number of samples.  So do this instead:

h = impz (1, [1, -1, 0.9], 101);

In addition, it seems that Octave returns a row vector instead of a column vector so do this:

h = impz (1, [1, -1, 0.9], 101)(:);

The reason why I am using (:) instead of .' (transpose) is so that it continues working in the next version of the signal package where this will be fixed.  Alternatively, run which impz to find where is the source for Octave's impz function, and fix it there for yourself now.


问:
How to update conteneditable div without changing cursor position
Here is the javascript code I am using and I want to highlighted the characters after 255 and should be shown in another div with diff color

```<code>$( "#testdiv" ).keyup(function() {
   if($("#testdiv").text().length>255)
   {
   var text = $("#info").text()
   $("#testdiv").text("")
   $("#testdiv").append(text.slice(0,255)+"<div>"+text.slice(255)+"</div>")
   }
});
</code>```

Here is the HTML code,

```<code><div id="testdiv"  contenteditable="true">
</div>
</code>```

With this code the problem I am facing is

It is updating the cursor position to the beginning of text when I try to update text after 255 characters.

When there is less than 255 character inside div and I press enter then every time it appends a div enclosing the
 tag.

答:
$("#testdiv").on('keyup', function() {
  if ($("#testdiv").text().length > 255) {
    var text = $("#testdiv").text()
    $("#testdiv").text("");
    $("#testdiv").html(text.slice(0, 255) + "
" + text.slice(255) + "
");

    var preHtml = $("#testdiv").html();
    $("#testdiv").html(preHtml);

    $("#testdiv").focus();
    placeCaretAtEnd(document.getElementById("testdiv"));

  }
});

function placeCaretAtEnd(el) {
  el.focus();
  if (typeof window.getSelection != "undefined" &&
    typeof document.createRange != "undefined") {
    var range = document.createRange();
    range.selectNodeContents(el);
    range.collapse(false);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (typeof document.body.createTextRange != "undefined") {
    var textRange = document.body.createTextRange();
    textRange.moveToElementText(el);
    textRange.collapse(false);
    textRange.select();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="testdiv" contenteditable="true">sample text
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script></code>```

Body:
Here is the javascript code I am using and I want to highlighted the characters after 255 and should be shown in another div with diff color

$( "#testdiv" ).keyup(function() {
   if($("#testdiv").text().length>255)
   {
   var text = $("#info").text()
   $("#testdiv").text("")
   $("#testdiv").append(text.slice(0,255)+"
"+text.slice(255)+"
")
   }
});

Here is the HTML code,

With this code the problem I am facing is

It is updating the cursor position to the beginning of text when I try to update text after 255 characters.

When there is less than 255 character inside div and I press enter then every time it appends a div enclosing the
 tag.

Body:
$("#testdiv").on('keyup', function() {
  if ($("#testdiv").text().length > 255) {
    var text = $("#testdiv").text()
    $("#testdiv").text("");
    $("#testdiv").html(text.slice(0, 255) + "<div style='color:red'>" + text.slice(255) + "</div>");

    var preHtml = $("#testdiv").html();
    $("#testdiv").html(preHtml);

    $("#testdiv").focus();
    placeCaretAtEnd(document.getElementById("testdiv"));

  }
});

function placeCaretAtEnd(el) {
  el.focus();
  if (typeof window.getSelection != "undefined" &&
    typeof document.createRange != "undefined") {
    var range = document.createRange();
    range.selectNodeContents(el);
    range.collapse(false);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (typeof document.body.createTextRange != "undefined") {
    var textRange = document.body.createTextRange();
    textRange.moveToElementText(el);
    textRange.collapse(false);
    textRange.select();
  }
}

<div id="testdiv" contenteditable="true">sample text
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>


问:
Photoshop Batch Action Save for Web and Devices
I created an Action in Photoshop CS4. It's something like this:

Open Document

Change Canvas Size

Save for Web & Devices

Close Document

Now, the "Save for Web & Devices" does all nice stuff, including saving it with a specific name to a specific folder.
Somehow, when I try to Batch this Action, I'm not able to tell Photoshop NOT to use the name (and probably location) as defined in the "Save for Web & Devices". As a result, Photoshop keeps on overwriting the output previous files in the batch, leaving me with only the transformed rendition of the last file in the batch.

I tried to select the 'override Save As' checkbox in the batch, but that doesn't seem to influence the behavior of the Save for Web & Devices part of the Action.

Can anyone help me?

答:
Make sure you dont have any forward/backslash in the file name. I am assuming you have a slash in the file name and thats what is preventing the desired result.

Regards!

Bharat Mudgal

ContentLicense: CC BY-SA 2.5


问:
Highstock Highchart empty space between chart and scrollbar

I am having an issue with a chart as seen from image above.

For some reason there is an empty space between chart and scrollbar.

Chart does fill the area completely if the scrollbar is turned off.

How do I position it correctly?

Removing empty space or making chart to use all available height are both fine solutions for me.

Just in case, the chart's parameters are:

```<code>        chart: {
            borderWidth: 0,
            type: 'area',
            margin: [0, 0, 0, 0],
            spacingBottom: 0,
            width: 250,
            height: 60,
            style: {
                overflow: 'visible'
            },
            skipClone: true,
        },

        xAxis: {
            labels: {
                enabled: false
            },
            title: {
                text: null
            },
            startOnTick: false,
            endOnTick: false,
            tickPositions: [],
            tickInterval: 1,
            max: 16
        },

        scrollbar: {
            enabled: true,
            height: 10
        },

        yAxis: {
            minorTickInterval: 1,
            endOnTick: false,
            startOnTick: false,
            labels: {
                enabled: false
            },
            title: {
                text: null
            },
            tickPositions: [0],
            max: 7,
            tickInterval: 1
        },

        title: {
            text: null
        },

        credits: {
            enabled: false
        },

        legend: {
            enabled: false
        },

        plotOptions: {
            series: {
                animation: {
                    duration: 2000
                },
                lineWidth: 1,
                shadow: false,
                states: {
                    hover: {
                        lineWidth: 1
                    }
                },
                marker: {
                    radius: 2,
                    states: {
                        hover: {
                            radius: 4                                                        }
                    }
                },
                fillOpacity: 0.25
            },
        },

        series: [{
            data: [1,1,2,1,3,1,4,1,5,1,6,1,7,1,8,1,9,1,10,1,11,1,12,1,13,1,14,1,15,1,16,1]
        }]
</code>```

答:
Decrease navigator.margin property.

```<code>navigator: {
  enabled: false,
  margin: 0
},
</code>```

example: http://jsfiddle.net/tL75q6wm/

Body:
I am having an issue with a chart as seen from image above.

For some reason there is an empty space between chart and scrollbar.

Chart does fill the area completely if the scrollbar is turned off.

How do I position it correctly?

Removing empty space or making chart to use all available height are both fine solutions for me.

Just in case, the chart's parameters are:

        chart: {
            borderWidth: 0,
            type: 'area',
            margin: [0, 0, 0, 0],
            spacingBottom: 0,
            width: 250,
            height: 60,
            style: {
                overflow: 'visible'
            },
            skipClone: true,
        },

        xAxis: {
            labels: {
                enabled: false
            },
            title: {
                text: null
            },
            startOnTick: false,
            endOnTick: false,
            tickPositions: [],
            tickInterval: 1,
            max: 16
        },

        scrollbar: {
            enabled: true,
            height: 10
        },

        yAxis: {
            minorTickInterval: 1,
            endOnTick: false,
            startOnTick: false,
            labels: {
                enabled: false
            },
            title: {
                text: null
            },
            tickPositions: [0],
            max: 7,
            tickInterval: 1
        },

        title: {
            text: null
        },

        credits: {
            enabled: false
        },

        legend: {
            enabled: false
        },

        plotOptions: {
            series: {
                animation: {
                    duration: 2000
                },
                lineWidth: 1,
                shadow: false,
                states: {
                    hover: {
                        lineWidth: 1
                    }
                },
                marker: {
                    radius: 2,
                    states: {
                        hover: {
                            radius: 4                                                        }
                    }
                },
                fillOpacity: 0.25
            },
        },

        series: [{
            data: [1,1,2,1,3,1,4,1,5,1,6,1,7,1,8,1,9,1,10,1,11,1,12,1,13,1,14,1,15,1,16,1]
        }]

Body:
Decrease navigator.margin property.

navigator: {
  enabled: false,
  margin: 0
},

example: http://jsfiddle.net/tL75q6wm/


问:
WCF equivalent of ServiceDescriptionReflector
For an asmx webservice ServiceDescriptionReflector can be used to generate a schema programmatically for message validation.

Is their a WCF equivalent for runtime schema generation?

答:
If you want to customize the WSDL generation process, implement a Contract or Endpoint behavior and inject a custom IWsdlExportExtension implementation.

Here's an older sample I wrote on that a few years ago.


问:
pass a db connexion instance to other classes php
i am trying to make a registration system using PHP OOP but im getting this errors when i excute it

Notice: Undefined variable: connect in C:\wamp64\www\news\classes\user.php on line 14

Fatal error: Call to a member function prepare() on null in C:\wamp64\www\news\classes\user.php on line 14

i beleive that my problem is that my calsse can't get the db connection instance even im passing it on intiation. i have 2 classes and a registration page
my first class is dbconnect.php

```<code><?php

    include "./config.php";

    class dbconnect{

        public  function __construct(){
            try {
                $conect = new PDO('mysql:host='.SERVER.'; dbname='.DATABASE, USERNAME, PASSWORD);
                $conect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conect;

            }
        catch(PDOException $e)
                {
                echo "Connection failed: " . $e->getMessage();
            }
        }

    }

?>
</code>```

my second class is user.php

```<code><?php

    class user{
        public  $username;
        public  $connect;

            function __construct($username,$connect){
                $this->username=$username;
                $this->connect=$connect;
            }

            protected function user_exist(){
                $request="SELECT * FROM `users` where username='".$this->username."'";
                $sql=$connect->prepare($request);
                $sql->execute();
                $results = $sql->fetch(PDO::FETCH_ASSOC);

                if(is_array($results)){
                    //echo "utilisateur exist";
                    return true;
                }
                else{
                    //echo "utilisateur n'existe pas";
                    return false;
                }
            }
            public function register($firstname,$lastname,$email,$user,$password){
                if(!($this->user_exist())){
                    $request="INSERT INTO USERS (nom,prenom,email,user,pass,role,statut,date ) VALUES (:firstname, :lastname, :email, :username, :password, :role,:staut, :now())";
                    $sql = $connect->prepare($request);
                    $sql->bindParam(':fistname', $firstname);
                    $sql->bindParam(':lastname', $lastname);
                    $sql->bindParam(':email', $email);
                    $sql->bindParam(':username', $username);
                    $sql->bindParam(':password', $password);
                    $sql->bindParam(':role', 'subscriber');
                    $sql->bindParam(':statut', 'waiting for validation');
                    //$sql->bindParam(':date', $date);
                    try{
                        $sql->execute();
                    }
                    catch(Exception $e){
                        if ($e->getCode() == 1062) {
                            echo $e;
                        } else {
                            throw $e;
                        }
                    }

                }
            }

    }

?>
</code>```

and then my registration page

```<code><?php
    include "classes/dbconnect.php";
    include "classes/user.php";

    if((isset($_POST["submit"]))    and $_POST["verificaation"]=="submit1"){
        $nom        =   $_POST["nom"];
        $prenom     =   $_POST["prenom"];
        $email      =   $_POST["email"];
        $username   =   $_POST["username"];
        $pass       =   $_POST["password"];
        $passver    =   $_POST["passver"];
        $conect=new dbconnect();

        $user= new user($username,$conect->connect);
        $msg=$user->register($nom,$prenom,$email,$user,$pass);
        print_r ($conect);

    }

?>
<form method="post" action="register.php">
<label>Nom</label>
<input type="text" name="nom"/><br />
<label>Prenom</label>
<input type="text" name="prenom"/><br />
<label>Email</label>
<input type="email" name="email"/><br />
<label>Nom d'utilisateur</label>
<input type="text" name="username" /><br />
<label>Mot de passe</label>
<input type="password" name="password" /><br />
<label>Recrivez le mot de passe</label>
<input type="password" name="passver"/><br />
<input type="submit" name="submit" value="submit" /><br />
<input type="hidden" name="verificaation" value="submit1" />

</form>
</code>```

答:
on User.php, Instead of using :

```<code>$sql=$connect->prepare($request);
</code>```

Use :

```<code>$sql=$this->connect->prepare($request);
</code>```

Also, Instead of using :

```<code>$sql = $connect->prepare($request);
</code>```

Use :

```<code>$sql = $this->connect->prepare($request);
</code>```

Body:
i am trying to make a registration system using PHP OOP but im getting this errors when i excute it

Notice: Undefined variable: connect in C:\wamp64\www\news\classes\user.php on line 14

Fatal error: Call to a member function prepare() on null in C:\wamp64\www\news\classes\user.php on line 14

i beleive that my problem is that my calsse can't get the db connection instance even im passing it on intiation. i have 2 classes and a registration page
my first class is dbconnect.php

<?php

    include "./config.php";

    class dbconnect{

        public  function __construct(){
            try {
                $conect = new PDO('mysql:host='.SERVER.'; dbname='.DATABASE, USERNAME, PASSWORD);
                $conect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conect;

            }
        catch(PDOException $e)
                {
                echo "Connection failed: " . $e->getMessage();
            }
        }

    }

?>

my second class is user.php

<?php

    class user{
        public  $username;
        public  $connect;

            function __construct($username,$connect){
                $this->username=$username;
                $this->connect=$connect;
            }

            protected function user_exist(){
                $request="SELECT * FROM `users` where username='".$this->username."'";
                $sql=$connect->prepare($request);
                $sql->execute();
                $results = $sql->fetch(PDO::FETCH_ASSOC);

                if(is_array($results)){
                    //echo "utilisateur exist";
                    return true;
                }
                else{
                    //echo "utilisateur n'existe pas";
                    return false;
                }
            }
            public function register($firstname,$lastname,$email,$user,$password){
                if(!($this->user_exist())){
                    $request="INSERT INTO USERS (nom,prenom,email,user,pass,role,statut,date ) VALUES (:firstname, :lastname, :email, :username, :password, :role,:staut, :now())";
                    $sql = $connect->prepare($request);
                    $sql->bindParam(':fistname', $firstname);
                    $sql->bindParam(':lastname', $lastname);
                    $sql->bindParam(':email', $email);
                    $sql->bindParam(':username', $username);
                    $sql->bindParam(':password', $password);
                    $sql->bindParam(':role', 'subscriber');
                    $sql->bindParam(':statut', 'waiting for validation');
                    //$sql->bindParam(':date', $date);
                    try{
                        $sql->execute();
                    }
                    catch(Exception $e){
                        if ($e->getCode() == 1062) {
                            echo $e;
                        } else {
                            throw $e;
                        }
                    }

                }
            }

    }

?>

and then my registration page

<?php
    include "classes/dbconnect.php";
    include "classes/user.php";

    if((isset($_POST["submit"]))    and $_POST["verificaation"]=="submit1"){
        $nom        =   $_POST["nom"];
        $prenom     =   $_POST["prenom"];
        $email      =   $_POST["email"];
        $username   =   $_POST["username"];
        $pass       =   $_POST["password"];
        $passver    =   $_POST["passver"];
        $conect=new dbconnect();

        $user= new user($username,$conect->connect);
        $msg=$user->register($nom,$prenom,$email,$user,$pass);
        print_r ($conect);

    }

?>
<form method="post" action="register.php">
Nom
<input type="text" name="nom"/>

Prenom
<input type="text" name="prenom"/>

Email
<input type="email" name="email"/>

Nom d'utilisateur
<input type="text" name="username" />

Mot de passe
<input type="password" name="password" />

Recrivez le mot de passe
<input type="password" name="passver"/>

<input type="submit" name="submit" value="submit" />

<input type="hidden" name="verificaation" value="submit1" />

</form>

Body:
on User.php, Instead of using :

$sql=$connect->prepare($request);

Use :

$sql=$this->connect->prepare($request);

Also, Instead of using :

$sql = $connect->prepare($request);

Use :

$sql = $this->connect->prepare($request);


问:
How to not restart IIS every time I make changes to code?
I have my web application running. And every time I change some little peace of logic code I need to stop the app and wait for IIS to restart entirely.

Somewhere in the web I saw some guy saying that one of cool features of MVC5 (or maybe MVC6 on ASP.NET Core) that you can make changes "on the fly".

So can I not stop and restart IIS every time, or I just misunderstood something?

答:
Actually, you don't need to restart IIS after each deploy. Whenever a change is detected in DLLs, the app (not IIS) will recycle and re-load the new DLLs. It just impacts that particular application and reloads the app domain.

Also, editing the web.config in a web application will also recycle the app.

You can read more in this article.


问:
How to load comma delimited file with comma as a value to Hive
I'm getting comma in a field in a comma separated file. Kindly help me to load the file to Hive.
E.g :

```<code>Name,Description,Date
Gupta,Shradha,she is crazy,30/04/2017
Lokesh Ch,he is good,30/04/2017
</code>```

Gupta and Shradha shoud be fit under "Name" field.

Kindly help.

答:
Place all values inside double quotes(like "Gupta,Shradha","she is crazy","30/04/2017") and use OpenCSVSerde to parse the data file

include below properties in create table statement

```<code>ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
   "separatorChar" = ",",
   "quoteChar"     = "\""
)
</code>```

Body:
I'm getting comma in a field in a comma separated file. Kindly help me to load the file to Hive.
E.g :

Name,Description,Date
Gupta,Shradha,she is crazy,30/04/2017
Lokesh Ch,he is good,30/04/2017

Gupta and Shradha shoud be fit under "Name" field.

Kindly help.

Body:
Place all values inside double quotes(like "Gupta,Shradha","she is crazy","30/04/2017") and use OpenCSVSerde to parse the data file

include below properties in create table statement

ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
   "separatorChar" = ",",
   "quoteChar"     = "\""
)


问:
Fibonacci in Scheme
I am trying to understand recursion in Scheme and I have a hard time doing the dry run for it, for example a simple Fibonacci number problem. </p>

<p>Could someone break down the steps in which the additions take place, for me? </p>

```<code>(define (fib n)
  (if (<= n 2)
      1
      (+ (fib (- n 1)) (fib (- n 2)))))
</code>```

答:
This is a code that prints the fibonacci sequence members from 1 to n
each in a new line. Importnat to note, it's using two very simple helper functions. Hope this helps.</p>

```<code>;Prints to the screen all the member up to the nth member in the fibonaci sequence (define (fibo n)
 (let ((i 1))
  (if (= n 1)
      (display 1)
      (fiboHelp i n))))

;Helper function that presents Fibonaci sequence from bottom index i until upper index n
(define (fiboHelp i n)
  (if (= i n)
      (display(fiboMember i))
      (begin
        (display (fiboMember i))
        (newline)
        (fiboHelp (+ i 1)n))))

;Returns the nth member of the Fibonaci sequence
(define (fiboMember n)
  (if (<= n 2)
      (+ 1 0)
      (+ (fiboMember(- n 1))(fiboMember(- n 2)))))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Fibonacci in Scheme

Body:
I am trying to understand recursion in Scheme and I have a hard time doing the dry run for it, for example a simple Fibonacci number problem.

Could someone break down the steps in which the additions take place, for me?

(define (fib n)
  (if (<= n 2)
      1
      (+ (fib (- n 1)) (fib (- n 2)))))

Body:
This is a code that prints the fibonacci sequence members from 1 to n
each in a new line. Importnat to note, it's using two very simple helper functions. Hope this helps.

;Prints to the screen all the member up to the nth member in the fibonaci sequence (define (fibo n)
 (let ((i 1))
  (if (= n 1)
      (display 1)
      (fiboHelp i n))))

;Helper function that presents Fibonaci sequence from bottom index i until upper index n
(define (fiboHelp i n)
  (if (= i n)
      (display(fiboMember i))
      (begin
        (display (fiboMember i))
        (newline)
        (fiboHelp (+ i 1)n))))

;Returns the nth member of the Fibonaci sequence
(define (fiboMember n)
  (if (<= n 2)
      (+ 1 0)
      (+ (fiboMember(- n 1))(fiboMember(- n 2)))))


问:
dlopen library path syntax
I'm compiling the library for android (especially android M) and ı want to ask while I'm using dlopen(); function, what is the correct syntax of library path?

Which one is correct?

First one:

```<code>libcameraHandle = ::dlopen("/system/lib/libseccameraadaptor.so", RTLD_LAZY);
</code>```

so the path is: /system/lib/libseccameraadaptor.so

or Second one:

```<code>libcameraHandle = ::dlopen("libseccameraadaptor.so", RTLD_LAZY);
</code>```

so the path is libseccameraadaptor.so

I also found something that can be good info for this specific subject but couldn't understand well look into cool hacks/opengl section

答: The second syntax searches for libseccameraadaptor.so in standard paths and paths specified in LD_LIBRARY_PATH. For a standard library like this which will be in /system/lib forever it does not really make much difference. For anything else, the second call is probly more robust if library is ever moved to different place.

Title: dlopen library path syntax

Body:
I'm compiling the library for android (especially android M) and ı want to ask while I'm using dlopen(); function, what is the correct syntax of library path?

Which one is correct?

First one:

libcameraHandle = ::dlopen("/system/lib/libseccameraadaptor.so", RTLD_LAZY);

so the path is: /system/lib/libseccameraadaptor.so

or Second one:

libcameraHandle = ::dlopen("libseccameraadaptor.so", RTLD_LAZY);

so the path is libseccameraadaptor.so

I also found something that can be good info for this specific subject but couldn't understand well look into cool hacks/opengl section


问:
How to fetch the google plus contact list using firebase?
I want to try fetching the contact list of the Google plus using firebase but firebase login with Google demo example available but how I can fetch the contact list of the Google contacts with the help of the firebase? I am confused between Google plus SDK and firebase please any one help for this query.</p>

答:
I have created a Util class that handle google +</p>

```<code>public class GooglePlusUtil implements GoogleApiClient.OnConnectionFailedListener {

public static final int RC_SIGN_IN = 007;
public static final int G_LOGIN_CANCELLED = 12051;

private int userIdCounter = 0;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private FragmentActivity mFragmentActivity;
private GoogleResponse mResponseListener;

/**
 * Instantiates a new Google util.
 *
 * @param context
 * @param activity        the context
 * @param signInPresenter
 */
public GooglePlusUtil(Context context, FragmentActivity activity, SignInPresenter signInPresenter) {
    mContext = context;
    mFragmentActivity = activity;
    mResponseListener = signInPresenter;
    initGPlus();
}

private void initGPlus() {
    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    mGoogleApiClient = new GoogleApiClient.Builder(mContext)
            .enableAutoManage(mFragmentActivity, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
}

/**
 * Call G+ login activity.
 */
public void login() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    mFragmentActivity.startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Crashlytics.log(connectionResult.toString());
    Log.d("ConnectionResult", "G+ " + connectionResult.toString());
}

/**
 * Parse G+ response.
 *
 * @param accountsByType account number id
 * @param acct           G+ response.
 */
public void findAuth(Account[] accountsByType, GoogleSignInAccount acct) {
    matchAccountNumber(accountsByType, acct);
    new GoogleAsyncTask(accountsByType, acct).execute();
}

/**
 * userIdCounter Account Number
 *
 * @param accounts account number id
 * @param acct     G+ response.
 */
private void matchAccountNumber(Account[] accounts, GoogleSignInAccount acct) {
    for (int index = 0; index < accounts.length; index++) {
        if (accounts[index].name.equals(acct.getEmail())) {
            userIdCounter = index;
            break;
        }
    }
}

/**
 * Google login response.
 *
 * @param result G+ instance.
 */
public void handleSignInResult(GoogleSignInResult result) {
    if (result.isSuccess()) {
        GoogleSignInAccount acct = result.getSignInAccount();
        if (acct == null || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        findAuth(AccountManager.get(mContext).getAccountsByType("com.google"), acct);

    } else if (result.getStatus().getStatusCode() == G_LOGIN_CANCELLED) {
        ToastUtils.getInstance(mContext).showToast(mContext.getString(R.string.google_login_cancelled));
    } else {
        ToastUtils.getInstance(mContext).showToast(mContext.getString(R.string.message_not_able_to_login_via_google));
    }
}

public class GoogleAsyncTask extends AsyncTask<Void, Void, String> {
    private Account[] mAccountsByType;
    private GoogleSignInAccount mGoogleSignInAccount;

    /**
     * Instantiates a new Google async task.
     *
     * @param accountsByType
     * @param acct
     */
    public GoogleAsyncTask(Account[] accountsByType, GoogleSignInAccount acct) {
        mAccountsByType = accountsByType;
        mGoogleSignInAccount = acct;
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            return GoogleAuthUtil.getToken(mContext, mAccountsByType[userIdCounter], Constants.OAUTH_URL);
        } catch (UserRecoverableAuthException e) {
            Crashlytics.logException(e.getCause());
            AppLogger.e(e);
            mResponseListener.onTokenNotFound(e.getIntent(), RC_SIGN_IN);
        } catch (GoogleAuthException | IOException e) {
            Crashlytics.logException(e.getCause());
            AppLogger.e(e);
        }
        return "";
    }

    @Override
    protected void onPostExecute(String token) {
        IsAuthValidRequest isAuthValidRequest = new IsAuthValidRequest();
        isAuthValidRequest.setEmail(mGoogleSignInAccount.getEmail());
        isAuthValidRequest.setFirstName(mGoogleSignInAccount.getDisplayName());
        isAuthValidRequest.setLastName(mGoogleSignInAccount.getFamilyName());
        mResponseListener.onGoogleUserInfoAvailable(isAuthValidRequest, token);
    }
}

public interface GoogleResponse {

    /**
     * When user info and token found.
     *
     * @param isAuthValidRequest info instance.
     * @param token G+.
     */
    void onGoogleUserInfoAvailable(IsAuthValidRequest isAuthValidRequest, String token);

    /**
     * Invoke when auth token not found.
     *
     * @param intent      instance.
     * @param requestCode request code.
     */
    void onTokenNotFound(Intent intent, int requestCode);
}
}
</code>```

Body:
I have created a Util class that handle google +

public class GooglePlusUtil implements GoogleApiClient.OnConnectionFailedListener {

public static final int RC_SIGN_IN = 007;
public static final int G_LOGIN_CANCELLED = 12051;

private int userIdCounter = 0;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private FragmentActivity mFragmentActivity;
private GoogleResponse mResponseListener;

/**
 * Instantiates a new Google util.
 *
 * @param context
 * @param activity        the context
 * @param signInPresenter
 */
public GooglePlusUtil(Context context, FragmentActivity activity, SignInPresenter signInPresenter) {
    mContext = context;
    mFragmentActivity = activity;
    mResponseListener = signInPresenter;
    initGPlus();
}

private void initGPlus() {
    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    mGoogleApiClient = new GoogleApiClient.Builder(mContext)
            .enableAutoManage(mFragmentActivity, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
}

/**
 * Call G+ login activity.
 */
public void login() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    mFragmentActivity.startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Crashlytics.log(connectionResult.toString());
    Log.d("ConnectionResult", "G+ " + connectionResult.toString());
}

/**
 * Parse G+ response.
 *
 * @param accountsByType account number id
 * @param acct           G+ response.
 */
public void findAuth(Account[] accountsByType, GoogleSignInAccount acct) {
    matchAccountNumber(accountsByType, acct);
    new GoogleAsyncTask(accountsByType, acct).execute();
}

/**
 * userIdCounter Account Number
 *
 * @param accounts account number id
 * @param acct     G+ response.
 */
private void matchAccountNumber(Account[] accounts, GoogleSignInAccount acct) {
    for (int index = 0; index < accounts.length; index++) {
        if (accounts[index].name.equals(acct.getEmail())) {
            userIdCounter = index;
            break;
        }
    }
}

/**
 * Google login response.
 *
 * @param result G+ instance.
 */
public void handleSignInResult(GoogleSignInResult result) {
    if (result.isSuccess()) {
        GoogleSignInAccount acct = result.getSignInAccount();
        if (acct == null || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        findAuth(AccountManager.get(mContext).getAccountsByType("com.google"), acct);

    } else if (result.getStatus().getStatusCode() == G_LOGIN_CANCELLED) {
        ToastUtils.getInstance(mContext).showToast(mContext.getString(R.string.google_login_cancelled));
    } else {
        ToastUtils.getInstance(mContext).showToast(mContext.getString(R.string.message_not_able_to_login_via_google));
    }
}

public class GoogleAsyncTask extends AsyncTask<Void, Void, String> {
    private Account[] mAccountsByType;
    private GoogleSignInAccount mGoogleSignInAccount;

    /**
     * Instantiates a new Google async task.
     *
     * @param accountsByType
     * @param acct
     */
    public GoogleAsyncTask(Account[] accountsByType, GoogleSignInAccount acct) {
        mAccountsByType = accountsByType;
        mGoogleSignInAccount = acct;
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            return GoogleAuthUtil.getToken(mContext, mAccountsByType[userIdCounter], Constants.OAUTH_URL);
        } catch (UserRecoverableAuthException e) {
            Crashlytics.logException(e.getCause());
            AppLogger.e(e);
            mResponseListener.onTokenNotFound(e.getIntent(), RC_SIGN_IN);
        } catch (GoogleAuthException | IOException e) {
            Crashlytics.logException(e.getCause());
            AppLogger.e(e);
        }
        return "";
    }

    @Override
    protected void onPostExecute(String token) {
        IsAuthValidRequest isAuthValidRequest = new IsAuthValidRequest();
        isAuthValidRequest.setEmail(mGoogleSignInAccount.getEmail());
        isAuthValidRequest.setFirstName(mGoogleSignInAccount.getDisplayName());
        isAuthValidRequest.setLastName(mGoogleSignInAccount.getFamilyName());
        mResponseListener.onGoogleUserInfoAvailable(isAuthValidRequest, token);
    }
}

public interface GoogleResponse {

    /**
     * When user info and token found.
     *
     * @param isAuthValidRequest info instance.
     * @param token G+.
     */
    void onGoogleUserInfoAvailable(IsAuthValidRequest isAuthValidRequest, String token);

    /**
     * Invoke when auth token not found.
     *
     * @param intent      instance.
     * @param requestCode request code.
     */
    void onTokenNotFound(Intent intent, int requestCode);
}
}


问:
Java: Hibernate does not see changes in DataBase
I have two different applications that share the same database. The problem is that when I have an application change something in the database, the other does not update.

I tried to make a session.flush() but it didn't work. The only way is to close the entire session and recreate it, but of course, that takes too long.

答: I haven't tested this but the Session class has a clear method that evicts all loaded entities. This should force a reload from the db.</p>


问:
How does BinaryFormatter.Deserialize create new objects?
When BinaryFormatter deserializes a stream into objects, it appears to create new objects without calling constructors.

How is it doing this? And why? Is there anything else in .NET that does this?

Here's a demo:

```<code>[Serializable]
public class Car
{
    public static int constructionCount = 0;

    public Car()
    {
        constructionCount++;
    }
}

public class Test
{
    public static void Main(string[] args)
    {
        // Construct a car
        Car car1 = new Car();

        // Serialize and then deserialize to create a second, identical car
        MemoryStream stream = new MemoryStream();
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, car1);
        stream.Seek(0, SeekOrigin.Begin);
        Car car2 = (Car)formatter.Deserialize(stream);

        // Wait, what happened?
        Console.WriteLine("Cars constructed: " + Car.constructionCount);
        if (car2 != null && car2 != car1)
        {
            Console.WriteLine("But there are actually two.");
        }
    }
}
</code>```

Output:

Cars constructed: 1

But there are actually two.

答:
Not sure why the constructor does not get called but I use IDeserializationCallback as a work around.

also take a look at

OnSerializingAttribute

OnSerializedAttribute

OnDeserializingAttribute

OnDeserializedAttribute

Body:
When BinaryFormatter deserializes a stream into objects, it appears to create new objects without calling constructors.

How is it doing this? And why? Is there anything else in .NET that does this?

Here's a demo:

[Serializable]
public class Car
{
    public static int constructionCount = 0;

    public Car()
    {
        constructionCount++;
    }
}

public class Test
{
    public static void Main(string[] args)
    {
        // Construct a car
        Car car1 = new Car();

        // Serialize and then deserialize to create a second, identical car
        MemoryStream stream = new MemoryStream();
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, car1);
        stream.Seek(0, SeekOrigin.Begin);
        Car car2 = (Car)formatter.Deserialize(stream);

        // Wait, what happened?
        Console.WriteLine("Cars constructed: " + Car.constructionCount);
        if (car2 != null && car2 != car1)
        {
            Console.WriteLine("But there are actually two.");
        }
    }
}

Output:

Cars constructed: 1

But there are actually two.


问:
Vapor: git push heroku master is failing
I've been working with Vapor and Heroku for a few weeks now and it is all going well. Vapor is fab! ;] I have been successfully updating the app on Heroku using git push heroku master until yesterday evening when I started to get this error:

```<code>$ git push heroku master
Counting objects: 26, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (24/24), done.
Writing objects: 100% (26/26), 7.37 KiB | 0 bytes/s, done.
Total 26 (delta 15), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Swift app detected
remote: Cloning into 'swiftenv'...
remote: Swift 3 Heroku Installer
remote:   Version: 3.0.2
remote:   Operating System: ubuntu1404
remote:  Installing Swiftenv
remote: Cloning into '/app/.swiftenv'...
remote:  Installing Swift
remote: Downloading https://swift.org/builds/swift-3.0.2-release/ubuntu1404/swift-3.0.2-RELEASE/swift-3.0.2-RELEASE-ubuntu14.04.tar.gz
remote: /tmp/swiftenv-3.0.2- /tmp/build_577666a1ce2003bd1d820e031bc0f306
remote:   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
remote:                                  Dload  Upload   Total   Spent    Left  Speed
remote: 100  113M  100  113M    0     0  8057k      0  0:00:14  0:00:14 --:--:-- 8613k
remote: /tmp/build_577666a1ce2003bd1d820e031bc0f306
remote: 3.0.2 has been installed.
remote: ✅  Done
remote: precompile
remote: -----> Installing toolbox
remote: Downloading...
remote: Compiling...
remote: <unknown>:0: error: build had 1 command failures
remote: swift-build: error: exit(1): /app/.swiftenv/versions/3.0.2/usr/bin/swift-build-tool -f /tmp/build_577666a1ce2003bd1d820e031bc0f306/vapor-toolbox/.build/debug.yaml
remote:  !     Push rejected, failed to compile Swift app.
remote:
remote:  !     Push failed
remote: Verifying deploy....
remote:
remote: !   Push rejected to zzzzzzzz.
remote:
To https://git.heroku.com/zzzzzzzz.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/zzzzzzzz.git'
</code>```

The master branch of my repo is clean and up to date with no commits pending from elsewhere (there's only be working on the code).

答:
Hah! The guys on the Vapor Slack have sorted it. pbodsk, you were correct in that it was a Swift 3.1 issue.

You need to create a .swift-version file in the root directory of your Vapor project. The content of the file is simply:

```<code>3.1
</code>```

When this is pushed to Heroku, it will compile using the correct version of Swift.

Please be aware that you'll also need to do this if you are having this issue:

vapor toolbox broken after upgrading swift

Body:
I've been working with Vapor and Heroku for a few weeks now and it is all going well. Vapor is fab! ;] I have been successfully updating the app on Heroku using git push heroku master until yesterday evening when I started to get this error:

$ git push heroku master
Counting objects: 26, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (24/24), done.
Writing objects: 100% (26/26), 7.37 KiB | 0 bytes/s, done.
Total 26 (delta 15), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Swift app detected
remote: Cloning into 'swiftenv'...
remote: Swift 3 Heroku Installer
remote:   Version: 3.0.2
remote:   Operating System: ubuntu1404
remote:  Installing Swiftenv
remote: Cloning into '/app/.swiftenv'...
remote:  Installing Swift
remote: Downloading https://swift.org/builds/swift-3.0.2-release/ubuntu1404/swift-3.0.2-RELEASE/swift-3.0.2-RELEASE-ubuntu14.04.tar.gz
remote: /tmp/swiftenv-3.0.2- /tmp/build_577666a1ce2003bd1d820e031bc0f306
remote:   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
remote:                                  Dload  Upload   Total   Spent    Left  Speed
remote: 100  113M  100  113M    0     0  8057k      0  0:00:14  0:00:14 --:--:-- 8613k
remote: /tmp/build_577666a1ce2003bd1d820e031bc0f306
remote: 3.0.2 has been installed.
remote: ✅  Done
remote: precompile
remote: -----> Installing toolbox
remote: Downloading...
remote: Compiling...
remote: <unknown>:0: error: build had 1 command failures
remote: swift-build: error: exit(1): /app/.swiftenv/versions/3.0.2/usr/bin/swift-build-tool -f /tmp/build_577666a1ce2003bd1d820e031bc0f306/vapor-toolbox/.build/debug.yaml
remote:  !     Push rejected, failed to compile Swift app.
remote:
remote:  !     Push failed
remote: Verifying deploy....
remote:
remote: !   Push rejected to zzzzzzzz.
remote:
To https://git.heroku.com/zzzzzzzz.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/zzzzzzzz.git'

The master branch of my repo is clean and up to date with no commits pending from elsewhere (there's only be working on the code).

Body:
Hah! The guys on the Vapor Slack have sorted it. pbodsk, you were correct in that it was a Swift 3.1 issue.

You need to create a .swift-version file in the root directory of your Vapor project. The content of the file is simply:

3.1

When this is pushed to Heroku, it will compile using the correct version of Swift.

Please be aware that you'll also need to do this if you are having this issue:

vapor toolbox broken after upgrading swift


问:
How can I extract objects several layers deep using the map method?
I'm a trying to access the change order information as seen below to create a list of all the change_order_names. Using the current code I am getting the results I have posted. Will someone show me how I can access the change order information and produce the list?

```<code>if (componentType == CHANGE_ORDER_TYPE) {
        if (!this.props.data) {
            return null;
        } else {
            const changeList = this.props.data.map(function (result) {
                return (result.change_orders);
            });
            // return resultsList;
            console.log(changeList);
        }
    }
</code>```

This is the current response from the map method above.

```<code>[
 [
  {
     "id":1,
     "change_order_name":"change 1",
     "project_id":"1",
     "cws_change_order_id":"33214324",
     "slug":"change-1",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":2,
     "change_order_name":"change 2",
     "project_id":"1",
     "cws_change_order_id":"3211324",
     "slug":"change-2",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":3,
     "change_order_name":"change 3",
     "project_id":"2",
     "cws_change_order_id":"3234324",
     "slug":"change-3",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":4,
     "change_order_name":"change 4",
     "project_id":"2",
     "cws_change_order_id":"6234532",
     "slug":"change-4",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":5,
     "change_order_name":"change 5",
     "project_id":"3",
     "cws_change_order_id":"3124214",
     "slug":"change-5",
     "created_at":null,
     "updated_at":null
  }
]
]
</code>```

答:
It's not entirely clear what your desired output is, but I think you want a single array with all change_orders in it?  If this is correct then you can use the reduce function after your current map function:

```<code>if (componentType == CHANGE_ORDER_TYPE) {
    if (!this.props.data) {
        return null;
    } else {
        const changeList = this.props.data.map(function (result) {
            return (result.change_orders);
        }).reduce((output, item) => [...output, ...item], []);
        // return changeList;
        console.log(changeList);
    }
}
</code>```

const mapOutput = [
 [
  {
     "id":1,
     "change_order_name":"change 1",
     "project_id":"1",
     "cws_change_order_id":"33214324",
     "slug":"change-1",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":2,
     "change_order_name":"change 2",
     "project_id":"1",
     "cws_change_order_id":"3211324",
     "slug":"change-2",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":3,
     "change_order_name":"change 3",
     "project_id":"2",
     "cws_change_order_id":"3234324",
     "slug":"change-3",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":4,
     "change_order_name":"change 4",
     "project_id":"2",
     "cws_change_order_id":"6234532",
     "slug":"change-4",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":5,
     "change_order_name":"change 5",
     "project_id":"3",
     "cws_change_order_id":"3124214",
     "slug":"change-5",
     "created_at":null,
     "updated_at":null
  }
]
];

const change_orders = mapOutput.reduce((orders, arr) => [...orders,...arr],[]);

console.log(change_orders);```

Body:
I'm a trying to access the change order information as seen below to create a list of all the change_order_names. Using the current code I am getting the results I have posted. Will someone show me how I can access the change order information and produce the list?

if (componentType == CHANGE_ORDER_TYPE) {
        if (!this.props.data) {
            return null;
        } else {
            const changeList = this.props.data.map(function (result) {
                return (result.change_orders);
            });
            // return resultsList;
            console.log(changeList);
        }
    }

This is the current response from the map method above.

[
 [
  {
     "id":1,
     "change_order_name":"change 1",
     "project_id":"1",
     "cws_change_order_id":"33214324",
     "slug":"change-1",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":2,
     "change_order_name":"change 2",
     "project_id":"1",
     "cws_change_order_id":"3211324",
     "slug":"change-2",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":3,
     "change_order_name":"change 3",
     "project_id":"2",
     "cws_change_order_id":"3234324",
     "slug":"change-3",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":4,
     "change_order_name":"change 4",
     "project_id":"2",
     "cws_change_order_id":"6234532",
     "slug":"change-4",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":5,
     "change_order_name":"change 5",
     "project_id":"3",
     "cws_change_order_id":"3124214",
     "slug":"change-5",
     "created_at":null,
     "updated_at":null
  }
]
]

Body:
It's not entirely clear what your desired output is, but I think you want a single array with all change_orders in it?  If this is correct then you can use the reduce function after your current map function:

if (componentType == CHANGE_ORDER_TYPE) {
    if (!this.props.data) {
        return null;
    } else {
        const changeList = this.props.data.map(function (result) {
            return (result.change_orders);
        }).reduce((output, item) => [...output, ...item], []);
        // return changeList;
        console.log(changeList);
    }
}

const mapOutput = [
 [
  {
     "id":1,
     "change_order_name":"change 1",
     "project_id":"1",
     "cws_change_order_id":"33214324",
     "slug":"change-1",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":2,
     "change_order_name":"change 2",
     "project_id":"1",
     "cws_change_order_id":"3211324",
     "slug":"change-2",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":3,
     "change_order_name":"change 3",
     "project_id":"2",
     "cws_change_order_id":"3234324",
     "slug":"change-3",
     "created_at":null,
     "updated_at":null
  },
  {
     "id":4,
     "change_order_name":"change 4",
     "project_id":"2",
     "cws_change_order_id":"6234532",
     "slug":"change-4",
     "created_at":null,
     "updated_at":null
  }
],
[
  {
     "id":5,
     "change_order_name":"change 5",
     "project_id":"3",
     "cws_change_order_id":"3124214",
     "slug":"change-5",
     "created_at":null,
     "updated_at":null
  }
]
];

const change_orders = mapOutput.reduce((orders, arr) => [...orders,...arr],[]);

console.log(change_orders);


问:
Ask user to turn on Location
How can I prompt the user to turn on Location?

The app is supposed to filter a list of locations with the current location of the user. If the user has the Location service turned off, the app should prompt the user asking for the Location to be turned on.

For instance Trip Advisor app does this:

( Not sure if I can post other apps screenshots here, but if I shouldn't be doing it, please say so. And apologize for the full sized images, tried to make them smaller, but SO didn't liked it... )

In the first image, you can see I have the Location service turned off. The, after opening the Trip Advisor app, and tapping the Near me now option, I'm prompted with the second image, where I'm asked to Turn on Location services. After I tap the button, a dialog shows up so I can allow, or disallow, the Location service to be turned on. If I tap OK, the Location service is turned on on the device, and the app consumes it.

How can I achieve this?

答:
You can use the following class for moving user to settings. First check for the location if it is not available call showSettingAlert

```<code>AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        mContext.startActivity(intent);
    }
});

// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});
// Showing Alert Message
alertDialog.show();
</code>```

Title: Ask user to turn on Location

Body:
You can use the following class for moving user to settings. First check for the location if it is not available call showSettingAlert

AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        mContext.startActivity(intent);
    }
});

// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});
// Showing Alert Message
alertDialog.show();


问:
Unable to get the JSON POST in php
I don't know, if this is a duplicate question to any post. As I am not able to get the exact answer of my question..

I have a Ajax request, which is sending 'Category' to a php page on a 'api.mysite.com/create.php'

Ajax code is as follows:

```<code>$.ajax({
type: "POST",
url: _apiUrl+"create.php",
contentType: 'application/json',
data: JSON.stringify({ Category: Category}),
dataType: 'json',
success: function(data){
    $("#myDiv").html(data);
}});
</code>```

And my PHP Code is like this:

```<code><?php
ini_set('display_errors', 1);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST,GET,OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
include("includes/db_connection.php");
$Category = json_decode($_POST['Category'], true);
$Category = $Category[0]['Category'];?>
</code>```

Any help will be much appreciated. Thank You in advance.
Best regards,

答:
Replace

```<code>data: JSON.stringify({ Category: Category}),
</code>```

To

```<code>data: {Category : JSON.stringify({ Category: Category})},
</code>```

You may get solution here Send array with Ajax to PHP script

Title: Unable to get the JSON POST in php

Body:
I don't know, if this is a duplicate question to any post. As I am not able to get the exact answer of my question..

I have a Ajax request, which is sending 'Category' to a php page on a 'api.mysite.com/create.php'

Ajax code is as follows:

$.ajax({
type: "POST",
url: _apiUrl+"create.php",
contentType: 'application/json',
data: JSON.stringify({ Category: Category}),
dataType: 'json',
success: function(data){
    $("#myDiv").html(data);
}});

And my PHP Code is like this:

<?php
ini_set('display_errors', 1);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST,GET,OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
include("includes/db_connection.php");
$Category = json_decode($_POST['Category'], true);
$Category = $Category[0]['Category'];?>

Any help will be much appreciated. Thank You in advance.
Best regards,

Body:
Replace

data: JSON.stringify({ Category: Category}),

To

data: {Category : JSON.stringify({ Category: Category})},

You may get solution here Send array with Ajax to PHP script


问:
JavaScript Passing Parameters to modal ASP.NET Core
I have problem with my modal boostrap seems like not passing parameter to modal. Here is my code:

My view:

```<code>@foreach (var item in Model)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.EmployeeId)</td>
        <td>@Html.DisplayFor(modelItem => item.Fname)  @Html.DisplayFor(modelItem => item.Lname)</td>
        <td>@Html.DisplayFor(modelItem => item.PhoneNumber)</td>
        <td>@Html.DisplayFor(modelItem => item.Position)</td>
        <td>
            <a asp-action="Edit" asp-route-id="@item.EmployeeId">Edit</a> |
            <button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#myModal" data-emp-id="@item.EmployeeId"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Delete</button>
        </td>
    </tr>

}
</code>```

My modal:

```<code><div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Confirm Delete</h4>
        </div>
        <div class="modal-body">
            <p>Are you sure you want to delete invoice number:</p>
            <input type="text" name="empID" value=""/>
        </div>
        <div class="modal-footer">
            <form asp-controller="Employee" asp-action="Delete" method="post" class="form-inline" role="form">
                <input type="hidden" id="Id">
                <button type="submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Delete</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </form>
        </div>
    </div>
</div>
</code>```

My JavaScript:
I think the problem is somewhere in this code but I don't know why.

```<code><script src="./javascript.js" type="text/javascript">
$("button[type='button']").click(function () {
    $("#myModal").find("input[type='text']").val($(this).attr("EmpID"));
});
</code>```

What makes it wrong with my work? Does anyone knows why is not passing the parameter to model?

I'm just a beginner and I have no idea whats going on in my codes.

Any help would be appreciated.

答:
Your button doesn't have an attribute named EmpId. However it does have an attribute named data-emp-id which I assume contains the value you want.

jQuery has a data method for accessing data attributes easily; in short you can get it using $(this).data("emp-id")

Body:
I have problem with my modal boostrap seems like not passing parameter to modal. Here is my code:

My view:

@foreach (var item in Model)
{

        @Html.DisplayFor(modelItem => item.EmployeeId)
        @Html.DisplayFor(modelItem => item.Fname)  @Html.DisplayFor(modelItem => item.Lname)
        @Html.DisplayFor(modelItem => item.PhoneNumber)
        @Html.DisplayFor(modelItem => item.Position)

            Edit |
            <button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#myModal" data-emp-id="@item.EmployeeId"> Delete</button>

}

My modal:

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

Confirm Delete

Are you sure you want to delete invoice number:

            <input type="text" name="empID" value=""/>

            <form asp-controller="Employee" asp-action="Delete" method="post" class="form-inline" role="form">
                <input type="hidden" id="Id">
                <button type="submit" class="btn btn-danger"> Delete</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </form>

My JavaScript:
I think the problem is somewhere in this code but I don't know why.


问:
Drill into other dimension or Hierarchy than used in original MDX
Using iccube reporting V6, I cannot find a way to drill thru another dimension / Hierarchy using Drilldown Strategy "mdxExpression".

When selecting this option, the "mdxExpression" field below is defaulted to $member.children

Can someone provide a working example of this functionality ?

答:
This is a standard MDX function?

```<code>Member_Expression.Children
</code>```

The documentation on MSDN is here: https://technet.microsoft.com/en-us/library/ms146018(v=sql.110).aspx

So for example to get the states (children) of the member United States it would be this:

```<code>SELECT
  [Geography].[Geography].[Country].&[United States].Children ON 0
FROM [Adventure Works]
</code>```

Body:
This is a standard MDX function?

Member_Expression.Children

The documentation on MSDN is here: https://technet.microsoft.com/en-us/library/ms146018(v=sql.110).aspx

So for example to get the states (children) of the member United States it would be this:

SELECT
  [Geography].[Geography].[Country].&[United States].Children ON 0
FROM [Adventure Works]


问:
rails 3 meta_search usage
I am in the process of upgrading my app from Rails2 to Rails3.

My Rails2 app uses searchlogic heavily.

After googling i've come to know that searchlogic is not compatible with Rails3 and need to use meta_search instead.

But i havent quite understood the usage of meta_search vis-a-vis searchlogic.

If i have a User model with :name and :address fields, i am not able to use the following methods with meta_search. What am i doing wrong?

```<code>ruby-1.9.2-p0 > User.name_null
NoMethodError: undefined method `name_null' for #<Class:0x000000038d5ce0>
from /home/pratik/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
from (irb):7
from /home/pratik/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.3/lib/rails/commands/console.rb:44:in `start'
from /home/pratik/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.3/lib/rails/commands/console.rb:8:in `start'
from /home/pratik/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.3/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
</code>```

None of the methods like User.user_id_eq(1) or User.name_equals("Blah") are working.
I guess i havent understood the usage of meta_search yet!

Ref:

meta_search https://github.com/ernie/meta_search

答:
The methods are attributes to be set in a FormBuilder. As such, you'll want to call user_name_equals = "Bob", not user_name_equals("Bob"). Also, they'll be on a search instance, not the model itself.

@search = User.search(:user_name_eq => "Bob")

If you're looking for something to use in day to day query construction, try MetaWhere instead. http://metautonomo.us/projects/metawhere

Title: rails 3 meta_search usage

Body:
I am in the process of upgrading my app from Rails2 to Rails3.

My Rails2 app uses searchlogic heavily.

After googling i've come to know that searchlogic is not compatible with Rails3 and need to use meta_search instead.

But i havent quite understood the usage of meta_search vis-a-vis searchlogic.

If i have a User model with :name and :address fields, i am not able to use the following methods with meta_search. What am i doing wrong?

ruby-1.9.2-p0 > User.name_null
NoMethodError: undefined method `name_null' for #<Class:0x000000038d5ce0>
from /home/pratik/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
from (irb):7
from /home/pratik/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.3/lib/rails/commands/console.rb:44:in `start'
from /home/pratik/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.3/lib/rails/commands/console.rb:8:in `start'
from /home/pratik/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.3/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `'

None of the methods like User.user_id_eq(1) or User.name_equals("Blah") are working.
I guess i havent understood the usage of meta_search yet!

Ref:

meta_search https://github.com/ernie/meta_search