问:
windows encrypted rdp passwords in golang
like http://play.golang.org/p/fD7mx2k4Yc

window rdp password  encrypted  http://www.remkoweijnen.nl/blog/2007/10/18/how-rdp-passwords-are-encrypted/

```<code>   package main

    import (
        "fmt"
        "log"
        "syscall"
        "unsafe"
    )

    const (
        CRYPTPROTECT_UI_FORBIDDEN = 0x1
    )

    var (
        dllcrypt32  = syscall.NewLazyDLL("Crypt32.dll")
        dllkernel32 = syscall.NewLazyDLL("Kernel32.dll")

        procEncryptData = dllcrypt32.NewProc("CryptProtectData")
        procDecryptData = dllcrypt32.NewProc("CryptUnprotectData")
        procLocalFree   = dllkernel32.NewProc("LocalFree")
    )

    type DATA_BLOB struct {
        cbData uint32
        pbData *byte
    }

    func NewBlob(d []byte) *DATA_BLOB {
        if len(d) == 0 {
            return &DATA_BLOB{}
        }
        return &DATA_BLOB{
            pbData: &d[0],
            cbData: uint32(len(d)),
        }
    }

    func (b *DATA_BLOB) ToByteArray() []byte {
        d := make([]byte, b.cbData)
        copy(d, (*[1 << 30]byte)(unsafe.Pointer(b.pbData))[:])
        return d
    }

    func Encrypt(data []byte) ([]byte, error) {
        var outblob DATA_BLOB
        r, _, err := procEncryptData.Call(uintptr(unsafe.Pointer(NewBlob(data))), 0, 0, 0, 0, 0, uintptr(unsafe.Pointer(&outblob)))
        if r == 0 {
            return nil, err
        }
        defer procLocalFree.Call(uintptr(unsafe.Pointer(outblob.pbData)))
        return outblob.ToByteArray(), nil
    }

    func Decrypt(data []byte) ([]byte, error) {
        var outblob DATA_BLOB
        r, _, err := procDecryptData.Call(uintptr(unsafe.Pointer(NewBlob(data))), 0, 0, 0, 0, 0, uintptr(unsafe.Pointer(&outblob)))
        if r == 0 {
            return nil, err
        }
        defer procLocalFree.Call(uintptr(unsafe.Pointer(outblob.pbData)))
        return outblob.ToByteArray(), nil
    }

    func main() {
        const secret = "MYpasswd"
        enc, err := Encrypt([]byte(secret))
        if err != nil {
            log.Fatalf("Encrypt failed: %v", err)
        }
        dec, err := Decrypt(enc)
        if err != nil {
            log.Fatalf("Decrypt failed: %v", err)
        }
        if string(dec) != secret {
            log.Fatalf("decrypted secret \"%s\" does not match to \"%s\".", dec, secret)
        }
        fmt.Println(fmt.Sprintf("%x", enc))
        fmt.Println(string(dec))
    }
</code>```

out: 01000000d08c9ddf0115d1118c7a00c04fc297eb01000000de7c90fbe3c9854381f0a0ffe1d496f3000000000200000000001066000000010000200000000790b641e1a9d4bfe54d81966c4d7aaeabf19b63c36dff42668e3b256edbeed8000000000e8000000002000020000000d6385d3352d5a4b011e171ab25b30271e73a4ddc0b9f9bfb8ecd13f230362a0110000000da71663217c163d7ab77231282e7d8d64000000025fbcbb72efcdc711f3a74c38bddbf0b71538f0ffe27d133c0c5cd2434f88d55d924f598ac2f94758d66a448682ed841fb56ce8c9de38601dcce6bd42aa41fbb

MYpasswd

create  tmp.rdp

```<code>screen mode id:i:1
....
winposstr:s:0,1,153,64,953,664
username:s:{{username}}
domain:s:
password 51:b:01000000d08c9ddf0115d1118c7a00c04fc297eb0100000............
disable wallpaper:i:1
disable full window drag:i:1
</code>```

final：
   mstsc.exe  tmp.rdp

But Login failed

python  "win32crypt.CryptProtectData"  is work.

```<code>    pwdHash = win32crypt.CryptProtectData(u"MYpasswd", u'pws', None, None, None, 0)
    enc_password = binascii.hexlify(pwdHash)
</code>```

答:
make an addition for the not-detailed answer above. According @Fuqiang's answer, just transfer the encoding of the plain string to UTF-16LE before encrypting, and it finally works. So it looks like this:

```<code>....

func convertToUTF16LittleEndianBytes(s string) []byte {
    u := utf16.Encode([]rune(s))
    b := make([]byte, 2*len(u))
    for index, value := range u {
        binary.LittleEndian.PutUint16(b[index*2:], value)
    }
    return b
}

func main() {
    const secret = "MYpasswd"
    s := convertToUTF16LittleEndianBytes(secret)
    enc, err := Encrypt(s)
    if err != nil {
        log.Fatalf("Encrypt failed: %v", err)
    }
    ...
}
</code>```

And after decrypting, you have to decode the decrypted string from utf-16le before you comparing or using it, don't directly transfer the utf-16le char to string by string(dec).

Body:
like http://play.golang.org/p/fD7mx2k4Yc

window rdp password  encrypted  http://www.remkoweijnen.nl/blog/2007/10/18/how-rdp-passwords-are-encrypted/

   package main

    import (
        "fmt"
        "log"
        "syscall"
        "unsafe"
    )

    const (
        CRYPTPROTECT_UI_FORBIDDEN = 0x1
    )

    var (
        dllcrypt32  = syscall.NewLazyDLL("Crypt32.dll")
        dllkernel32 = syscall.NewLazyDLL("Kernel32.dll")

        procEncryptData = dllcrypt32.NewProc("CryptProtectData")
        procDecryptData = dllcrypt32.NewProc("CryptUnprotectData")
        procLocalFree   = dllkernel32.NewProc("LocalFree")
    )

    type DATA_BLOB struct {
        cbData uint32
        pbData *byte
    }

    func NewBlob(d []byte) *DATA_BLOB {
        if len(d) == 0 {
            return &DATA_BLOB{}
        }
        return &DATA_BLOB{
            pbData: &d[0],
            cbData: uint32(len(d)),
        }
    }

    func (b *DATA_BLOB) ToByteArray() []byte {
        d := make([]byte, b.cbData)
        copy(d, (*[1 << 30]byte)(unsafe.Pointer(b.pbData))[:])
        return d
    }

    func Encrypt(data []byte) ([]byte, error) {
        var outblob DATA_BLOB
        r, _, err := procEncryptData.Call(uintptr(unsafe.Pointer(NewBlob(data))), 0, 0, 0, 0, 0, uintptr(unsafe.Pointer(&outblob)))
        if r == 0 {
            return nil, err
        }
        defer procLocalFree.Call(uintptr(unsafe.Pointer(outblob.pbData)))
        return outblob.ToByteArray(), nil
    }

    func Decrypt(data []byte) ([]byte, error) {
        var outblob DATA_BLOB
        r, _, err := procDecryptData.Call(uintptr(unsafe.Pointer(NewBlob(data))), 0, 0, 0, 0, 0, uintptr(unsafe.Pointer(&outblob)))
        if r == 0 {
            return nil, err
        }
        defer procLocalFree.Call(uintptr(unsafe.Pointer(outblob.pbData)))
        return outblob.ToByteArray(), nil
    }

    func main() {
        const secret = "MYpasswd"
        enc, err := Encrypt([]byte(secret))
        if err != nil {
            log.Fatalf("Encrypt failed: %v", err)
        }
        dec, err := Decrypt(enc)
        if err != nil {
            log.Fatalf("Decrypt failed: %v", err)
        }
        if string(dec) != secret {
            log.Fatalf("decrypted secret \"%s\" does not match to \"%s\".", dec, secret)
        }
        fmt.Println(fmt.Sprintf("%x", enc))
        fmt.Println(string(dec))
    }

out: 01000000d08c9ddf0115d1118c7a00c04fc297eb01000000de7c90fbe3c9854381f0a0ffe1d496f3000000000200000000001066000000010000200000000790b641e1a9d4bfe54d81966c4d7aaeabf19b63c36dff42668e3b256edbeed8000000000e8000000002000020000000d6385d3352d5a4b011e171ab25b30271e73a4ddc0b9f9bfb8ecd13f230362a0110000000da71663217c163d7ab77231282e7d8d64000000025fbcbb72efcdc711f3a74c38bddbf0b71538f0ffe27d133c0c5cd2434f88d55d924f598ac2f94758d66a448682ed841fb56ce8c9de38601dcce6bd42aa41fbb

MYpasswd

create  tmp.rdp

screen mode id:i:1
....
winposstr:s:0,1,153,64,953,664
username:s:{{username}}
domain:s:
password 51:b:01000000d08c9ddf0115d1118c7a00c04fc297eb0100000............
disable wallpaper:i:1
disable full window drag:i:1

final：
   mstsc.exe  tmp.rdp

But Login failed

python  "win32crypt.CryptProtectData"  is work.

    pwdHash = win32crypt.CryptProtectData(u"MYpasswd", u'pws', None, None, None, 0)
    enc_password = binascii.hexlify(pwdHash)

Body:
make an addition for the not-detailed answer above. According @Fuqiang's answer, just transfer the encoding of the plain string to UTF-16LE before encrypting, and it finally works. So it looks like this:

....

func convertToUTF16LittleEndianBytes(s string) []byte {
    u := utf16.Encode([]rune(s))
    b := make([]byte, 2*len(u))
    for index, value := range u {
        binary.LittleEndian.PutUint16(b[index*2:], value)
    }
    return b
}

func main() {
    const secret = "MYpasswd"
    s := convertToUTF16LittleEndianBytes(secret)
    enc, err := Encrypt(s)
    if err != nil {
        log.Fatalf("Encrypt failed: %v", err)
    }
    ...
}

And after decrypting, you have to decode the decrypted string from utf-16le before you comparing or using it, don't directly transfer the utf-16le char to string by string(dec).


来源: stackexchange

问:
for each loop in java not working with a array that changes as loop progresses
In this I have provided an array of arrays which changes as loop progresses , and the result was not as expected.
Please tell me why that happened.

```<code>public class forEach2 {

public static void main(String[] args) {

    int a [][] = {{ 1,2,3},{4 ,5,6},{7,8,9}};
    int proArr = 0;
    for (int pro : a[proArr] ){
        System.out.println(pro);
        proArr ++;
    }

}
</code>```

result -

```<code>1
2
3
</code>```

here , as the loop starts the value of proArr (which is handling the Array of Arrays , array 'a' to be more specific) changes but that puts no effect o the result.

the result is the data of a[0];

why is this happening in the for loop of Java ?

答:
I assume that you wanted to print all values in the multidimensional 'a' array. You need two nested 'for' loops to achieve that.
Change your 'for' loop to this one:

```<code>for(int [ ] pro : a) {
for(int p : pro){
System.out.println(p);
}
}
</code>```

Hope it will solve your problem :)

EDIT

If you want to print only first elements of these arrays you have to change your 'for' loop to this one:

```<code>for(int [ ] pro : a){
System.out.println(pro[0]);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In this I have provided an array of arrays which changes as loop progresses , and the result was not as expected.
Please tell me why that happened.

public class forEach2 {

public static void main(String[] args) {

    int a [][] = {{ 1,2,3},{4 ,5,6},{7,8,9}};
    int proArr = 0;
    for (int pro : a[proArr] ){
        System.out.println(pro);
        proArr ++;
    }

}

result -

1
2
3

here , as the loop starts the value of proArr (which is handling the Array of Arrays , array 'a' to be more specific) changes but that puts no effect o the result.

the result is the data of a[0];

why is this happening in the for loop of Java ?

Body:
I assume that you wanted to print all values in the multidimensional 'a' array. You need two nested 'for' loops to achieve that.
Change your 'for' loop to this one:

for(int [ ] pro : a) {
for(int p : pro){
System.out.println(p);
}
}

Hope it will solve your problem :)

EDIT

If you want to print only first elements of these arrays you have to change your 'for' loop to this one:

for(int [ ] pro : a){
System.out.println(pro[0]);
}


问:
Typed query for INNER JOIN (SELECT DISTINCT)?
Is it possible to create a typed query that produces the following SQL?</p>

```<code>SELECT A.*
FROM schema1.Table1 A
INNER JOIN (SELECT DISTINCT column1, column2 FROM schema1.Table2) B ON A.column1 = B.column1
</code>```

答:
You can't join a sub select with a typed API, the easiest way to implement this would be to use a CustomJoin, e.g:

```<code>var table1 = db.GetTableName<Table1>();
var q = db.From<Table1>()
    .CustomJoin($@"INNER JOIN
        (SELECT DISTINCT column1, column2 FROM schema1.Table2) B
        ON {table1}.column1 = B.column1");
</code>```

Body:
Is it possible to create a typed query that produces the following SQL?

SELECT A.*
FROM schema1.Table1 A
INNER JOIN (SELECT DISTINCT column1, column2 FROM schema1.Table2) B ON A.column1 = B.column1

Body:
You can't join a sub select with a typed API, the easiest way to implement this would be to use a CustomJoin, e.g:

var table1 = db.GetTableName<Table1>();
var q = db.From<Table1>()
    .CustomJoin($@"INNER JOIN
        (SELECT DISTINCT column1, column2 FROM schema1.Table2) B
        ON {table1}.column1 = B.column1");


问:
Creating an ORD_MAP with Tupples as Key in SML
I'm doing an exercise in SML in which I'm in a grid and start from cell (i,j) and I want to go to cell (x,y). To simulate this every cell is treated as a State (i,j,move) where move how it got there from the previous cell. Then I wrote a simple traversal algorithm (more like dfs) which starts searching the States until it finds the desired one.

Note that for the traversal function I use a Map-Dictionary which takes a State as an Index in order to keep track of the visited States.

Code:

```<code>val startp = (0,0)
val endp = (3,0)
val (N,M) = (4,4)

(*Define the Basic structures tht will be used*)
datatype movement = RIGHT | DOWN | LEFT | UP

type State = int * int * movement

val firstState = (#1 startp,#2 startp,UP): State

structure STATES_KEY: ORD_KEY =
  struct
    type ord_key = State
    val compare = fn (s1:State, s2:State) =>
      if (#1 s1 = #1 s2) andalso (#2 s1 = #2 s2)
      then EQUAL
      else if (#1 s1 > #1 s2) then GREATER
      else LESS
  end

structure StatesMap = SplayMapFn(STATES_KEY)

fun convert_ij id = (id div M, id mod N)

fun getNextStates ((i,j,_):State): State list =
  [ (i,j+1,RIGHT),
    (i+1,j,DOWN),
    (i,j-1,LEFT),
    (i-1,j,UP)]

fun getPrevState ((i,j,move):State): State =
  case move of
       RIGHT => (i,j-1,UP)
     | LEFT => (i,j+1,UP)
     | UP => (i+1,j,UP)
     | DOWN => (i-1,j,UP)

(*True -> Invalid State*)
fun checkInvalidState ((i,j,_):State) =
  if (i < 0 orelse i > N-1 orelse j < 0 orelse j > M-1)
  then true
  else false

fun checkEnd ((i,j,_):State) =
  if (i = #1 endp andalso j = #2 endp)
  then true
  else false

fun traversal [] visited = visited
  | traversal (h::t) visited =
  if (checkEnd h) then visited
  else if (checkInvalidState h) then traversal t visited
  else if (StatesMap.find (visited, h) = NONE)
  then
    let
      val [s1,s2,s3,s4] = getNextStates h
    in
      traversal (s1::s2::s3::s4::t) (StatesMap.insert (visited, h, h))
    end
  else traversal t visited

val it = traversal [firstState] StatesMap.empty
</code>```

When I run the program, it gets in an infinite loop when executing the traverse function. It goes from State: (1,0)->(0,0)->(0,1)->(0,2)->(0,3)->(1,3)->(2,3)->(3,3)

And from there on it keeps on going between States (3,3) and (3,2). Also, I checked the Map struct when the traversal function is in State (3,2) and State (3,3) exists in it, meaning that it shouldn't look at it again and continue checking the other States.

What exactly doesn't work the way I think it works and causes this loop?

答:
I believe the problem is that your comparison function is broken. Edit: For example it defines

```<code>(0, 2) < (0, 1)
(0, 1) < (0, 2)
</code>```

which violates anti-symmetry. But that's a necessary property of an ordering.

You want a proper lexicographic ordering:

```<code>fun compare ((x1,y1,_), (x2,y2,_)) =
    case Int.compare (x1, x2) of
      EQUAL => Int.compare (y1, y2)
    | order => order
</code>```

Body:
I'm doing an exercise in SML in which I'm in a grid and start from cell (i,j) and I want to go to cell (x,y). To simulate this every cell is treated as a State (i,j,move) where move how it got there from the previous cell. Then I wrote a simple traversal algorithm (more like dfs) which starts searching the States until it finds the desired one.

Note that for the traversal function I use a Map-Dictionary which takes a State as an Index in order to keep track of the visited States.

Code:

val startp = (0,0)
val endp = (3,0)
val (N,M) = (4,4)

(*Define the Basic structures tht will be used*)
datatype movement = RIGHT | DOWN | LEFT | UP

type State = int * int * movement

val firstState = (#1 startp,#2 startp,UP): State

structure STATES_KEY: ORD_KEY =
  struct
    type ord_key = State
    val compare = fn (s1:State, s2:State) =>
      if (#1 s1 = #1 s2) andalso (#2 s1 = #2 s2)
      then EQUAL
      else if (#1 s1 > #1 s2) then GREATER
      else LESS
  end

structure StatesMap = SplayMapFn(STATES_KEY)

fun convert_ij id = (id div M, id mod N)

fun getNextStates ((i,j,_):State): State list =
  [ (i,j+1,RIGHT),
    (i+1,j,DOWN),
    (i,j-1,LEFT),
    (i-1,j,UP)]

fun getPrevState ((i,j,move):State): State =
  case move of
       RIGHT => (i,j-1,UP)
     | LEFT => (i,j+1,UP)
     | UP => (i+1,j,UP)
     | DOWN => (i-1,j,UP)

(*True -> Invalid State*)
fun checkInvalidState ((i,j,_):State) =
  if (i < 0 orelse i > N-1 orelse j < 0 orelse j > M-1)
  then true
  else false

fun checkEnd ((i,j,_):State) =
  if (i = #1 endp andalso j = #2 endp)
  then true
  else false

fun traversal [] visited = visited
  | traversal (h::t) visited =
  if (checkEnd h) then visited
  else if (checkInvalidState h) then traversal t visited
  else if (StatesMap.find (visited, h) = NONE)
  then
    let
      val [s1,s2,s3,s4] = getNextStates h
    in
      traversal (s1::s2::s3::s4::t) (StatesMap.insert (visited, h, h))
    end
  else traversal t visited

val it = traversal [firstState] StatesMap.empty

When I run the program, it gets in an infinite loop when executing the traverse function. It goes from State: (1,0)->(0,0)->(0,1)->(0,2)->(0,3)->(1,3)->(2,3)->(3,3)

And from there on it keeps on going between States (3,3) and (3,2). Also, I checked the Map struct when the traversal function is in State (3,2) and State (3,3) exists in it, meaning that it shouldn't look at it again and continue checking the other States.

What exactly doesn't work the way I think it works and causes this loop?

Body:
I believe the problem is that your comparison function is broken. Edit: For example it defines

(0, 2) < (0, 1)
(0, 1) < (0, 2)

which violates anti-symmetry. But that's a necessary property of an ordering.

You want a proper lexicographic ordering:

fun compare ((x1,y1,_), (x2,y2,_)) =
    case Int.compare (x1, x2) of
      EQUAL => Int.compare (y1, y2)
    | order => order


问:
SSIS Excel to CSV - 64 bit True
I'm trying to convert excel(xlsx) file to CSV file - SSIS without changing 64 bit option.

All other packages run on 64 bit - True except this.

I have created a script task which doesn't work unless I turn 64 bit to False.

Used Excel source to Flat file destination works with 64 bit false but flipping back to 64 bit = true, things doesn't work anymore.

Is there a way to work with Excel and 64 bit = True in SSIS.

Need advice, Thanks!!

答:
I think you have to download and install the AccessDatabaseEngine 64bit

When searching on this issue i found these articles

http://www.madeiradata.com/load-data-excel-ssis-32-bit-vs-64-bit/

http://toddmcdermid.blogspot.com/2009/10/quick-reference-ssis-in-32-and-64-bits.html

They contains the full story :)

Title: SSIS Excel to CSV - 64 bit True


问:
Add Checked Table Rows to Email Body
I have a table where each row can be selected by checking a checkbox. Whatever rows are selected, I am wanting those rows to be pasted to the body of an email that pops up when the "Checkout" button is pressed.

Currently, whenever I hit the "Checkout" button, the email pops up and it will display the first row in the table, whether selected or not, but nothing more.

How can I get multiple selections displayed based on if it is checked?

Table:

```<code><section id="checkout-btn">
<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>
</section>

<br>

<table id="merchTable" cellspacing="5" class="sortable">
    <thead>
        <tr class="ui-widget-header">
            <th class="sorttable_nosort"></th>
            <th class="sorttable_nosort">Loc</th>
            <th class="merchRow">Report Code</th>
            <th class="merchRow">SKU</th>
            <th class="merchRow">Special ID</th>
            <th class="merchRow">Description</th>
            <th class="merchRow">Quantity</th>
            <th class="sorttable_nosort">Unit</th>
            <th style="display: none;" class="num">Quantity #</th>
        </tr>
    </thead>
    <tbody>

        <?php foreach ($dbh->query($query) as $row) {?>

        <tr>
            <td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
            <td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
            <td name="rows[0][0][rp-code]" class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
            <td name="rows[0][0][sku]" class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
            <td name="rows[0][0][special-id]" class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
            <td name="rows[0][0][description]" class="description ui-widget-content" data-description="<?php echo $row['Description'] ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
            <td name="rows[0][0][quantity]" class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?></td>
            <td name="rows[0][0][unit]" class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
            <td name="rows[0][0][quant]" style="display: none;" class="quantity_num ui-widget-content"><input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
        </tr>

    <?php } ?>

    </tbody>
</table>
</code>```

Javascript that adds data to email:

```<code>function sendMail() {
    var link = "mailto:me@example.com"
             + "?subject=" + encodeURIComponent("Order")
             + "&body=" + encodeURIComponent($('.loc').data('loc')) + '\xa0\xa0' + encodeURIComponent($('.rp-code').data('rp-code')) + '\xa0\xa0' + encodeURIComponent($('.sku').data('sku')) + '\xa0\xa0' + encodeURIComponent($('.special-id').data('special-id')) + '\xa0\xa0' + encodeURIComponent($('.description').data('description')) + '\xa0\xa0' + encodeURIComponent($('.quantity').data('quantity')) + '\xa0\xa0' + encodeURIComponent($('.unit').data('unit')) + '\xa0\xa0' + encodeURIComponent($('.quantity_num').data('quantity_num'));

    window.location.href = link;
}
</code>```

答:
You are calling array elements like rows[0][0][rp-code] outside of PHP tags.
You could create the tables more easily by keeping all nested inside the PHP tags and by echoing each table elements.
Like so:

```<code>echo <tr>;
echo <td name="rows[0][0][rp-code]">Some Text</td>;
echo </tr>;
</code>```

You could also do everything inside javascript, but this depends on your preferences

Title: Add Checked Table Rows to Email Body

Body:
I have a table where each row can be selected by checking a checkbox. Whatever rows are selected, I am wanting those rows to be pasted to the body of an email that pops up when the "Checkout" button is pressed.

Currently, whenever I hit the "Checkout" button, the email pops up and it will display the first row in the table, whether selected or not, but nothing more.

How can I get multiple selections displayed based on if it is checked?

Table:

<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>

            Loc
            Report Code
            SKU
            Special ID
            Description
            Quantity
            Unit
            Quantity #

        <?php foreach ($dbh->query($query) as $row) {?>

            <input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>">
            <td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?>
            <td name="rows[0][0][rp-code]" class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?>
            <td name="rows[0][0][sku]" class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?>
            <td name="rows[0][0][special-id]" class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?>
            <td name="rows[0][0][description]" class="description ui-widget-content" data-description="<?php echo $row['Description'] ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?>
            <td name="rows[0][0][quantity]" class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?>
            <td name="rows[0][0][unit]" class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?>
            <input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>">

    <?php } ?>

Javascript that adds data to email:

function sendMail() {
    var link = "mailto:me@example.com"
             + "?subject=" + encodeURIComponent("Order")
             + "&body=" + encodeURIComponent($('.loc').data('loc')) + '\xa0\xa0' + encodeURIComponent($('.rp-code').data('rp-code')) + '\xa0\xa0' + encodeURIComponent($('.sku').data('sku')) + '\xa0\xa0' + encodeURIComponent($('.special-id').data('special-id')) + '\xa0\xa0' + encodeURIComponent($('.description').data('description')) + '\xa0\xa0' + encodeURIComponent($('.quantity').data('quantity')) + '\xa0\xa0' + encodeURIComponent($('.unit').data('unit')) + '\xa0\xa0' + encodeURIComponent($('.quantity_num').data('quantity_num'));

    window.location.href = link;
}

Body:
You are calling array elements like rows[0][0][rp-code] outside of PHP tags.
You could create the tables more easily by keeping all nested inside the PHP tags and by echoing each table elements.
Like so:

echo <tr>;
echo <td name="rows[0][0][rp-code]">Some Text</td>;
echo </tr>;

You could also do everything inside javascript, but this depends on your preferences


问:
Question on using List
I created an List like this

```<code>List<Dictionary<DicKeyCla, DicValCla>>

public Class DicKeyCla
{
   public EnKey1 DicKeyItem1,
   public EnKey2 DicKeyItem2,
}

public enum EnKey1
{
   A1,
   A2,
   A3,
   A4,
   A5
}

public enum EnKey2
{
   B11,
   B12,
   B13,
   B14,
   B15,
   B16,
   B17,
   B18,
   B19,
}
</code>```

As I know, there is contains() method available for List class.

If I called an function which argues contain the DicKeyCla members like A3 and B15.

How can I pick out the entirely dictionary member from the Top level List rapidly?

I need do more operation on dictionary member.

答:
The List.Contains method would only check if the parameter you send it is an item in the list.

If you want to be able to find an entire dictionary that contains some given A3 or B15 from this data strcuture, you will have to implement this yourself.

You can do something like manage an internal dictionary that would keep mapping from various A3/B15/etc objects to Lists of Dictionaries to which they have been added.

If O(1) search is not very important to you, consider favoring simplicity over performance, and just scan the list.

ContentLicense: CC BY-SA 2.5

Title: Question on using List

Body:
I created an List like this

List<Dictionary<DicKeyCla, DicValCla>>

public Class DicKeyCla
{
   public EnKey1 DicKeyItem1,
   public EnKey2 DicKeyItem2,
}

public enum EnKey1
{
   A1,
   A2,
   A3,
   A4,
   A5
}

public enum EnKey2
{
   B11,
   B12,
   B13,
   B14,
   B15,
   B16,
   B17,
   B18,
   B19,
}

As I know, there is contains() method available for List class.

If I called an function which argues contain the DicKeyCla members like A3 and B15.

How can I pick out the entirely dictionary member from the Top level List rapidly?

I need do more operation on dictionary member.


问:
Using QtAV in qml
I am trying to use QtAV library in QML following the instructions at this link https://github.com/wang-bin/QtAV/wiki/Deploy-SDK-Without-Building-QtAV. I have managed to successfully build the project, but I am unable to use the module in QML. In my .pro file I have QT += av avwidgets, then in my qml file I have import QtAV 1.6. I get the following error: QtAV module not installed.

答:
In your qml file instead of

```<code>import QtAV 1.6
</code>```

point to your QtAV qml directory by this line

```<code>import "[QtAVSourceCodePath]/qml"
</code>```

Then make your project again and try to rerun your program

Title: Using QtAV in qml

Body:
In your qml file instead of

import QtAV 1.6

point to your QtAV qml directory by this line

import "[QtAVSourceCodePath]/qml"

Then make your project again and try to rerun your program


问:
codeigniter 404 Page on Item view Page custom issue
i am new in CI and facing issue with url for 404 page
http://www.sogoteleshopping.com/product/50/herbal-madhunashni when i access
http://www.sogoteleshopping.com/product/50/herbal-madhunashni_test redirect on same i want 404 here please help me.

$route['product/(:any)'] = "home/product_details/$1";

答:
You have to separate all the segments and use variables for the method $1/$2/$3 etc

For your example, you would need to do:

```<code>$route['product/(:num)/(:any)'] = "home/product_details/$1/$2";
</code>```

Using (:num) for only [0-9]+ (on your product id segment)

--

Within your home.php and method of product_details() will use as such:

```<code>public function product_details($id, $name) {

}
</code>```

For more information on routing refer to the CI docs:

https://www.codeigniter.com/user_guide/general/routing.html?highlight=routing

Body:
You have to separate all the segments and use variables for the method $1/$2/$3 etc

For your example, you would need to do:

$route['product/(:num)/(:any)'] = "home/product_details/$1/$2";

Using (:num) for only [0-9]+ (on your product id segment)

--

Within your home.php and method of product_details() will use as such:

public function product_details($id, $name) {

}

For more information on routing refer to the CI docs:

https://www.codeigniter.com/user_guide/general/routing.html?highlight=routing


答:
"please print first element of each array with the help of one forEach
  loop"

Finally, a definition of the problem! Do this:

```<code>for (int[] pro : a ){
    System.out.println(pro[0]);
}
</code>```

Title: for each loop in java not working with a array that changes as loop progresses

Body:
"please print first element of each array with the help of one forEach
  loop"

Finally, a definition of the problem! Do this:

for (int[] pro : a ){
    System.out.println(pro[0]);
}


问:
Bootstrap-table css not loading after ajax call
i'm having trouble loading CSS to bootstrap-table after I call it by Ajax.

This table is appended to my view by Ajax for each click event fired, but the bootstrap-table CSS hasn't been loaded to each one:

```<code><div id="sala_2">
  <h3>Sala 2</h3>
  <table id="tb_sala_2"
     data-toggle="table"
     data-toolbar="#toolbar"
     data-click-to-select="true"
     data-single-select="true">
    <thead>
      <tr>
        <th data-field="state" data-checkbox="true" data-halign="center" data-align="center"></th>
        <th data-field="id" data-halign="center" data-align="center">ID</th>
        <th data-field="cargo_id" class="hidden_field" data-halign="center" data-align="center">Cargo ID</th>
        <th data-field="cargo" data-halign="center" data-align="center">Cargo</th>
        <th data-field="quantidade_de_candidatos" data-halign="center" data-align="center">Quantidade de candidatos</th>
      </tr>
    </thead>
    <tbody>
        <% i = 0 %>
        <% @cargos.each do |cargo| %>
          <tr>
            <td></td>
            <td><%= i %></td>
            <% i = i + 1 %>
            <td class="hidden_field"><%= cargo.id %></td>
            <td><%= cargo.nome %></td>
            <td class="quantidade_de_candidatos"> 0 </td>
          </tr>
       <% end %>
   </tbody>
 </table>
</div>
</code>```

Application.js:

```<code>//= require jquery
//= require jquery_ujs
//= require bootstrap-table
//= require turbolinks
//= require_tree .
</code>```

Application.css:

```<code>*= require bootstrap-table
*= require_tree .
*= require_self
</code>```

Observation: When the page is loaded for the first time, the bootstrap-table CSS has been loaded right. The problem happen when I use ajax to append another table. So, I believe that the issue is the way rails works loading assets.

答:
You can try with loadCss.js lib asynchronously.

git https://github.com/filamentgroup/loadCSS

Usage: loadCSS( "path/to/mystylesheet.css" );

Body:
i'm having trouble loading CSS to bootstrap-table after I call it by Ajax.

This table is appended to my view by Ajax for each click event fired, but the bootstrap-table CSS hasn't been loaded to each one:

Sala 2

        ID
        Cargo ID
        Cargo
        Quantidade de candidatos

        <% i = 0 %>
        <% @cargos.each do |cargo| %>

            <%= i %>
            <% i = i + 1 %>
            <%= cargo.id %>
            <%= cargo.nome %>
             0

       <% end %>

Application.js:

//= require jquery
//= require jquery_ujs
//= require bootstrap-table
//= require turbolinks
//= require_tree .

Application.css:

*= require bootstrap-table
*= require_tree .
*= require_self

Observation: When the page is loaded for the first time, the bootstrap-table CSS has been loaded right. The problem happen when I use ajax to append another table. So, I believe that the issue is the way rails works loading assets.


问:
Android Studio icons such as AVD, Run, debug, etc are unavailable (grey)
Pretty much what the title says. I am sorry if the question seems naive, but today is the first day I am starting learning android development and I am extremely unfamiliar with this feature-heavy IDE as of yet.</p>

答:
press Alt+u or Click Run on the menu, then select 'Edit Configuration' option.
then click on Android Application on the left and click the on top-left + button.
Choose Android Application from the pop-up menu. after that select module like app then click on apply and ok.</p>


问:
Use grunt-browser-sync to watch changes in jsp and tag files
I'm trying to use the grunt-browser-sync to watch the changes in the jsp and tag files, but the same is not working. Does anybody know what`s happening?
Grunt works with tag and jsp files?</p>

```<code> module.exports = function(grunt) {
   // Project configuration.
   grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        watch: {
           // hide code
        },
        less: {
           // hide code
        },
        // hide code
        browserSync: {
            default_options: {
                bsFiles: {
                    src: ["**/*.js", "*/*.css", "**/*.jsp", "**/*.tag" ]
                },
                options: {
                    watchTask: true,
                    proxy: "https://pageteste.local:9001/sitedeteste"
                }
            }
        }
    });

    // Plugins
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks("grunt-browser-sync");

    // Browser sync task
    grunt.registerTask("server", ["browserSync", "watch"]);

    // Default task(s).
    grunt.registerTask('default', ['less', 'sprite', 'sync']);

};
</code>```

答:
I need change my code path for this:</p>

```<code>bsFiles: {
    src: [
        "web/path/**/*.js",
        "web/path/css/style.css",
        "web/**/*.jsp",
        "web/webroot/path/**/*.tag",
    ]
},
</code>```

Body:
I'm trying to use the grunt-browser-sync to watch the changes in the jsp and tag files, but the same is not working. Does anybody know what`s happening?
Grunt works with tag and jsp files?

 module.exports = function(grunt) {
   // Project configuration.
   grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        watch: {
           // hide code
        },
        less: {
           // hide code
        },
        // hide code
        browserSync: {
            default_options: {
                bsFiles: {
                    src: ["**/*.js", "*/*.css", "**/*.jsp", "**/*.tag" ]
                },
                options: {
                    watchTask: true,
                    proxy: "https://pageteste.local:9001/sitedeteste"
                }
            }
        }
    });

    // Plugins
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks("grunt-browser-sync");

    // Browser sync task
    grunt.registerTask("server", ["browserSync", "watch"]);

    // Default task(s).
    grunt.registerTask('default', ['less', 'sprite', 'sync']);

};

Body:
I need change my code path for this:

bsFiles: {
    src: [
        "web/path/**/*.js",
        "web/path/css/style.css",
        "web/**/*.jsp",
        "web/webroot/path/**/*.tag",
    ]
},


问:
Hive select data into an array of structs
I am trying to figure out a way in Hive to select data from a flat source and output into an array of named struct(s). Here is a example of what I am looking for...

Sample Data:

```<code>house_id,first_name,last_name
1,bob,jones
1,jenny,jones
2,sally,johnson
3,john,smith
3,barb,smith
</code>```

Desired Output:

```<code>1   [{"first_name":"bob","last_name":"jones"},{"first_name":"jenny","last_name":"jones"}]
2   [{"first_name":"sally","last_name":"johnson"}]
3   [{"first_name":"john","last_name":"smith"},{"first_name":"barb","last_name":"smith"}]
</code>```

I tried collect_list and collect_set but they only allow primitive data types. Any thoughts of how I might go about this in Hive?

答:
You can also use a workaround </p>

```<code>select collect_list(full_name) full_name_list from (
    select
        concat_ws(',',
            concat("first_name:",first_name),
            concat("last_name:",last_name)
            ) full_name,
        house_id
    from house) a
group by house_id
</code>```

Body:
I am trying to figure out a way in Hive to select data from a flat source and output into an array of named struct(s). Here is a example of what I am looking for...

Sample Data:

house_id,first_name,last_name
1,bob,jones
1,jenny,jones
2,sally,johnson
3,john,smith
3,barb,smith

Desired Output:

1   [{"first_name":"bob","last_name":"jones"},{"first_name":"jenny","last_name":"jones"}]
2   [{"first_name":"sally","last_name":"johnson"}]
3   [{"first_name":"john","last_name":"smith"},{"first_name":"barb","last_name":"smith"}]

I tried collect_list and collect_set but they only allow primitive data types. Any thoughts of how I might go about this in Hive?

Body:
You can also use a workaround

select collect_list(full_name) full_name_list from (
    select
        concat_ws(',',
            concat("first_name:",first_name),
            concat("last_name:",last_name)
            ) full_name,
        house_id
    from house) a
group by house_id


问:
Magento files: where to paste and read results of this query
I am giving up on trying to fetch values for all product attributes on magento by SQL as it gets a nightmare of joins, yet, I am not familiar with the folders structure and I dont know where to paste this query below. Could anyone give me a handguided enumeration on where to go please? If possible I d like to have more values, like description, meta keywords etc</p>

```<code><?php
require_once 'app/Mage.php';
umask(0);
Mage::app('default');

$collection = Mage::getModel('catalog/product')->getCollection();

echo '<table border="1"> ';
echo '<tr>';
echo "<th>entity_id <th />";
echo "<th>store_id <th />";
echo "<th>name<th />";
echo "<th>sku <th />";
echo "<th>price<th />";
echo "<th>status<th />";
echo '</tr>';

foreach ($collection as $product_all) {
  $sku = $product_all['sku'];
  $product_id =  $product_all['entity_id'];
  // call product model and create product object
  $product    = Mage::getModel('catalog/product')->load($product_id);

  $pk_sku = $product['sku'];
  $pk_name = $product['name'];
  $store_id = $product->getStoreIds();
  $pk_price = $product['price'];
  $status = $product->getStatus();

  echo '<tr>';
  echo "<td>".$product_id."<td />";
  echo "<td>".$store_id[0]."<td />";
  echo "<td>".$pk_name."<td />";
  echo "<td>".$pk_sku."<td />";
  echo "<td>".$pk_price."<td />";
  echo "<td>".$status."<td />";
  echo '</tr>';
 }
echo '</table>';?>
</code>```

答:
If you want to see product attribute data, these are the tables in the db you need to concern yourself with.

catalog_product_entity: stores all base product data

eav_attribute: lists all attribute_codes and the attribute type

catalog_product_entity_{varchar/int/datetime/..}: contains relevant attribute values based on eav_attribute attribute_id and catalog_product_entity entity_id.

So if you wanted to use a SQL query to get a certain attribute, you could use a statement like this to view all varchar attributes stored for a particular product (or all products):

```<code>SELECT cpe.entity_id, cpe.sku,  attrib.attribute_id, attrib.value
FROM catalog_product_entity AS cpe
LEFT JOIN (
    SELECT entity_id, attribute_id, VALUE
    FROM catalog_product_entity_varchar AS attrib
) AS attrib ON cpe.entity_id = attrib.entity_id
WHERE cpe.sku = '{your sku here}';
</code>```

With these tables and a little more research into the eav system and a little sql knowledge, you should be able to wrap your head around how the system works and see the data you need.

Body:
I am giving up on trying to fetch values for all product attributes on magento by SQL as it gets a nightmare of joins, yet, I am not familiar with the folders structure and I dont know where to paste this query below. Could anyone give me a handguided enumeration on where to go please? If possible I d like to have more values, like description, meta keywords etc

<?php
require_once 'app/Mage.php';
umask(0);
Mage::app('default');

$collection = Mage::getModel('catalog/product')->getCollection();

echo '
 ';
echo '
';
echo "entity_id ";
echo "store_id ";
echo "name";
echo "sku ";
echo "price";
echo "status";
echo '
';

foreach ($collection as $product_all) {
  $sku = $product_all['sku'];
  $product_id =  $product_all['entity_id'];
  // call product model and create product object
  $product    = Mage::getModel('catalog/product')->load($product_id);

  $pk_sku = $product['sku'];
  $pk_name = $product['name'];
  $store_id = $product->getStoreIds();
  $pk_price = $product['price'];
  $status = $product->getStatus();

  echo '
';
  echo "".$product_id."";
  echo "".$store_id[0]."";
  echo "".$pk_name."";
  echo "".$pk_sku."";
  echo "".$pk_price."";
  echo "".$status."";
  echo '
';
 }
echo '
';?>

Body:
If you want to see product attribute data, these are the tables in the db you need to concern yourself with.

catalog_product_entity: stores all base product data

eav_attribute: lists all attribute_codes and the attribute type

catalog_product_entity_{varchar/int/datetime/..}: contains relevant attribute values based on eav_attribute attribute_id and catalog_product_entity entity_id.

So if you wanted to use a SQL query to get a certain attribute, you could use a statement like this to view all varchar attributes stored for a particular product (or all products):

SELECT cpe.entity_id, cpe.sku,  attrib.attribute_id, attrib.value
FROM catalog_product_entity AS cpe
LEFT JOIN (
    SELECT entity_id, attribute_id, VALUE
    FROM catalog_product_entity_varchar AS attrib
) AS attrib ON cpe.entity_id = attrib.entity_id
WHERE cpe.sku = '{your sku here}';

With these tables and a little more research into the eav system and a little sql knowledge, you should be able to wrap your head around how the system works and see the data you need.


问:
Java: Strange result after decompiling
I have a strange jar file, it contains some class that when I use JD Decompiler, it show a segment like this:

```<code>public final void a(ak aa) {
    this.jdField_a_of_type_Ak = aa;
}

public final void a(cn ccn) {
  this.jdField_a_of_type_Cn = ccn;
}

public final cN a() {
  return this.jdField_a_of_type_CN;
}

public final void a() {
  super.b();
}

public final boolean a() {
    return this.jdField_a_of_type_Boolean;
}
</code>```

I just wonder why a/an compiler/obfuscator can product a class byte code like that, I mean the method signature. Did any one know a obfuscator can do this?

答:
The class has been compiled without debugging information (at least local variable information is missing) and obfuscated later.

One basic obfuscating strategy is to replace (nearly) all package, class and methodnames by new, senseless names, so that one can't understand the decompiled code.

Additional strategies are obfuscating strings and adding bytecode constructs that can't be decompiled to java code.

You'll still be able to create a java source equivalent for the obfuscated class file but only with great effort.

Title: Java: Strange result after decompiling

Body:
I have a strange jar file, it contains some class that when I use JD Decompiler, it show a segment like this:

public final void a(ak aa) {
    this.jdField_a_of_type_Ak = aa;
}

public final void a(cn ccn) {
  this.jdField_a_of_type_Cn = ccn;
}

public final cN a() {
  return this.jdField_a_of_type_CN;
}

public final void a() {
  super.b();
}

public final boolean a() {
    return this.jdField_a_of_type_Boolean;
}

I just wonder why a/an compiler/obfuscator can product a class byte code like that, I mean the method signature. Did any one know a obfuscator can do this?


问:
How to get closest n rows for specific row in table?
I have a table foo with its primary key id and some other columns.
My goal is to find for instance rows with id=3 and id=4 and rows with id=6 and id=7 for row with id=5 - in case I would like to find 2 closest previous and next rows.

In case there is only one or no such rows (e.g. for id=2 there is only previous row) I would like to get only possible ones.

The problem is there can be some rows missing.

Is there a common practice to make such queries?

答:
One way is this:

```<code>with your_table(id) as(
    select 1 union all
    select 2 union all
    select 4 union all
    select 5 union all
    select 10 union all
    select 11 union all
    select 12 union all
    select 13 union all
    select 14
)

select * from (
    (select * from your_table where id <= 10 order by id desc limit 3+1)
    union all
    (select * from your_table where id > 10 order by id limit 3)
) t
order by id
</code>```

(Here 10 is start point and 3 is n rows you want)

Body:
One way is this:

with your_table(id) as(
    select 1 union all
    select 2 union all
    select 4 union all
    select 5 union all
    select 10 union all
    select 11 union all
    select 12 union all
    select 13 union all
    select 14
)

select * from (
    (select * from your_table where id <= 10 order by id desc limit 3+1)
    union all
    (select * from your_table where id > 10 order by id limit 3)
) t
order by id

(Here 10 is start point and 3 is n rows you want)


问:
Connect with ssh to docker daemon on Windows
I installed Docker Desktop for Windows on Windows 10 with https://docs.docker.com/docker-for-windows/install/#install-docker-for-windows. It not uses VirtualBox and default VM to host docker.

I am able to run containers but how I connect to a docker with ssh?

docker-machine ls does not show my docker host.

Tried to connect to docker@10.0.75.1 but it requires password. And tcuser that  used for boot2docker VM not matching:

ssh docker@10.0.75.1 Could not create directory '/home/stan/.ssh'. The
  authenticity of host '10.0.75.1 (10.0.75.1)' can't be established. RSA
  key fingerprint is .... Are you sure you want to continue connecting
  (yes/no)? yes Failed to add the host to the list of known hosts
  (/home/stan/.ssh/known_hosts). docker@10.0.75.1's password: Write
  failed: Connection reset by peer

答: As far as I know you can't connect to the docker VM using SSH and you cannot connect to the console/terminal using Hyper-V Manager either. https://forums.docker.com/t/how-can-i-ssh-into-the-betas-mobylinuxvm/10991/17</p>

ContentLicense: CC BY-SA 4.0


问:
java.lang.NoSuchMethodError: No virtual method setTag(Ljava/lang/Object;)
I just finish my codes for using log in and registration screen with volley

but on running in emulator i get this error

```<code>java.lang.NoSuchMethodError: No virtual method setTag(Ljava/lang/Object;)Lcom/android/volley/Request; in class Lcom/android/volley/Request; or its super classes (declaration of 'com.android.volley.Request' appears in /data/app/com.dreacot.street_crime-2/split_lib_dependencies_apk.apk:classes10.dex)
</code>```

according to the debug these are the files with issues

please can anyone tell me what i am doing wrong?

AppController.java

```<code>public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}
}
</code>```

SignUpActivity.java

```<code>public class SignupActivity extends Activity {

private static final String TAG = SignupActivity.class.getSimpleName();
Button regbutton;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private SessionManager session;
private SQLiteHandler db;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set View to register.xml
    setContentView(R.layout.activity_register);

    inputFullName = (EditText) findViewById(R.id.reg_username);
    inputEmail = (EditText) findViewById(R.id.reg_email);
    inputPassword = (EditText) findViewById(R.id.reg_password);

    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(SignupActivity.this,
                AfterLogin.class);
        startActivity(intent);
        finish();
    }

    addListenerOnButton();

    TextView loginScreen = (TextView) findViewById(R.id.link_to_login);

    // Listening to Login Screen link
    loginScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // Closing registration screen
            // Switching to Login Screen/closing register screen
            finish();
        }
    });

}

public void addListenerOnButton() {

    regbutton = (Button) findViewById(R.id.btnRegister);

    regbutton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            String name = inputFullName.getText().toString().trim();
            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerUser(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });
}
/**
 * Function to store user in MySQL database will post params(tag, name,
 * email, password) to register url
 * */
private void registerUser(final String name, final String email,
                          final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_register";

    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_REGISTER, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Register Response: " + response.toString());

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (!error) {
                    // User successfully stored in MySQL
                    // Now store the user in sqlite
                    String uid = jObj.getString("uid");

                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user
                            .getString("created_at");

                    // Inserting row in users table
                    db.addUser(name, email, uid, created_at);

                    Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();

                    // Launch login activity
                    Intent intent = new Intent(
                            SignupActivity.this,
                            LoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {

                    // Error occurred in registration. Get the error
                    // message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Registration Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
</code>```

Log

```<code>06-05 15:38:27.457 28919-28919/com.dreacot.street_crime E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: com.dreacot.street_crime, PID: 28919
                                                                      java.lang.NoSuchMethodError: No virtual method setTag(Ljava/lang/Object;)Lcom/android/volley/Request; in class Lcom/android/volley/Request; or its super classes (declaration of 'com.android.volley.Request' appears in /data/app/com.dreacot.street_crime-2/split_lib_dependencies_apk.apk:classes10.dex)
                                                                          at com.dreacot.street_crime.app.AppController.addToRequestQueue(AppController.java:37)
                                                                          at com.dreacot.street_crime.other.SignupActivity.registerUser(SignupActivity.java:181)
                                                                          at com.dreacot.street_crime.other.SignupActivity.access$300(SignupActivity.java:31)
                                                                          at com.dreacot.street_crime.other.SignupActivity$2.onClick(SignupActivity.java:94)
                                                                          at android.view.View.performClick(View.java:5610)
                                                                          at android.view.View.onKeyUp(View.java:10581)
                                                                          at android.widget.TextView.onKeyUp(TextView.java:6435)
                                                                          at android.view.KeyEvent.dispatch(KeyEvent.java:2700)
                                                                          at android.view.View.dispatchKeyEvent(View.java:9880)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at android.widget.ScrollView.dispatchKeyEvent(ScrollView.java:379)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:403)
                                                                          at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1800)
                                                                          at android.app.Activity.dispatchKeyEvent(Activity.java:3021)
                                                                          at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:317)
                                                                          at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4327)
                                                                          at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4298)
                                                                          at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
                                                                          at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3902)
                                                                          at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3868)
                                                                          at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3995)
                                                                          at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3876)
                                                                          at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4052)
                                                                          at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
                                                                          at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3902)
                                                                          at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3868)
                                                                          at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3876)
                                                                          at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
                                                                          at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6210)
                                                                          at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6184)
                                                                          at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6145)
                                                                          at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3647)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

答:
I had two Volley dependencies in my gradle dependencies so i guess thats what caused it all

```<code>compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
</code>```

i just took this one out

```<code>compile 'com.mcxiaoke.volley:library:1.0.19'
</code>```

now everything works fine

Body:
I just finish my codes for using log in and registration screen with volley

but on running in emulator i get this error

java.lang.NoSuchMethodError: No virtual method setTag(Ljava/lang/Object;)Lcom/android/volley/Request; in class Lcom/android/volley/Request; or its super classes (declaration of 'com.android.volley.Request' appears in /data/app/com.dreacot.street_crime-2/split_lib_dependencies_apk.apk:classes10.dex)

according to the debug these are the files with issues

please can anyone tell me what i am doing wrong?

AppController.java

public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}
}

SignUpActivity.java

public class SignupActivity extends Activity {

private static final String TAG = SignupActivity.class.getSimpleName();
Button regbutton;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private SessionManager session;
private SQLiteHandler db;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set View to register.xml
    setContentView(R.layout.activity_register);

    inputFullName = (EditText) findViewById(R.id.reg_username);
    inputEmail = (EditText) findViewById(R.id.reg_email);
    inputPassword = (EditText) findViewById(R.id.reg_password);

    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(SignupActivity.this,
                AfterLogin.class);
        startActivity(intent);
        finish();
    }

    addListenerOnButton();

    TextView loginScreen = (TextView) findViewById(R.id.link_to_login);

    // Listening to Login Screen link
    loginScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // Closing registration screen
            // Switching to Login Screen/closing register screen
            finish();
        }
    });

}

public void addListenerOnButton() {

    regbutton = (Button) findViewById(R.id.btnRegister);

    regbutton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            String name = inputFullName.getText().toString().trim();
            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerUser(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });
}
/**
 * Function to store user in MySQL database will post params(tag, name,
 * email, password) to register url
 * */
private void registerUser(final String name, final String email,
                          final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_register";

    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_REGISTER, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Register Response: " + response.toString());

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (!error) {
                    // User successfully stored in MySQL
                    // Now store the user in sqlite
                    String uid = jObj.getString("uid");

                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user
                            .getString("created_at");

                    // Inserting row in users table
                    db.addUser(name, email, uid, created_at);

                    Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();

                    // Launch login activity
                    Intent intent = new Intent(
                            SignupActivity.this,
                            LoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {

                    // Error occurred in registration. Get the error
                    // message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Registration Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}

Log

06-05 15:38:27.457 28919-28919/com.dreacot.street_crime E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: com.dreacot.street_crime, PID: 28919
                                                                      java.lang.NoSuchMethodError: No virtual method setTag(Ljava/lang/Object;)Lcom/android/volley/Request; in class Lcom/android/volley/Request; or its super classes (declaration of 'com.android.volley.Request' appears in /data/app/com.dreacot.street_crime-2/split_lib_dependencies_apk.apk:classes10.dex)
                                                                          at com.dreacot.street_crime.app.AppController.addToRequestQueue(AppController.java:37)
                                                                          at com.dreacot.street_crime.other.SignupActivity.registerUser(SignupActivity.java:181)
                                                                          at com.dreacot.street_crime.other.SignupActivity.access$300(SignupActivity.java:31)
                                                                          at com.dreacot.street_crime.other.SignupActivity$2.onClick(SignupActivity.java:94)
                                                                          at android.view.View.performClick(View.java:5610)
                                                                          at android.view.View.onKeyUp(View.java:10581)
                                                                          at android.widget.TextView.onKeyUp(TextView.java:6435)
                                                                          at android.view.KeyEvent.dispatch(KeyEvent.java:2700)
                                                                          at android.view.View.dispatchKeyEvent(View.java:9880)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at android.widget.ScrollView.dispatchKeyEvent(ScrollView.java:379)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
                                                                          at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:403)
                                                                          at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1800)
                                                                          at android.app.Activity.dispatchKeyEvent(Activity.java:3021)
                                                                          at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:317)
                                                                          at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4327)
                                                                          at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4298)
                                                                          at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
                                                                          at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3902)
                                                                          at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3868)
                                                                          at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3995)
                                                                          at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3876)
                                                                          at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4052)
                                                                          at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
                                                                          at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3902)
                                                                          at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3868)
                                                                          at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3876)
                                                                          at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
                                                                          at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6210)
                                                                          at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6184)
                                                                          at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6145)
                                                                          at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3647)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Body:
I had two Volley dependencies in my gradle dependencies so i guess thats what caused it all

compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'

i just took this one out

compile 'com.mcxiaoke.volley:library:1.0.19'

now everything works fine


问:
How to host socket.io on website hosting?
Hello I already create 2 Dimension online game client and server and I want to test it by uploading server and client on the internet, because now I load everything on xampp and nodejs localhost:8080. Maybe someone know how to put it on web hosting.

THANKS :)

答:
There are many options to host a website. If you don't want to use your own virtual server that you will have to configure, you can use heroku. Else you could try hosting on Digital Ocean. They are vps providers, you should have some knowledge of linux to do that or simply use google. There are many digital ocean tutorials on how to install nodeJS on the vps and configure it for production. I recommend reading this guide: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-16-04. The pros of using a vps is simply more resources for the same price and more functionality in the future.

Bare in mind that socket.io is also using websockets instead of just HTTP. If you choose to try and host it on your very own machine, you will have to add some configuration to your nginx server. The basics options required inside the configuration of the server are:

```<code>proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
</code>```

Body:
There are many options to host a website. If you don't want to use your own virtual server that you will have to configure, you can use heroku. Else you could try hosting on Digital Ocean. They are vps providers, you should have some knowledge of linux to do that or simply use google. There are many digital ocean tutorials on how to install nodeJS on the vps and configure it for production. I recommend reading this guide: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-16-04. The pros of using a vps is simply more resources for the same price and more functionality in the future.

Bare in mind that socket.io is also using websockets instead of just HTTP. If you choose to try and host it on your very own machine, you will have to add some configuration to your nginx server. The basics options required inside the configuration of the server are:

proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";


问:
What is the best way to check if a URL exists in PHP?
What is the best way to see a URL exists and the response is not a 404 ?</p>

答:
You can use get_headers($url)

Example 2 from Manual:

```<code><?php
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);
print_r(get_headers('http://example.com'));

// gives
Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)
</code>```

The first array element will contain the HTTP Response Status code. You have to parse that.

Note that the get_headers function in the example will issue an HTTP HEAD request, which means it will not fetch the body of the URL. This is more efficient than using a GET request which will also return the body.

Also note that by setting a default context, any subsequent calls using an http stream context, will now issue HEAD requests. So make sure to reset the default context to use GET again when done.

PHP also provides the variable $http_response_header

The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers. $http_response_header will be created in the local scope.

If you want to download the content of a remote resource, you don't want to do two requests (one to see if the resource exists and one to fetch it), but just one. In that case, use something like file_get_contents to fetch the content and then inspect the headers from the variable.

Body:
You can use get_headers($url)

Example 2 from Manual:

<?php
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);
print_r(get_headers('http://example.com'));

// gives
Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

The first array element will contain the HTTP Response Status code. You have to parse that.

Note that the get_headers function in the example will issue an HTTP HEAD request, which means it will not fetch the body of the URL. This is more efficient than using a GET request which will also return the body.

Also note that by setting a default context, any subsequent calls using an http stream context, will now issue HEAD requests. So make sure to reset the default context to use GET again when done.

PHP also provides the variable $http_response_header

The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers. $http_response_header will be created in the local scope.

If you want to download the content of a remote resource, you don't want to do two requests (one to see if the resource exists and one to fetch it), but just one. In that case, use something like file_get_contents to fetch the content and then inspect the headers from the variable.


问:
GetTypeInfo().Assembly.Location .net core
Using VS2017 .net core 1.4 I can get the line of code

```<code>var z = typeof(object).GetTypeInfo().Assembly.Location;
</code>```

to compile if it is in my application project using the Microsoft.NetCore.App SDK.
However, it does not compile when in the Standard class project using the NETStandard.Library SDK.

Similar issues with referencing the System.Runtime.Loader assembly.

Any ideas to to how to overcome this.

Thanks
Martin

答: The Location property of System.Reflection.Assembly is only available in .NET Standard 1.5 and higher. So it cannot be used in a netstandard1.4 project.

Body:
Using VS2017 .net core 1.4 I can get the line of code

var z = typeof(object).GetTypeInfo().Assembly.Location;

to compile if it is in my application project using the Microsoft.NetCore.App SDK.
However, it does not compile when in the Standard class project using the NETStandard.Library SDK.

Similar issues with referencing the System.Runtime.Loader assembly.

Any ideas to to how to overcome this.

Thanks
Martin


问:
R - how to index rank and accordingly display a data frame?
I have a data frame that lists down some names of individuals and their monetary transactions carried out in USD. The table lists down data according to several districts and the valid transactions made by either cash or credit cards, like so:

```<code>X    Dist    transact.cash    transact.card
a    1       USD              USD
b    1       USD              USD
</code>```

Where X is an individual and his/her transactions for a period of time keeping that period fixed and Dist is the district where he/she resides. There are over 4000 observations in total for an approx. 80-100 rows per Dist. So far, the sorting, slicing and everything else have been simple operations with dat.cash and dat.card being subsetted tables according to mode of transaction; but I'm having problems when extracting information in reference to ranking the dataset. For this, I have written a function where I specify a rank and the function should show those rows starting from that rank:

```<code>rankdat <- function(transact, numb) {
               # Truncated
                 valid.nums = c('highest', 'lowest', 1:nrow(dat.cash)) # for cash subset
                     if (transact == 'cash' && numb == 'highest') { # This is easy
                 sort <- dat.cash[order(dat.cash[, 3], decreasing = T), ]# For sorting only cash data set
                  } else if (transact == 'cash' and numb == 1:nrow(dat.cash)) {
                 sort <- dat.cash[order(dat.cash[, 3], decreasing = T) == numb, ] } # Not getting results here
                 }
</code>```

The last line is returning NULL instead of a ranked transaction and all its rows. Replacing == with %in% still gives NULL and using rank() doesn't change anything. For highest and lowest numbers, its not a great deal since it only involves simple sorting. If I specify rankdat('cash', 10), the function should return values starting from the 10th highest transaction and decreasing irrespective of Dist, similar to:

```<code> X    Dist    transact.cash
 b    1       10th highest
 h    2       11th highest
 p    1       12th highest
 and  so      on
</code>```

答:
Suppose that you have the following data.frame:

```<code>df=data.frame(X=c(rep('A',2),rep('B',3),rep('A',3),rep('B',2)),
               Dist=c(rep(1,5),rep(0,5)),
               transact.cash=c(rep('USD',5),rep('€',5)),
               transact.card=c(rep('USD',5),rep('€',5)))
</code>```

We obtain:

```<code>   X Dist transact.cash transact.card
1  A    1           USD           USD
2  A    1           USD           USD
3  B    1           USD           USD
4  B    1           USD           USD
5  B    1           USD           USD
6  A    0             €             €
7  A    0             €             €
8  A    0             €             €
9  B    0             €             €
10 B    0             €             €
</code>```

If you would like to sort a dataframe with multiple columns transact.cash or transact.cash you can used stackoverflow : How to sort a dataframe by column(s). In your example, you only specified dat.cash, thus :

```<code>sort = df[order(df$transact.cash, decreasing=T),] # Order your dataFrame with transact.cash column
</code>```

If you want to extract rows which respect a specific statement, you need to use which() and == for numeric, double, logical match or %in% for string match. For example:

```<code>XA = df[which(df$X %in% "A"),] # Select row by user
XDist = df[which(df$Dist == 1),] # Select row by District
</code>```

Finally, if you would like to select the first five row after ordering:

```<code>sort[1:5,] # Select first five rows
sort[1:numb,] # Select first numb rows
</code>```

With that you can perform a simple function to easily extract data from your dataframe.

Hope it will help you

Body:
I have a data frame that lists down some names of individuals and their monetary transactions carried out in USD. The table lists down data according to several districts and the valid transactions made by either cash or credit cards, like so:

X    Dist    transact.cash    transact.card
a    1       USD              USD
b    1       USD              USD

Where X is an individual and his/her transactions for a period of time keeping that period fixed and Dist is the district where he/she resides. There are over 4000 observations in total for an approx. 80-100 rows per Dist. So far, the sorting, slicing and everything else have been simple operations with dat.cash and dat.card being subsetted tables according to mode of transaction; but I'm having problems when extracting information in reference to ranking the dataset. For this, I have written a function where I specify a rank and the function should show those rows starting from that rank:

rankdat <- function(transact, numb) {
               # Truncated
                 valid.nums = c('highest', 'lowest', 1:nrow(dat.cash)) # for cash subset
                     if (transact == 'cash' && numb == 'highest') { # This is easy
                 sort <- dat.cash[order(dat.cash[, 3], decreasing = T), ]# For sorting only cash data set
                  } else if (transact == 'cash' and numb == 1:nrow(dat.cash)) {
                 sort <- dat.cash[order(dat.cash[, 3], decreasing = T) == numb, ] } # Not getting results here
                 }

The last line is returning NULL instead of a ranked transaction and all its rows. Replacing == with %in% still gives NULL and using rank() doesn't change anything. For highest and lowest numbers, its not a great deal since it only involves simple sorting. If I specify rankdat('cash', 10), the function should return values starting from the 10th highest transaction and decreasing irrespective of Dist, similar to:

 X    Dist    transact.cash
 b    1       10th highest
 h    2       11th highest
 p    1       12th highest
 and  so      on

Body:
Suppose that you have the following data.frame:

df=data.frame(X=c(rep('A',2),rep('B',3),rep('A',3),rep('B',2)),
               Dist=c(rep(1,5),rep(0,5)),
               transact.cash=c(rep('USD',5),rep('€',5)),
               transact.card=c(rep('USD',5),rep('€',5)))

We obtain:

   X Dist transact.cash transact.card
1  A    1           USD           USD
2  A    1           USD           USD
3  B    1           USD           USD
4  B    1           USD           USD
5  B    1           USD           USD
6  A    0             €             €
7  A    0             €             €
8  A    0             €             €
9  B    0             €             €
10 B    0             €             €

If you would like to sort a dataframe with multiple columns transact.cash or transact.cash you can used stackoverflow : How to sort a dataframe by column(s). In your example, you only specified dat.cash, thus :

sort = df[order(df$transact.cash, decreasing=T),] # Order your dataFrame with transact.cash column

If you want to extract rows which respect a specific statement, you need to use which() and == for numeric, double, logical match or %in% for string match. For example:

XA = df[which(df$X %in% "A"),] # Select row by user
XDist = df[which(df$Dist == 1),] # Select row by District

Finally, if you would like to select the first five row after ordering:

sort[1:5,] # Select first five rows
sort[1:numb,] # Select first numb rows

With that you can perform a simple function to easily extract data from your dataframe.

Hope it will help you


问:
NullReferenceException on DisplayRootViewFor<>
I've created a class derived from BootstrapperBase, overwrote OnStartup() and call DisplayRootViewFor<AppViewModel>() just like in the documentation.

But when i start the app, i get a NullReferenceException on DisplayRooViewFor<AppViewModel>()

```<code>using Caliburn.Micro;
using MHBRestore.Logic;
using MHBRestore.UI.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MHBRestore.UI
{
public class AppBootstrapper : BootstrapperBase
{
    private SimpleContainer _container = new SimpleContainer();

    public AppBootstrapper()
    {
        Initialize();
    }

    protected override void OnStartup(object sender, StartupEventArgs e)
    {
        DisplayRootViewFor<AppViewModel>();
    }

    protected override object GetInstance(Type service, string key)
    {
        return _container.GetInstance(service, key);
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return _container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance)
    {
        _container.BuildUp(instance);
    }
}
}
</code>```

答:
Try to override the Configure method and register your view model type:

```<code>public class AppBootstrapper : BootstrapperBase
{
    private SimpleContainer _container = new SimpleContainer();

    public AppBootstrapper()
    {
        Initialize();
    }

    protected override void Configure()
    {
        _container.Singleton<IWindowManager, WindowManager>();
        _container.Singleton<IEventAggregator, EventAggregator>();
        _container.RegisterPerRequest(typeof(AppViewModel), null, typeof(AppViewModel));
    }

    protected override void OnStartup(object sender, StartupEventArgs e)
    {
        DisplayRootViewFor<AppViewModel>();
    }

    protected override object GetInstance(Type service, string key)
    {
        return _container.GetInstance(service, key);
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return _container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance)
    {
        _container.BuildUp(instance);
    }
}
</code>```

Body:
I've created a class derived from BootstrapperBase, overwrote OnStartup() and call DisplayRootViewFor<AppViewModel>() just like in the documentation.

But when i start the app, i get a NullReferenceException on DisplayRooViewFor<AppViewModel>()

using Caliburn.Micro;
using MHBRestore.Logic;
using MHBRestore.UI.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MHBRestore.UI
{
public class AppBootstrapper : BootstrapperBase
{
    private SimpleContainer _container = new SimpleContainer();

    public AppBootstrapper()
    {
        Initialize();
    }

    protected override void OnStartup(object sender, StartupEventArgs e)
    {
        DisplayRootViewFor<AppViewModel>();
    }

    protected override object GetInstance(Type service, string key)
    {
        return _container.GetInstance(service, key);
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return _container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance)
    {
        _container.BuildUp(instance);
    }
}
}

Body:
Try to override the Configure method and register your view model type:

public class AppBootstrapper : BootstrapperBase
{
    private SimpleContainer _container = new SimpleContainer();

    public AppBootstrapper()
    {
        Initialize();
    }

    protected override void Configure()
    {
        _container.Singleton<IWindowManager, WindowManager>();
        _container.Singleton<IEventAggregator, EventAggregator>();
        _container.RegisterPerRequest(typeof(AppViewModel), null, typeof(AppViewModel));
    }

    protected override void OnStartup(object sender, StartupEventArgs e)
    {
        DisplayRootViewFor<AppViewModel>();
    }

    protected override object GetInstance(Type service, string key)
    {
        return _container.GetInstance(service, key);
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return _container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance)
    {
        _container.BuildUp(instance);
    }
}


问:
python Beautifulsoup4 package installing
I've trying to install beautifulsoup4 package for my mac.
I was following the video (https://www.youtube.com/watch?v=gM-L1rvTpwU).

I got up to where it's 1:40 in the video to upgrade the version of beautifulsoup.
But my terminal throws the error and this is how it looks:

could you guys help me how to fix this problem?

Thank you in advance!

答:
try

```<code>sudo pip install BeautifulSoup4
</code>```

as unix based system needs superuser permission to write unless you are installing it in a virtualenv

Body:
try

sudo pip install BeautifulSoup4

as unix based system needs superuser permission to write unless you are installing it in a virtualenv