问:
maatwebsite/excel Import using chunks seems to be not working - Laravel 5.4
I am following as per the documentation and queue executes fine, but no data after 1st are not stored in to database (for code sample, I am writing a separate files). Please refer my code below.

Package version: 2.1.0
Laravel version: 5.4.36

```<code>Excel::filter('chunk')->load(storage_path('users.csv'))->
chunk(250,function($results){
       $row_set = $results->toArray();
       foreach ($row_set as $key => $row) {
           Storage::disk('local')->put(rand(10, 100).'_users.txt', json_encode($row));
       }
});
</code>```

Configurations:
php.ini -> auto_detect_line_endings : true
export.php
force_sheets_collection: true,
QUEUE_DRIVER=database

Please help me to resolve this issue and I spend around 2 days to find a solution in different bug reports and solutions.

答:
You should set your $results into function, also you need to make sure by placing Log::debug() messages in you foreach loop</p>

```<code>Excel::filter('chunk')->load(storage_path('users.csv'))->
chunk(250,function($results){
       foreach ($results as $key => $row) {
           Storage::disk('local')->put(rand(10, 100).'_users.txt', json_encode($row));
       }
});
</code>```

Body:
I am following as per the documentation and queue executes fine, but no data after 1st are not stored in to database (for code sample, I am writing a separate files). Please refer my code below.

Package version: 2.1.0
Laravel version: 5.4.36

Excel::filter('chunk')->load(storage_path('users.csv'))->
chunk(250,function($results){
       $row_set = $results->toArray();
       foreach ($row_set as $key => $row) {
           Storage::disk('local')->put(rand(10, 100).'_users.txt', json_encode($row));
       }
});

Configurations:
php.ini -> auto_detect_line_endings : true
export.php
force_sheets_collection: true,
QUEUE_DRIVER=database

Please help me to resolve this issue and I spend around 2 days to find a solution in different bug reports and solutions.

Body:
You should set your $results into function, also you need to make sure by placing Log::debug() messages in you foreach loop

Excel::filter('chunk')->load(storage_path('users.csv'))->
chunk(250,function($results){
       foreach ($results as $key => $row) {
           Storage::disk('local')->put(rand(10, 100).'_users.txt', json_encode($row));
       }
});


来源: stackexchange

问:
JS: Replace some fields of an specific object inside of an array
I got an object array which looks like this:

```<code>const items = [
  {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
  {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "two", context: "default"}
]
</code>```

Note: items is readonly as it comes from prop in a react component

And I want to update the content by a given object like this:

```<code>const changeThis = { _id: "uK4MYJJGa6ra9e99v", context: "info" }
</code>```

So the object with the matching ID should get 'info' as new context value while keeping all other elements:

```<code>[
  {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
  {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "two", context: "info"}
]
</code>```

Another example

And...

```<code>const changeThis = { _id: "uK4MYJJGa6ra9e99v", context: "info", content: "new" }
</code>```

...should change context and content of the matching object:

```<code>[
  {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
  {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "new", context: "info"}
]
</code>```

My attempt

So first of all I would use map() to iterate throught the array, but how do I update all other fields using changeThis-object?
I tried to use assign() and keys() and I tried to ignore the _id-key:

```<code>items.map((item, index) => {
  if (item._id === changeThis._id) {
    Object.assign(
      {},
      ...Object.keys(item).map(k => (
        {
          [k]: changeThis.indexOf(k) > -1 && k !== '_id'
            ? changeThis[k]
            : item[k]
        }
    ))
  }
});
</code>```

答:
A simple function will suffice here; keep in mind that you will need to use let or var instead of const for items; map does not edit in place, but rather returns a new array. You could edit in place, but I would not necessarily recommend it.

```<code>items = items.map(item => {
  return (item._id === changeThis._id) ?
    { ...item, ...changeThis } :
    item
});
</code>```

By spreading the contents of changeThis into the object after the keys of item, any keys appearing in changeThis will override those from item. Keys non-duplicate keys from either object will also appear in the final result.

ContentLicense: CC BY-SA 3.0

Body:
I got an object array which looks like this:

const items = [
  {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
  {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "two", context: "default"}
]

Note: items is readonly as it comes from prop in a react component

And I want to update the content by a given object like this:

const changeThis = { _id: "uK4MYJJGa6ra9e99v", context: "info" }

So the object with the matching ID should get 'info' as new context value while keeping all other elements:

[
  {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
  {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "two", context: "info"}
]

Another example

And...

const changeThis = { _id: "uK4MYJJGa6ra9e99v", context: "info", content: "new" }

...should change context and content of the matching object:

[
  {_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
  {_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "new", context: "info"}
]

My attempt

So first of all I would use map() to iterate throught the array, but how do I update all other fields using changeThis-object?
I tried to use assign() and keys() and I tried to ignore the _id-key:

items.map((item, index) => {
  if (item._id === changeThis._id) {
    Object.assign(
      {},
      ...Object.keys(item).map(k => (
        {
          [k]: changeThis.indexOf(k) > -1 && k !== '_id'
            ? changeThis[k]
            : item[k]
        }
    ))
  }
});

Body:
A simple function will suffice here; keep in mind that you will need to use let or var instead of const for items; map does not edit in place, but rather returns a new array. You could edit in place, but I would not necessarily recommend it.

items = items.map(item => {
  return (item._id === changeThis._id) ?
    { ...item, ...changeThis } :
    item
});

By spreading the contents of changeThis into the object after the keys of item, any keys appearing in changeThis will override those from item. Keys non-duplicate keys from either object will also appear in the final result.


问:
Use timestamp in AWS API Gateway in the Path Override of the Integration Request
I've been trying to create a method in API Gateway that drops the body of the incoming request into a file/object in an S3 bucket. But I want the method to create a new file each time (so a file with a new name) instead of overwriting the previous one. But I've been struggling to find a way to do it. Anyone has any suggestions/ideas? Something like a timestamp, or a sequence number (or both) to use as a variable in the Path override so that it would become the name of the s3 file. I looked at suggestions to use the X-Amzn-Trace-Id but it doesn't seem to be available in Path override. Anything else I could try? Maybe something in Swagger? I want to achieve it using API Gateway (avoid using a lambda as an extra step) to keep our architecture from getting too complex. Thanks in advance!

答:
You can set the X-Amzn-Trace-Id as the method parameter, then map the parameter to the integration parameter on the path to S3 as the object name .

Example:

```<code>---
swagger: "2.0"
info:
  version: "2017-12-04T23:03:26Z"
  title: "API"
host: "xxxx.execute-api.us-east-1.amazonaws.com"
basePath: "/dev"
schemes:
- "https"
paths:
  /:
    post:
      produces:
      - "application/json"
      parameters:
      - name: "X-Amzn-Trace-Id"
        in: "header"
        required: false
        type: "string"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
      x-amazon-apigateway-integration:
        credentials: "arn:aws:iam::178779171625:role/api-gate-way"
        responses:
          default:
            statusCode: "200"
        requestParameters:
          integration.request.path.traceid: "method.request.header.X-Amzn-Trace-Id"
        uri: "arn:aws:apigateway:us-east-1:bucketName.s3:path/{traceid}"
        passthroughBehavior: "when_no_match"
        httpMethod: "PUT"
        type: "aws"
definitions:
  Empty:
    type: "object"
    title: "Empty Schema"
</code>```

Body:
You can set the X-Amzn-Trace-Id as the method parameter, then map the parameter to the integration parameter on the path to S3 as the object name .

Example:

---
swagger: "2.0"
info:
  version: "2017-12-04T23:03:26Z"
  title: "API"
host: "xxxx.execute-api.us-east-1.amazonaws.com"
basePath: "/dev"
schemes:
- "https"
paths:
  /:
    post:
      produces:
      - "application/json"
      parameters:
      - name: "X-Amzn-Trace-Id"
        in: "header"
        required: false
        type: "string"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
      x-amazon-apigateway-integration:
        credentials: "arn:aws:iam::178779171625:role/api-gate-way"
        responses:
          default:
            statusCode: "200"
        requestParameters:
          integration.request.path.traceid: "method.request.header.X-Amzn-Trace-Id"
        uri: "arn:aws:apigateway:us-east-1:bucketName.s3:path/{traceid}"
        passthroughBehavior: "when_no_match"
        httpMethod: "PUT"
        type: "aws"
definitions:
  Empty:
    type: "object"
    title: "Empty Schema"


问:
C++ standard library - when should I use it and when shouldn't I?
I was wondering how often people actually use much of the standard c++ library, particularly the stuff in the <algorithm> and <numeric> headers.  The text books seem to recommend them, but I haven't seen any of them used at all in various projects I've sifted through (coincidence?) and personally it seems easier to just write appropriate simple algorithms myself each time rather than memorize or consult a reference to these headers each time. Am just being lazy or stubborn?  Is there actually performance gains etc when using these libraries?

Thanks,

R

答:
Just about everyone using C++ uses the STL, especially <algorithm>. You really don't want to have to write sorting functions yourself; you'll just end up making mistakes, and in the end the performance will probably be worse.

Whether or not there are performance gains obviously depends on what you are comparing to. In general though, using the STL algorithms is typically faster than writing your own functions -- unless you happen to have a particular trick that applies to your use case that could give you the edge. If you just write a standard quicksort yourself, it will probably be slower than the one in the STL.

ContentLicense: CC BY-SA 2.5


问:
How to store CSV files to Google Drive using Python
I'm trying to upload CSV files from my desktop to Google Drive using the Google Drive API and Python. I have completed the set up through the developers site https://developers.google.com/drive/v3/web/quickstart/python and am confused on the next steps. </p>

<p>I want to upload the CSV files, and DO NOT want to convert the files to google spreadsheets. </p>

答:
The docs here imply that your file will not be converted unless you specify a mimeType in file metadata.

So you should be able to do:

```<code>file_metadata = {'name': 'My Report'}
media = MediaFileUpload('files/report.csv',
                    mimetype='text/csv',
                    resumable=True)
file = drive_service.files().create(body=file_metadata,
                                media_body=media,
                                fields='id').execute()
print 'File ID: %s' % file.get('id')
</code>```

Body:
I'm trying to upload CSV files from my desktop to Google Drive using the Google Drive API and Python. I have completed the set up through the developers site https://developers.google.com/drive/v3/web/quickstart/python and am confused on the next steps.

I want to upload the CSV files, and DO NOT want to convert the files to google spreadsheets.

Body:
The docs here imply that your file will not be converted unless you specify a mimeType in file metadata.

So you should be able to do:

file_metadata = {'name': 'My Report'}
media = MediaFileUpload('files/report.csv',
                    mimetype='text/csv',
                    resumable=True)
file = drive_service.files().create(body=file_metadata,
                                media_body=media,
                                fields='id').execute()
print 'File ID: %s' % file.get('id')


问:
Unexpected/inaccurate image color conversions in Go
It seems as if Go's conversion arithmetic from JPEG's YCbCr to RGBA is slightly off, based on Python's PIL and ImageMagick's color values, but I'm probably just overlooking something.

PIL's and IM's results are identical. For Go, I load the image, convert to a non-alpha-premultiplied model, and then access the fields directly instead of using the RGBA getter (which will multiply the alpha against the color components). Unfortunately, many of the individual component values are equal but most of the colors have at least one component that is +-1 off of the component in that same position in PIL/IM's results.

Can anyone lend some wisdom/interpretation to this?

With ImageMagick ("convert image.jpg image.txt"; the left and right RGBs match, here, FYI):

```<code># ImageMagick pixel enumeration: 100,67,255,srgb
0,0: (190,200,210)  #BEC8D2  srgb(190,200,210)
1,0: (193,203,213)  #C1CBD5  srgb(193,203,213)
2,0: (195,205,215)  #C3CDD7  srgb(195,205,215)
3,0: (195,205,215)  #C3CDD7  srgb(195,205,215)
4,0: (194,204,214)  #C2CCD6  srgb(194,204,214)
5,0: (195,205,215)  #C3CDD7  srgb(195,205,215)
6,0: (198,208,218)  #C6D0DA  srgb(198,208,218)
7,0: (200,210,220)  #C8D2DC  srgb(200,210,220)
8,0: (202,210,221)  #CAD2DD  srgb(202,210,221)
9,0: (203,211,222)  #CBD3DE  srgb(203,211,222)
10,0: (205,213,224)  #CDD5E0  srgb(205,213,224)
11,0: (208,217,226)  #D0D9E2  srgb(208,217,226)
12,0: (211,218,226)  #D3DAE2  srgb(211,218,226)
13,0: (213,220,228)  #D5DCE4  srgb(213,220,228)
14,0: (216,223,229)  #D8DFE5  srgb(216,223,229)
15,0: (217,224,230)  #D9E0E6  srgb(217,224,230)
16,0: (220,225,231)  #DCE1E7  srgb(220,225,231)
17,0: (221,226,232)  #DDE2E8  srgb(221,226,232)
18,0: (223,228,234)  #DFE4EA  srgb(223,228,234)
19,0: (224,229,235)  #E0E5EB  srgb(224,229,235)
</code>```

With PIL:

(code)

```<code>import os

import PIL.Image as Image

def _main():
    image_filepath = 'image.jpg'
    output_filepath = image_filepath + '.python-dump'

    im = Image.open(image_filepath)
    width, height = im.size

    data = im.getdata()

    if os.path.exists(output_filepath):
        os.remove(output_filepath)

    with open(output_filepath, 'w') as f:
        for y in range(height):
            for x in range(width):
                r, g, b = data[y * im.size[0] + x]

                s = '({}, {}): [{} {} {}]\n'.format(y, x, r, g, b)
                f.write(s)

if __name__ == '__main__':
    _main()
</code>```

(output)

```<code>(0, 0): [190 200 210]
(0, 1): [193 203 213]
(0, 2): [195 205 215]
(0, 3): [195 205 215]
(0, 4): [194 204 214]
(0, 5): [195 205 215]
(0, 6): [198 208 218]
(0, 7): [200 210 220]
(0, 8): [202 210 221]
(0, 9): [203 211 222]
(0, 10): [205 213 224]
(0, 11): [208 217 226]
(0, 12): [211 218 226]
(0, 13): [213 220 228]
(0, 14): [216 223 229]
(0, 15): [217 224 230]
(0, 16): [220 225 231]
(0, 17): [221 226 232]
(0, 18): [223 228 234]
(0, 19): [224 229 235]
</code>```

With Go:

(code)

```<code>package main

import (
    "os"
    "fmt"
    "image"
    "image/color"
    "reflect"

    _ "image/jpeg"
)

func main() {
    imageFilepath := "image.jpg"
    outputFilepath := imageFilepath + ".go-dump"

    f, err := os.Open(imageFilepath)
    if err != nil {
        panic(err)
    }

    defer f.Close()

    image, _, err := image.Decode(f)
    if err != nil {
        panic(err)
    }

    r := image.Bounds()
    width := r.Max.X
    height := r.Max.Y

    os.Remove(outputFilepath)

    g, err := os.OpenFile(outputFilepath, os.O_RDWR|os.O_CREATE, 0644)
    if err != nil {
        panic(err)
    }

    defer g.Close()

    for y := 0; y < height; y++ {
        for x := 0; x < width; x++ {
            p := image.At(x, y)
            c := color.NRGBAModel.Convert(p).(color.NRGBA)

            s := fmt.Sprintf("(%d, %d): [%d %d %d %d]\n", y, x, c.R, c.G, c.B, c.A)
            g.Write([]byte(s))
        }
    }
}
</code>```

(output)

```<code>(0, 0): [190 200 211 255]
(0, 1): [193 203 214 255]
(0, 2): [195 205 216 255]
(0, 3): [195 205 216 255]
(0, 4): [194 204 215 255]
(0, 5): [195 205 216 255]
(0, 6): [198 208 219 255]
(0, 7): [200 210 221 255]
(0, 8): [202 210 222 255]
(0, 9): [203 211 223 255]
(0, 10): [205 213 225 255]
(0, 11): [208 217 226 255]
(0, 12): [212 218 226 255]
(0, 13): [214 220 228 255]
(0, 14): [217 224 229 255]
(0, 15): [218 225 230 255]
(0, 16): [220 225 231 255]
(0, 17): [221 226 232 255]
(0, 18): [223 228 234 255]
(0, 19): [224 229 235 255]
</code>```

EDIT: Oh, man.

The Go code seems to implement the YCbCr->RGB conversion in a totally different manner. Not only does it indicate that it does some minor rounding (which deviates from the JFIF specification) so that it can implement faster integer math, instead of floating point math, PIL/Pillow (and IM, by implication) uses lookup tables rather than actual arithmetic. This ultimately seems to imply that Go will never produce the same color values as the other implementations. If it's critical that the color values be identical between Go and the others, you might need to use an alternate implementation.

Go implementation:

(https://golang.org/src/image/color/ycbcr.go)

```<code>// YCbCrToRGB converts a Y'CbCr triple to an RGB triple.
func YCbCrToRGB(y, cb, cr uint8) (uint8, uint8, uint8) {
  // The JFIF specification says:
  //  R = Y' + 1.40200*(Cr-128)
  //  G = Y' - 0.34414*(Cb-128) - 0.71414*(Cr-128)
  //  B = Y' + 1.77200*(Cb-128)
  // http://www.w3.org/Graphics/JPEG/jfif3.pdf says Y but means Y'.
  //
  // Those formulae use non-integer multiplication factors. When computing,
  // integer math is generally faster than floating point math. We multiply
  // all of those factors by 1<<16 and round to the nearest integer:
  //   91881 = roundToNearestInteger(1.40200 * 65536).
  //   22554 = roundToNearestInteger(0.34414 * 65536).
  //   46802 = roundToNearestInteger(0.71414 * 65536).
  //  116130 = roundToNearestInteger(1.77200 * 65536).
  //
  // Adding a rounding adjustment in the range [0, 1<<16-1] and then shifting
  // right by 16 gives us an integer math version of the original formulae.
  //  R = (65536*Y' +  91881 *(Cr-128)                  + adjustment) >> 16
  //  G = (65536*Y' -  22554 *(Cb-128) - 46802*(Cr-128) + adjustment) >> 16
  //  B = (65536*Y' + 116130 *(Cb-128)                  + adjustment) >> 16
  // A constant rounding adjustment of 1<<15, one half of 1<<16, would mean
  // round-to-nearest when dividing by 65536 (shifting right by 16).
  // Similarly, a constant rounding adjustment of 0 would mean round-down.
  //
  // Defining YY1 = 65536*Y' + adjustment simplifies the formulae and
  // requires fewer CPU operations:
  //  R = (YY1 +  91881 *(Cr-128)                 ) >> 16
  //  G = (YY1 -  22554 *(Cb-128) - 46802*(Cr-128)) >> 16
  //  B = (YY1 + 116130 *(Cb-128)                 ) >> 16
  //
  // The inputs (y, cb, cr) are 8 bit color, ranging in [0x00, 0xff]. In this
  // function, the output is also 8 bit color, but in the related YCbCr.RGBA
  // method, below, the output is 16 bit color, ranging in [0x0000, 0xffff].
  // Outputting 16 bit color simply requires changing the 16 to 8 in the "R =
  // etc >> 16" equation, and likewise for G and B.
  //
  // As mentioned above, a constant rounding adjustment of 1<<15 is a natural
  // choice, but there is an additional constraint: if c0 := YCbCr{Y: y, Cb:
  // 0x80, Cr: 0x80} and c1 := Gray{Y: y} then c0.RGBA() should equal
  // c1.RGBA(). Specifically, if y == 0 then "R = etc >> 8" should yield
  // 0x0000 and if y == 0xff then "R = etc >> 8" should yield 0xffff. If we
  // used a constant rounding adjustment of 1<<15, then it would yield 0x0080
  // and 0xff80 respectively.
  //
  // Note that when cb == 0x80 and cr == 0x80 then the formulae collapse to:
  //  R = YY1 >> n
  //  G = YY1 >> n
  //  B = YY1 >> n
  // where n is 16 for this function (8 bit color output) and 8 for the
  // YCbCr.RGBA method (16 bit color output).
  //
  // The solution is to make the rounding adjustment non-constant, and equal
  // to 257*Y', which ranges over [0, 1<<16-1] as Y' ranges over [0, 255].
  // YY1 is then defined as:
  //  YY1 = 65536*Y' + 257*Y'
  // or equivalently:
  //  YY1 = Y' * 0x10101
  yy1 := int32(y) * 0x10101
  cb1 := int32(cb) - 128
  cr1 := int32(cr) - 128

  // The bit twiddling below is equivalent to
  //
  // r := (yy1 + 91881*cr1) >> 16
  // if r < 0 {
  //     r = 0
  // } else if r > 0xff {
  //     r = ^int32(0)
  // }
  //
  // but uses fewer branches and is faster.
  // Note that the uint8 type conversion in the return
  // statement will convert ^int32(0) to 0xff.
  // The code below to compute g and b uses a similar pattern.
  r := yy1 + 91881*cr1
  if uint32(r)&0xff000000 == 0 {
      r >>= 16
  } else {
      r = ^(r >> 31)
  }

  g := yy1 - 22554*cb1 - 46802*cr1
  if uint32(g)&0xff000000 == 0 {
      g >>= 16
  } else {
      g = ^(g >> 31)
  }

  b := yy1 + 116130*cb1
  if uint32(b)&0xff000000 == 0 {
      b >>= 16
  } else {
      b = ^(b >> 31)
  }

  return uint8(r), uint8(g), uint8(b)
}
</code>```

PIL (Pillow, actually) implementation (uses lookup tables):

(https://github.com/python-pillow/Pillow/blob/bb1b3a532ca3fef915f9cde17ba2227671ac691c/libImaging/ConvertYCbCr.c#L363)

```<code>void
ImagingConvertYCbCr2RGB(UINT8* out, const UINT8* in, int pixels)
{
    int x;
    UINT8 a;
    int r, g, b;
    int y, cr, cb;

    for (x = 0; x < pixels; x++, in += 4, out += 4) {

        y = in[0];
        cb = in[1];
        cr = in[2];
        a = in[3];

        r = y + ((           R_Cr[cr]) >> SCALE);
        g = y + ((G_Cb[cb] + G_Cr[cr]) >> SCALE);
        b = y + ((B_Cb[cb]           ) >> SCALE);

        out[0] = (r <= 0) ? 0 : (r >= 255) ? 255 : r;
        out[1] = (g <= 0) ? 0 : (g >= 255) ? 255 : g;
        out[2] = (b <= 0) ? 0 : (b >= 255) ? 255 : b;
        out[3] = a;
    }
}
</code>```

答: See the comment by @JimB, above. Apparently the specification does not cover this particular conversion. So, it may, in fact, be different from one implementation to the next.</p>

Body:
It seems as if Go's conversion arithmetic from JPEG's YCbCr to RGBA is slightly off, based on Python's PIL and ImageMagick's color values, but I'm probably just overlooking something.

PIL's and IM's results are identical. For Go, I load the image, convert to a non-alpha-premultiplied model, and then access the fields directly instead of using the RGBA getter (which will multiply the alpha against the color components). Unfortunately, many of the individual component values are equal but most of the colors have at least one component that is +-1 off of the component in that same position in PIL/IM's results.

Can anyone lend some wisdom/interpretation to this?

With ImageMagick ("convert image.jpg image.txt"; the left and right RGBs match, here, FYI):

# ImageMagick pixel enumeration: 100,67,255,srgb
0,0: (190,200,210)  #BEC8D2  srgb(190,200,210)
1,0: (193,203,213)  #C1CBD5  srgb(193,203,213)
2,0: (195,205,215)  #C3CDD7  srgb(195,205,215)
3,0: (195,205,215)  #C3CDD7  srgb(195,205,215)
4,0: (194,204,214)  #C2CCD6  srgb(194,204,214)
5,0: (195,205,215)  #C3CDD7  srgb(195,205,215)
6,0: (198,208,218)  #C6D0DA  srgb(198,208,218)
7,0: (200,210,220)  #C8D2DC  srgb(200,210,220)
8,0: (202,210,221)  #CAD2DD  srgb(202,210,221)
9,0: (203,211,222)  #CBD3DE  srgb(203,211,222)
10,0: (205,213,224)  #CDD5E0  srgb(205,213,224)
11,0: (208,217,226)  #D0D9E2  srgb(208,217,226)
12,0: (211,218,226)  #D3DAE2  srgb(211,218,226)
13,0: (213,220,228)  #D5DCE4  srgb(213,220,228)
14,0: (216,223,229)  #D8DFE5  srgb(216,223,229)
15,0: (217,224,230)  #D9E0E6  srgb(217,224,230)
16,0: (220,225,231)  #DCE1E7  srgb(220,225,231)
17,0: (221,226,232)  #DDE2E8  srgb(221,226,232)
18,0: (223,228,234)  #DFE4EA  srgb(223,228,234)
19,0: (224,229,235)  #E0E5EB  srgb(224,229,235)

With PIL:

(code)

import os

import PIL.Image as Image

def _main():
    image_filepath = 'image.jpg'
    output_filepath = image_filepath + '.python-dump'

    im = Image.open(image_filepath)
    width, height = im.size

    data = im.getdata()

    if os.path.exists(output_filepath):
        os.remove(output_filepath)

    with open(output_filepath, 'w') as f:
        for y in range(height):
            for x in range(width):
                r, g, b = data[y * im.size[0] + x]

                s = '({}, {}): [{} {} {}]\n'.format(y, x, r, g, b)
                f.write(s)

if __name__ == '__main__':
    _main()

(output)

(0, 0): [190 200 210]
(0, 1): [193 203 213]
(0, 2): [195 205 215]
(0, 3): [195 205 215]
(0, 4): [194 204 214]
(0, 5): [195 205 215]
(0, 6): [198 208 218]
(0, 7): [200 210 220]
(0, 8): [202 210 221]
(0, 9): [203 211 222]
(0, 10): [205 213 224]
(0, 11): [208 217 226]
(0, 12): [211 218 226]
(0, 13): [213 220 228]
(0, 14): [216 223 229]
(0, 15): [217 224 230]
(0, 16): [220 225 231]
(0, 17): [221 226 232]
(0, 18): [223 228 234]
(0, 19): [224 229 235]

With Go:

(code)

package main

import (
    "os"
    "fmt"
    "image"
    "image/color"
    "reflect"

    _ "image/jpeg"
)

func main() {
    imageFilepath := "image.jpg"
    outputFilepath := imageFilepath + ".go-dump"

    f, err := os.Open(imageFilepath)
    if err != nil {
        panic(err)
    }

    defer f.Close()

    image, _, err := image.Decode(f)
    if err != nil {
        panic(err)
    }

    r := image.Bounds()
    width := r.Max.X
    height := r.Max.Y

    os.Remove(outputFilepath)

    g, err := os.OpenFile(outputFilepath, os.O_RDWR|os.O_CREATE, 0644)
    if err != nil {
        panic(err)
    }

    defer g.Close()

    for y := 0; y < height; y++ {
        for x := 0; x < width; x++ {
            p := image.At(x, y)
            c := color.NRGBAModel.Convert(p).(color.NRGBA)

            s := fmt.Sprintf("(%d, %d): [%d %d %d %d]\n", y, x, c.R, c.G, c.B, c.A)
            g.Write([]byte(s))
        }
    }
}

(output)

(0, 0): [190 200 211 255]
(0, 1): [193 203 214 255]
(0, 2): [195 205 216 255]
(0, 3): [195 205 216 255]
(0, 4): [194 204 215 255]
(0, 5): [195 205 216 255]
(0, 6): [198 208 219 255]
(0, 7): [200 210 221 255]
(0, 8): [202 210 222 255]
(0, 9): [203 211 223 255]
(0, 10): [205 213 225 255]
(0, 11): [208 217 226 255]
(0, 12): [212 218 226 255]
(0, 13): [214 220 228 255]
(0, 14): [217 224 229 255]
(0, 15): [218 225 230 255]
(0, 16): [220 225 231 255]
(0, 17): [221 226 232 255]
(0, 18): [223 228 234 255]
(0, 19): [224 229 235 255]

EDIT: Oh, man.

The Go code seems to implement the YCbCr->RGB conversion in a totally different manner. Not only does it indicate that it does some minor rounding (which deviates from the JFIF specification) so that it can implement faster integer math, instead of floating point math, PIL/Pillow (and IM, by implication) uses lookup tables rather than actual arithmetic. This ultimately seems to imply that Go will never produce the same color values as the other implementations. If it's critical that the color values be identical between Go and the others, you might need to use an alternate implementation.

Go implementation:

(https://golang.org/src/image/color/ycbcr.go)

// YCbCrToRGB converts a Y'CbCr triple to an RGB triple.
func YCbCrToRGB(y, cb, cr uint8) (uint8, uint8, uint8) {
  // The JFIF specification says:
  //  R = Y' + 1.40200*(Cr-128)
  //  G = Y' - 0.34414*(Cb-128) - 0.71414*(Cr-128)
  //  B = Y' + 1.77200*(Cb-128)
  // http://www.w3.org/Graphics/JPEG/jfif3.pdf says Y but means Y'.
  //
  // Those formulae use non-integer multiplication factors. When computing,
  // integer math is generally faster than floating point math. We multiply
  // all of those factors by 1<<16 and round to the nearest integer:
  //   91881 = roundToNearestInteger(1.40200 * 65536).
  //   22554 = roundToNearestInteger(0.34414 * 65536).
  //   46802 = roundToNearestInteger(0.71414 * 65536).
  //  116130 = roundToNearestInteger(1.77200 * 65536).
  //
  // Adding a rounding adjustment in the range [0, 1<<16-1] and then shifting
  // right by 16 gives us an integer math version of the original formulae.
  //  R = (65536*Y' +  91881 *(Cr-128)                  + adjustment) >> 16
  //  G = (65536*Y' -  22554 *(Cb-128) - 46802*(Cr-128) + adjustment) >> 16
  //  B = (65536*Y' + 116130 *(Cb-128)                  + adjustment) >> 16
  // A constant rounding adjustment of 1<<15, one half of 1<<16, would mean
  // round-to-nearest when dividing by 65536 (shifting right by 16).
  // Similarly, a constant rounding adjustment of 0 would mean round-down.
  //
  // Defining YY1 = 65536*Y' + adjustment simplifies the formulae and
  // requires fewer CPU operations:
  //  R = (YY1 +  91881 *(Cr-128)                 ) >> 16
  //  G = (YY1 -  22554 *(Cb-128) - 46802*(Cr-128)) >> 16
  //  B = (YY1 + 116130 *(Cb-128)                 ) >> 16
  //
  // The inputs (y, cb, cr) are 8 bit color, ranging in [0x00, 0xff]. In this
  // function, the output is also 8 bit color, but in the related YCbCr.RGBA
  // method, below, the output is 16 bit color, ranging in [0x0000, 0xffff].
  // Outputting 16 bit color simply requires changing the 16 to 8 in the "R =
  // etc >> 16" equation, and likewise for G and B.
  //
  // As mentioned above, a constant rounding adjustment of 1<<15 is a natural
  // choice, but there is an additional constraint: if c0 := YCbCr{Y: y, Cb:
  // 0x80, Cr: 0x80} and c1 := Gray{Y: y} then c0.RGBA() should equal
  // c1.RGBA(). Specifically, if y == 0 then "R = etc >> 8" should yield
  // 0x0000 and if y == 0xff then "R = etc >> 8" should yield 0xffff. If we
  // used a constant rounding adjustment of 1<<15, then it would yield 0x0080
  // and 0xff80 respectively.
  //
  // Note that when cb == 0x80 and cr == 0x80 then the formulae collapse to:
  //  R = YY1 >> n
  //  G = YY1 >> n
  //  B = YY1 >> n
  // where n is 16 for this function (8 bit color output) and 8 for the
  // YCbCr.RGBA method (16 bit color output).
  //
  // The solution is to make the rounding adjustment non-constant, and equal
  // to 257*Y', which ranges over [0, 1<<16-1] as Y' ranges over [0, 255].
  // YY1 is then defined as:
  //  YY1 = 65536*Y' + 257*Y'
  // or equivalently:
  //  YY1 = Y' * 0x10101
  yy1 := int32(y) * 0x10101
  cb1 := int32(cb) - 128
  cr1 := int32(cr) - 128

  // The bit twiddling below is equivalent to
  //
  // r := (yy1 + 91881*cr1) >> 16
  // if r < 0 {
  //     r = 0
  // } else if r > 0xff {
  //     r = ^int32(0)
  // }
  //
  // but uses fewer branches and is faster.
  // Note that the uint8 type conversion in the return
  // statement will convert ^int32(0) to 0xff.
  // The code below to compute g and b uses a similar pattern.
  r := yy1 + 91881*cr1
  if uint32(r)&0xff000000 == 0 {
      r >>= 16
  } else {
      r = ^(r >> 31)
  }

  g := yy1 - 22554*cb1 - 46802*cr1
  if uint32(g)&0xff000000 == 0 {
      g >>= 16
  } else {
      g = ^(g >> 31)
  }

  b := yy1 + 116130*cb1
  if uint32(b)&0xff000000 == 0 {
      b >>= 16
  } else {
      b = ^(b >> 31)
  }

  return uint8(r), uint8(g), uint8(b)
}

PIL (Pillow, actually) implementation (uses lookup tables):

(https://github.com/python-pillow/Pillow/blob/bb1b3a532ca3fef915f9cde17ba2227671ac691c/libImaging/ConvertYCbCr.c#L363)

void
ImagingConvertYCbCr2RGB(UINT8* out, const UINT8* in, int pixels)
{
    int x;
    UINT8 a;
    int r, g, b;
    int y, cr, cb;

    for (x = 0; x < pixels; x++, in += 4, out += 4) {

        y = in[0];
        cb = in[1];
        cr = in[2];
        a = in[3];

        r = y + ((           R_Cr[cr]) >> SCALE);
        g = y + ((G_Cb[cb] + G_Cr[cr]) >> SCALE);
        b = y + ((B_Cb[cb]           ) >> SCALE);

        out[0] = (r <= 0) ? 0 : (r >= 255) ? 255 : r;
        out[1] = (g <= 0) ? 0 : (g >= 255) ? 255 : g;
        out[2] = (b <= 0) ? 0 : (b >= 255) ? 255 : b;
        out[3] = a;
    }
}


问:
Visual Studio 2017 project needs to be deployed before it can be started
I'm trying to run my UWP app on my local machine and all was going well until Windows crashed.  After that I started getting the error message:

The Project ### needs to be deployed before it can be started

Here is the screenshot:

I have uninstalled VS and reinstalled it and created new projects but I'm getting the same issue every time.  Both the Debug and Deploy boxes are ticked in Configuration Manager for Debug ans x64.  I have seen a few different answers for this but none have worked so far.

This in turn leads to the error message:

Severity  Code    Description Project File    Line    Suppression State Error DEP0600: Deployment failed. XmlException - '.', hexadecimal value 0x00, is an invalid character. Line 1, position 1. [0x80131940]   App3

Every new app I create does exactly the same thing

答:
In my case it helped when I switched the option Any CPU to x64. Then I could normally debug the program, just as in this picture:
Change CPU type</p>


问:
copy files without permissions
I have a powershell script that copies some files for later use by a Python script. The copy operation is this:

```<code>ls $env:MINGW_32 -r -ea silentlycontinue -fo -inc "*.dll" | % { cp $_.fullname "build\lib.win32-2.7" }
</code>```

Nothing particularly interesting or unusual. The interesting (frustrating) part is what happens later:

```<code>error: [Error 5] Access is denied: 'build\\bdist.win32\\4758ccaeay32.dll'
</code>```

CPython in fact has logic in distutils that explicitly resets the file permissions after it copies the DLLs to avoid this exact issue. I have attempted to replicate this in powershell but have not been successful:

```<code>$location = ".\build";
#Search recursivly through location defined;
get-childitem -r $location | foreach{
     $tempLocation = $_.FullName;
     #Get ACL for tempLocation;
     $acl = get-acl $tempLocation;
     #Get SID of explicit ACL;
     $acl.Access | where{
          $_.isinherited -like $false} | foreach{
          #Foreach SID purge the SID from the ACL;
          $acl.purgeaccessrules($_.IdentityReference);
          #Reapply ACL to file or folder without SID;
          Set-Acl -AclObject $acl -path $tempLocation;
     }
}
</code>```

Are there any suggestions to reset or preferably avoid copying the file permissions in the first place so that the Python script does not fail?

答:
Try a slightly different approach. Instead of rebuilding each file's ACLs build one ACL and apply it to all files. Also, I believe that your call to .PurgeAccessRules(<IdentityReference>) should instead be calls to .RemoveAccessRule(<AccessRule>)

```<code>$location = ".\build"

#Get ACLs for first file in the folder
$ACL = GCI $location -File | Select -First 1 | Get-Acl
#Remove all non-inherited access rules, piped to Out-Null to avoid 'True' spam as it removes rules
$ACL.Access | ?{!$_.IsInherited} | %{$ACL.RemoveAccessRule($_) | Out-Null}

#Search recursivly through location defined;
GCI -r $location | Set-Acl -AclObject $ACL
</code>```

Aliases used (truncated results):

```<code>PS C:\Users\TMTech> Get-Alias GCI,?
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           GCI -> Get-ChildItem
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
</code>```

Title: copy files without permissions

Body:
I have a powershell script that copies some files for later use by a Python script. The copy operation is this:

ls $env:MINGW_32 -r -ea silentlycontinue -fo -inc "*.dll" | % { cp $_.fullname "build\lib.win32-2.7" }

Nothing particularly interesting or unusual. The interesting (frustrating) part is what happens later:

error: [Error 5] Access is denied: 'build\\bdist.win32\\4758ccaeay32.dll'

CPython in fact has logic in distutils that explicitly resets the file permissions after it copies the DLLs to avoid this exact issue. I have attempted to replicate this in powershell but have not been successful:

$location = ".\build";
#Search recursivly through location defined;
get-childitem -r $location | foreach{
     $tempLocation = $_.FullName;
     #Get ACL for tempLocation;
     $acl = get-acl $tempLocation;
     #Get SID of explicit ACL;
     $acl.Access | where{
          $_.isinherited -like $false} | foreach{
          #Foreach SID purge the SID from the ACL;
          $acl.purgeaccessrules($_.IdentityReference);
          #Reapply ACL to file or folder without SID;
          Set-Acl -AclObject $acl -path $tempLocation;
     }
}

Are there any suggestions to reset or preferably avoid copying the file permissions in the first place so that the Python script does not fail?

Body:
Try a slightly different approach. Instead of rebuilding each file's ACLs build one ACL and apply it to all files. Also, I believe that your call to .PurgeAccessRules(<IdentityReference>) should instead be calls to .RemoveAccessRule(<AccessRule>)

$location = ".\build"

#Get ACLs for first file in the folder
$ACL = GCI $location -File | Select -First 1 | Get-Acl
#Remove all non-inherited access rules, piped to Out-Null to avoid 'True' spam as it removes rules
$ACL.Access | ?{!$_.IsInherited} | %{$ACL.RemoveAccessRule($_) | Out-Null}

#Search recursivly through location defined;
GCI -r $location | Set-Acl -AclObject $ACL

Aliases used (truncated results):

PS C:\Users\TMTech> Get-Alias GCI,?
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           GCI -> Get-ChildItem
Alias           % -> ForEach-Object
Alias           ? -> Where-Object


问:
Cannot get login button positioned correctly in navbar

The button that is labelled "Login" needs to be pushed to the right of the navbar and lined up properly with other buttons. Here is a jfiddle to see what it's doing. I am using bootstrap to design this and am having trouble with positioning of certain buttons.
 https://jsfiddle.net/sterlingmd17/tk17zjfq/1/

```<code><nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li class="{{a}}"> <a href="/">Home</a></li>
            <li class="{{b}}"> <a href="#order">Order form</a></li>
            <li class="{{c}}"> <a href="#about">About Swirlz</a></li>
            <li class="{{d}}"> <a href="#contact">Contact</a></li>
            <!--TODO fix login button positioning -->
            <div class="btn-group dropdown">
            <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Login
            </button>
            <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"></div>
          </div>
          </ul>

        </div>

    </nav>
</code>```

答:
First, move the button div outside of the unordered list tags, then add the classes navbar-form and navbar-right to the button div.

It should look like this

```<code><div id="navbar" class="navbar-collapse collapse">
  <ul class="nav navbar-nav">
    <li class="{{a}}"> <a href="/">Home</a></li>
    <li class="{{b}}"> <a href="#order">Order form</a></li>
    <li class="{{c}}"> <a href="#about">About Swirlz</a></li>
    <li class="{{d}}"> <a href="#contact">Contact</a></li>
  </ul>
  <!--TODO fix login button positioning -->
  <div class="navbar-form navbar-right btn-group dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      Login
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"></div>
  </div>
</div>
</code>```

Body:
The button that is labelled "Login" needs to be pushed to the right of the navbar and lined up properly with other buttons. Here is a jfiddle to see what it's doing. I am using bootstrap to design this and am having trouble with positioning of certain buttons.
 https://jsfiddle.net/sterlingmd17/tk17zjfq/1/

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Project name

 Home

 Order form

 About Swirlz

 Contact

            <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Login
            </button>

Body:
First, move the button div outside of the unordered list tags, then add the classes navbar-form and navbar-right to the button div.

It should look like this

<div id="navbar" class="navbar-collapse collapse">
  <ul class="nav navbar-nav">
    <li class="{{a}}"> <a href="/">Home</a></li>
    <li class="{{b}}"> <a href="#order">Order form</a></li>
    <li class="{{c}}"> <a href="#about">About Swirlz</a></li>
    <li class="{{d}}"> <a href="#contact">Contact</a></li>
  </ul>
  <!--TODO fix login button positioning -->
  <div class="navbar-form navbar-right btn-group dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      Login
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"></div>
  </div>
</div>


问:
No idea where this stylesheet is coming from - wordpress php
I'm trying to update my website but one thing I'm noticing is that I can't get rid of the original stylesheet. Right now I've gone into my bluehost control panel and replaced the style.css file. I also went into the custom css and deleted any css I had there to make sure there was nothing there that could possibly over ride it. But still if you go to the website you will see there are 2 stylesheets. I even searched my wordpress admin panel to make sure I didn't cache anything but I don't have a caching plugin. so that leads me to assume I messed up in the php somewhere but I'm not sure.

So when you go to the website and open the inspector and go to the sources you will see 2 stylesheets. style.css?ver=4.9.1 (the right one) and style.css?ver=1.0 (the old one). The old style sheet is making the navbar invisible and justifying the contact form to the left. The new stylesheet fixes those issues but for whatever reason the old stylesheet persists to exist and override the changes.

www.mustafasprojects.com

here's the header:

```<code><!doctype html>
<html <?php language_attributes(); ?> class="no-js">
    <head>
        <meta charset="<?php bloginfo('charset'); ?>">
        <title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' :'; } ?> <?php bloginfo('name'); ?></title>

        <link href="//www.google-analytics.com" rel="dns-prefetch">

        <link href="<?php echo get_template_directory_uri(); ?>/img/icons/touch.png" rel="apple-touch-icon-precomposed">

        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="<?php bloginfo('description'); ?>">

        <?php wp_head(); ?>
        <script>
        // conditionizr.com
        // configure environment tests
        conditionizr.config({
            assets: '<?php echo get_template_directory_uri(); ?>',
            tests: {}
        });
        </script>

    </head>
    <body <?php body_class(); ?>>

        <div id="page-wrapper">
</code>```

here's the function.php

```<code>// Load any external files you have here

function theme_styles() {
    wp_enqueue_style( 'bootstrap_css', 'http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css' );
    wp_enqueue_style( 'b_css', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css' );
    wp_enqueue_style( 'style_css', get_template_directory_uri() . '/style.css' );
}

add_action( 'wp_enqueue_scripts', 'theme_styles' );

function theme_js() {
    wp_enqueue_script( 'bootstrap_js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js');
}

add_action( 'wp_enqueue_scripts', 'themes_js');

add_action('wp_enqueue_scripts', 'add_my_script'); // initiate the function

function add_my_script() {
wp_register_script ( 'colorbox-min' , get_stylesheet_directory_uri() . '/js/jquery.colorbox-min.js', array( 'jquery' ), '1', true );
wp_enqueue_script( 'colorbox-min' );

// Commented out because you probably want to use the minified version of the script
//wp_register_script ( 'colorbox' , get_stylesheet_directory_uri() . '/js/jquery.colorbox.js', array( 'jquery' ), '1', true );
//wp_enqueue_script( 'colorbox' );

wp_register_style ('ihatecolorboxcss', get_stylesheet_directory_uri() . '/ihatecolorbox.css','', '1', 'all');
wp_enqueue_style( 'colorbox' );
}
</code>```

edit: other place I hooked in a style sheet

```<code>function html5blank_styles()
{
    wp_register_style('normalize', get_template_directory_uri() . '/normalize.css', array(), '1.0', 'all');
    wp_enqueue_style('normalize'); //

    wp_register_style('html5blank', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');
    wp_enqueue_style('html5blank');
</code>```

答:
You are loading two, this one in functions

```<code>wp_enqueue_style( 'style_css', get_template_directory_uri() . '/style.css' );
</code>```

and this one in your hook, adding v1.0 to the end

```<code>wp_register_style('html5blank', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');
</code>```

Enqueued with different names, but both have the same url

Body:
I'm trying to update my website but one thing I'm noticing is that I can't get rid of the original stylesheet. Right now I've gone into my bluehost control panel and replaced the style.css file. I also went into the custom css and deleted any css I had there to make sure there was nothing there that could possibly over ride it. But still if you go to the website you will see there are 2 stylesheets. I even searched my wordpress admin panel to make sure I didn't cache anything but I don't have a caching plugin. so that leads me to assume I messed up in the php somewhere but I'm not sure.

So when you go to the website and open the inspector and go to the sources you will see 2 stylesheets. style.css?ver=4.9.1 (the right one) and style.css?ver=1.0 (the old one). The old style sheet is making the navbar invisible and justifying the contact form to the left. The new stylesheet fixes those issues but for whatever reason the old stylesheet persists to exist and override the changes.

www.mustafasprojects.com

here's the header:

<!doctype html>
<html <?php language_attributes(); ?> class="no-js">

        <meta charset="<?php bloginfo('charset'); ?>">
        <title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' :'; } ?> <?php bloginfo('name'); ?></title>

        <link href="//www.google-analytics.com" rel="dns-prefetch">

        <link href="<?php echo get_template_directory_uri(); ?>/img/icons/touch.png" rel="apple-touch-icon-precomposed">

        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="<?php bloginfo('description'); ?>">

        <?php wp_head(); ?>

    <body <?php body_class(); ?>>

here's the function.php

// Load any external files you have here

function theme_styles() {
    wp_enqueue_style( 'bootstrap_css', 'http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css' );
    wp_enqueue_style( 'b_css', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css' );
    wp_enqueue_style( 'style_css', get_template_directory_uri() . '/style.css' );
}

add_action( 'wp_enqueue_scripts', 'theme_styles' );

function theme_js() {
    wp_enqueue_script( 'bootstrap_js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js');
}

add_action( 'wp_enqueue_scripts', 'themes_js');

add_action('wp_enqueue_scripts', 'add_my_script'); // initiate the function

function add_my_script() {
wp_register_script ( 'colorbox-min' , get_stylesheet_directory_uri() . '/js/jquery.colorbox-min.js', array( 'jquery' ), '1', true );
wp_enqueue_script( 'colorbox-min' );

// Commented out because you probably want to use the minified version of the script
//wp_register_script ( 'colorbox' , get_stylesheet_directory_uri() . '/js/jquery.colorbox.js', array( 'jquery' ), '1', true );
//wp_enqueue_script( 'colorbox' );

wp_register_style ('ihatecolorboxcss', get_stylesheet_directory_uri() . '/ihatecolorbox.css','', '1', 'all');
wp_enqueue_style( 'colorbox' );
}

edit: other place I hooked in a style sheet

function html5blank_styles()
{
    wp_register_style('normalize', get_template_directory_uri() . '/normalize.css', array(), '1.0', 'all');
    wp_enqueue_style('normalize'); //

    wp_register_style('html5blank', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');
    wp_enqueue_style('html5blank');

Body:
You are loading two, this one in functions

wp_enqueue_style( 'style_css', get_template_directory_uri() . '/style.css' );

and this one in your hook, adding v1.0 to the end

wp_register_style('html5blank', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');

Enqueued with different names, but both have the same url


问:
HTML, flex, two divs in a row, force one div to have size of smaller
Subj.

I have two divs (left and right). And I want to make left div something like main one, and force right div to have the same height as a left one, even if it will have more content (and do overflow: hidden). I will appreciate if there is a way to make it with css and html without js.

Here is a little snippet, how my markup is looking:

.parent {
  display: flex;
  flex-direction: row;
  align-items: stretch;
}

.children-1 {
  width: 66.6%;
  background: green;
}

.children-2 {
  width: 33.4%;
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="children-1">
    <p>My content</p>
  </div>

  <div class="children-2">
    <p>a lot of content<p>
    <p>a lot of content</p>
  </div>
</div></code>```

答:
Apply a fixed height to the container and use overflow-y: hidden; on the second child DIV:

.parent {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  height: 200px;
}

.children-1 {
  width: 66.6%;
  background: green;
}

.children-2 {
  width: 33.4%;
  background: yellow;
  overflow-y: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="children-1">
    <p>My content</p>
  </div>

  <div class="children-2">
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
  </div>
</div></code>```

Here's a second version without fixed height, but the HTML structure is changed: There is only one child (the right one), and the contents which were in the first child are now in the parent. It uses absolute positioning for that child element and hides the overflow of the child element - see the actual settings below:

html,
body {
  margin: 0;
}

.parent {
  position: relative;
  padding: 1em;
  background: green;
  overflow-y: hidden;
}

.children-2 {
  width: 33.4%;
  position: absolute;
  right: 0;
  top: 0;
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <p>My content</p>
  <p>My content</p>

  <div class="children-2">
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
  </div>

</div></code>```

Body:
Subj.

I have two divs (left and right). And I want to make left div something like main one, and force right div to have the same height as a left one, even if it will have more content (and do overflow: hidden). I will appreciate if there is a way to make it with css and html without js.

Here is a little snippet, how my markup is looking:

.parent {
  display: flex;
  flex-direction: row;
  align-items: stretch;
}

.children-1 {
  width: 66.6%;
  background: green;
}

.children-2 {
  width: 33.4%;
  background: yellow;
}

My content

a lot of content

a lot of content

Body:
Apply a fixed height to the container and use overflow-y: hidden; on the second child DIV:

.parent {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  height: 200px;
}

.children-1 {
  width: 66.6%;
  background: green;
}

.children-2 {
  width: 33.4%;
  background: yellow;
  overflow-y: hidden;
}

<div class="parent">
  <div class="children-1">
    <p>My content</p>
  </div>

  <div class="children-2">
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
  </div>
</div>

Here's a second version without fixed height, but the HTML structure is changed: There is only one child (the right one), and the contents which were in the first child are now in the parent. It uses absolute positioning for that child element and hides the overflow of the child element - see the actual settings below:

html,
body {
  margin: 0;
}

.parent {
  position: relative;
  padding: 1em;
  background: green;
  overflow-y: hidden;
}

.children-2 {
  width: 33.4%;
  position: absolute;
  right: 0;
  top: 0;
  background: yellow;
}

<div class="parent">
  <p>My content</p>
  <p>My content</p>

  <div class="children-2">
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
  </div>

</div>


问:
Combined Android Project but Maps isn't working on my phone
My partner and I are developing an android project on our own laptops. So we combine our work through GitHub(you probably knew that anyway). So my problem is after we have combined our project, the maps that she added in our app isn't working on my phone. We figured and saw the error/log message saying:

```<code>Ensure that the "Google Maps Android API v2" is enabled.
Ensure that the following Android Key exists:
API Key:
Android Application (<cert_fingerprint>;<package_name>):
</code>```

I have tried changing the API according to what my Android Studio provided for the fingerprint. It didn't work also. Thus, I want to understand the logic behind this. ^^" So if anyone can kindly explain it to me, it will be much appreciated!

P.S.: and if possible to let me know how to fix it too. =)

答:
You have the new google maps key with another application certificate from each developer.

For more information read this link

Body:
My partner and I are developing an android project on our own laptops. So we combine our work through GitHub(you probably knew that anyway). So my problem is after we have combined our project, the maps that she added in our app isn't working on my phone. We figured and saw the error/log message saying:

Ensure that the "Google Maps Android API v2" is enabled.
Ensure that the following Android Key exists:
API Key:
Android Application (<cert_fingerprint>;<package_name>):

I have tried changing the API according to what my Android Studio provided for the fingerprint. It didn't work also. Thus, I want to understand the logic behind this. ^^" So if anyone can kindly explain it to me, it will be much appreciated!

P.S.: and if possible to let me know how to fix it too. =)


问:
SQL - Create new start and stop datetime and combine rows based on other columns
My issue is pretty similar to this question: Find start and end dates when one field changes

However, I've been unable to adapt the code to my situation. Any help would be greatly appreciated.

I have data which contains an ID, a variable called Type, and two datetime fields (one named Start and the other named Stop). This can be found here: http://sqlfiddle.com/#!6/35f43

Values for columns Start and Stop can run consecutively, and I want to combine those records grouping by ID and Type. The issue I currently have is I need to keep ID and Type separate if the Start and Stop datetimes are not consecutive.

For example, in the data on the SQLFiddle link, ID '3' currently has five records with type A with one record of type B in between.

```<code>ID         Start                                Stop               Type
3      2010-03-12 05:10:02.0000000    2010-03-20 12:00:00.0000000   A
3      2010-03-20 12:00:00.0000000    2010-04-07 09:46:30.0000000   A
3      2010-04-07 09:46:30.0000000    2010-05-01 08:13:42.0000000   B
3      2010-05-01 08:13:42.0000000    2010-07-04 09:30:32.0000000   A
3      2010-07-04 09:30:32.0000000    2010-07-06 11:41:38.0000000   A
3      2010-07-06 11:41:38.0000000    2010-07-09 12:51:30.0000000   A
</code>```

I need this to show as:

```<code>ID         Start                                Stop               Type
3      2010-03-12 05:10:02.0000000    2010-04-07 09:46:30.0000000   A
3      2010-04-07 09:46:30.0000000    2010-05-01 08:13:42.0000000   B
3      2010-05-01 08:13:42.0000000    2010-07-09 12:51:30.0000000   A
</code>```

Any ideas?

答:
```<code>;WITH CTE_T AS (
    select *,ROW_NUMBER() OVER(ORDER BY Start) r
        from T A
            where not exists(
                select * from T B
                    WHERE B.ID = A.ID AND B.Start = A.Stop AND B.Type = A.Type
                )
    UNION ALL
    SELECT B.*,A.R fROM CTE_T A
        JOIN T B ON A.Start = B.Stop
            AND B.ID = A.ID  AND B.Type = A.Type
)

SELECT ID,MIN(Start) [Start],MAX(Stop) [Stop],Type FROM CTE_T
GROUP BY ID,TYPE,R
</code>```

Body:
My issue is pretty similar to this question: Find start and end dates when one field changes

However, I've been unable to adapt the code to my situation. Any help would be greatly appreciated.

I have data which contains an ID, a variable called Type, and two datetime fields (one named Start and the other named Stop). This can be found here: http://sqlfiddle.com/#!6/35f43

Values for columns Start and Stop can run consecutively, and I want to combine those records grouping by ID and Type. The issue I currently have is I need to keep ID and Type separate if the Start and Stop datetimes are not consecutive.

For example, in the data on the SQLFiddle link, ID '3' currently has five records with type A with one record of type B in between.

ID         Start                                Stop               Type
3      2010-03-12 05:10:02.0000000    2010-03-20 12:00:00.0000000   A
3      2010-03-20 12:00:00.0000000    2010-04-07 09:46:30.0000000   A
3      2010-04-07 09:46:30.0000000    2010-05-01 08:13:42.0000000   B
3      2010-05-01 08:13:42.0000000    2010-07-04 09:30:32.0000000   A
3      2010-07-04 09:30:32.0000000    2010-07-06 11:41:38.0000000   A
3      2010-07-06 11:41:38.0000000    2010-07-09 12:51:30.0000000   A

I need this to show as:

ID         Start                                Stop               Type
3      2010-03-12 05:10:02.0000000    2010-04-07 09:46:30.0000000   A
3      2010-04-07 09:46:30.0000000    2010-05-01 08:13:42.0000000   B
3      2010-05-01 08:13:42.0000000    2010-07-09 12:51:30.0000000   A

Any ideas?


问:
Create LINQ to entities OrderBy expression on the fly
I'm trying to add the orderby expression on the fly. But when the query below is executed I get the following exception:

System.NotSupportedException: Unable
  to create a constant value of type
  'Closure type'. Only primitive types
  ('such as Int32, String, and Guid')
  are supported in this context.

The strange thing is, I am query exactly those primitive types only.

```<code>string sortBy = HttpContext.Current.Request.QueryString["sidx"];
ParameterExpression prm = Expression.Parameter(typeof(buskerPosting), "posting");
Expression orderByProperty = Expression.Property(prm, sortBy);

// get the paged records
IQueryable<PostingListItemDto> query =
   (from posting in be.buskerPosting
    where posting.buskerAccount.cmsMember.nodeId == m.Id
    orderby orderByProperty
    //orderby posting.Created
    select new PostingListItemDto { Set = posting }).Skip<PostingListItemDto>((page -   1) * pageSize).Take<PostingListItemDto>(pageSize);
</code>```

Hope somebody can shed some light on this!

答:
I wanted to share my implementation using Jon's answer above as a starting point. In this case, rather than sorting by a string property name coming from the presentation layer (since the title of this question isn't specific about that), I am building out an Entity Framework data layer and want to allow its consumer to specify order by properties as lambda expressions. I.E. Rather than passing "sidx", I wanted to be able to use p => p.sidx. I also wanted to be able to pass an unlimited number of order by properties and be able to specify ascending or descending order.

Well my method can accept such a lambda expression as type Expression<Func<T, object>>. That let's me call it the way I want but the problem is, Entity Framework can't translate the expression to SQL unless the second generic parameter is strongly typed. The OrderBy extension method requires two generic parameters: T - the type the property belongs to, and TKey - the type the property returns. So the first step was to modify Jon's example to convert a given Expression<Func<T, object>> to a Expression<Func<T, Tkey>> (once we're working within the context of a query, we can determine the type TKey):

```<code>internal static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> source, Expression<Func<T, object>> sortExp)
{
    //We need to convert the key selector from Expression<Func<T, object>> to a strongly typed Expression<Func<T, TKey>>
    //in order for Entity Framework to be able to translate it to SQL
    MemberExpression orderByMemExp = ExpressionHelpers.RemoveConvert(sortExp.Body) as MemberExpression;
    ParameterExpression sourceParam = sortExp.Parameters[0];

    LambdaExpression orderByLamda = Expression.Lambda(orderByMemExp, new[] { sourceParam });

    MethodInfo orderByMethod = OrderByMethod.MakeGenericMethod(new[] { typeof(T), orderByMemExp.Type });

    //Call OrderBy or OrderByDescending on the source IQueryable<T>
    return (IQueryable<T>)orderByMethod.Invoke(null, new object[] { source, orderByLamda });
}
</code>```

As I mentioned, I want to accept an unlimited number of order by key selectors and also have the ability to specify the ascending or descending direction so I made a wrapper class for the Expression<Func<T, object>> which I named DynamicSortExpression:

```<code>public class DynamicSortExpression<T>
{
    /// <summary>
    /// Creates a new ascending DynamicSortExpression
    /// </summary>
    /// <param name="keySelector">A MemberExpression identifying the property to sort on</param>
    public DynamicSortExpression(Expression<Func<T, object>> keySelector) : this(keySelector, false)
    {
    }

    public DynamicSortExpression(Expression<Func<T, object>> keySelector, bool descending)
    {
        this.KeySelector = keySelector;
        this.Desc = descending;
    }

    /// <summary>
    /// Gets the expression that selects the property of T to sort on
    /// </summary>
    public Expression<Func<T, object>> KeySelector { get; }

    /// <summary>
    /// Gets sort expression is in ascending or descending order
    /// </summary>
    public bool Desc { get; }
}
</code>```

Then I updated the extension method to accept this type and created an overload for OrderBy that receives a List<DynamicSortExpression<T>> and adds them to the query using the extension method(s) one by one.  Here is the final result:

```<code>public static class Extensions
{
    private static readonly MethodInfo OrderByMethod = typeof(Queryable).GetMethods()
                                                        .Where(method => method.Name == "OrderBy")
                                                        .Where(method => method.GetParameters().Length == 2)
                                                        .Single();

    private static readonly MethodInfo OrderByDescMethod = typeof(Queryable).GetMethods()
                                                            .Where(method => method.Name == "OrderByDescending")
                                                            .Where(method => method.GetParameters().Length == 2)
                                                            .Single();

    private static readonly MethodInfo ThenByMethod = typeof(Queryable).GetMethods()
                                                    .Where(method => method.Name == "ThenBy")
                                                    .Where(method => method.GetParameters().Length == 2)
                                                    .Single();

    private static readonly MethodInfo ThenByDescMethod = typeof(Queryable).GetMethods()
                                                    .Where(method => method.Name == "ThenByDescending")
                                                    .Where(method => method.GetParameters().Length == 2)
                                                    .Single();

    internal static IQueryable<T> OrderBy<T>(this IQueryable<T> sourceQuery, List<DynamicSortExpression<T>> orderBy)
    {
        bool isFirst = true;
        foreach (var sortExpression in orderBy)
        {
            if (isFirst)
            {
                sourceQuery = sourceQuery.OrderByDynamic(sortExpression);
                isFirst = false;
            }
            else
                sourceQuery = sourceQuery.ThenByDynamic(sortExpression);
        }

        return sourceQuery;
    }

    internal static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> source, DynamicSortExpression<T> sortExpression)
    {
        //We need to convert the key selector from Expression<Func<T, object>> to a strongly typed Expression<Func<T, TKey>>
        //in order for Entity Framework to be able to translate it to SQL
        MemberExpression orderByMemExp = ExpressionHelpers.RemoveConvert(sortExpression.KeySelector.Body) as MemberExpression;
        ParameterExpression sourceParam = sortExpression.KeySelector.Parameters[0];

        LambdaExpression orderByLamda = Expression.Lambda(orderByMemExp, new[] { sourceParam });

        MethodInfo orderByMethod = sortExpression.Desc ?
                                        OrderByDescMethod.MakeGenericMethod(new[] { typeof(T), orderByMemExp.Type }) :
                                        OrderByMethod.MakeGenericMethod(new[] { typeof(T), orderByMemExp.Type });

        //Call OrderBy or OrderByDescending on the source IQueryable<T>
        return (IQueryable<T>)orderByMethod.Invoke(null, new object[] { source, orderByLamda });
    }

    internal static IQueryable<T> ThenByDynamic<T>(this IQueryable<T> source, DynamicSortExpression<T> sortExpression)
    {
        //We need to convert the key selector from Expression<Func<T, object>> to a strongly typed Expression<Func<T, TKey>>
        //in order for Entity Framework to be able to translate it to SQL
        Expression orderByMemExp = ExpressionHelpers.RemoveConvert(sortExpression.KeySelector.Body) as MemberExpression;
        ParameterExpression sourceParam = sortExpression.KeySelector.Parameters[0];

        LambdaExpression orderByLamda = Expression.Lambda(orderByMemExp, new[] { sourceParam });

        MethodInfo orderByMethod = sortExpression.Desc ?
                                        ThenByDescMethod.MakeGenericMethod(new[] { typeof(T), orderByMemExp.Type }) :
                                        ThenByMethod.MakeGenericMethod(new[] { typeof(T), orderByMemExp.Type });

        //Call OrderBy or OrderByDescending on the source IQueryable<T>
        return (IQueryable<T>)orderByMethod.Invoke(null, new object[] { source, orderByLamda });
    }
}
</code>```

Now my data layer can have a method like List<T> GetList(Expression<Func<T, bool>> where, params DynamicSortExpression<T>[] orderBy) that can be called like

```<code>new MyClass<Person>().GetList(p => p.FirstName == "Billy", //where clause
                              new DynamicSortExpression<Person>(p => p.FirstName),
                              new DynamicSortExpression<Person>(p => p.LastName, true));
</code>```

Where internally, MyClass<T>.GetList builds the query which calls my OrderBy extension method. Something like:

```<code>DBContext.Set<T>().Where(whereParam).OrderBy(orderByParams);
</code>```

The RemoveConvert method is something I yanked out of the EntityFramework source code to recursively remove Convert calls from a MemberExpression:

```<code>internal static Expression RemoveConvert(Expression expression)
{
    System.Diagnostics.Debug.Assert(expression != null);

    while ((expression != null)
            && (expression.NodeType == ExpressionType.Convert
                || expression.NodeType == ExpressionType.ConvertChecked))
    {
        expression = RemoveConvert(((UnaryExpression)expression).Operand);
    }

    return expression;
}
</code>```

I hope this is helpful! Thanks Jon!

Body:
I'm trying to add the orderby expression on the fly. But when the query below is executed I get the following exception:

System.NotSupportedException: Unable
  to create a constant value of type
  'Closure type'. Only primitive types
  ('such as Int32, String, and Guid')
  are supported in this context.

The strange thing is, I am query exactly those primitive types only.

string sortBy = HttpContext.Current.Request.QueryString["sidx"];
ParameterExpression prm = Expression.Parameter(typeof(buskerPosting), "posting");
Expression orderByProperty = Expression.Property(prm, sortBy);

// get the paged records
IQueryable<PostingListItemDto> query =
   (from posting in be.buskerPosting
    where posting.buskerAccount.cmsMember.nodeId == m.Id
    orderby orderByProperty
    //orderby posting.Created
    select new PostingListItemDto { Set = posting }).Skip<PostingListItemDto>((page -   1) * pageSize).Take<PostingListItemDto>(pageSize);

Hope somebody can shed some light on this!

Body:
I wanted to share my implementation using Jon's answer above as a starting point. In this case, rather than sorting by a string property name coming from the presentation layer (since the title of this question isn't specific about that), I am building out an Entity Framework data layer and want to allow its consumer to specify order by properties as lambda expressions. I.E. Rather than passing "sidx", I wanted to be able to use p => p.sidx. I also wanted to be able to pass an unlimited number of order by properties and be able to specify ascending or descending order.

Well my method can accept such a lambda expression as type Expression<Func<T, object>>. That let's me call it the way I want but the problem is, Entity Framework can't translate the expression to SQL unless the second generic parameter is strongly typed. The OrderBy extension method requires two generic parameters: T - the type the property belongs to, and TKey - the type the property returns. So the first step was to modify Jon's example to convert a given Expression<Func<T, object>> to a Expression<Func<T, Tkey>> (once we're working within the context of a query, we can determine the type TKey):

internal static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> source, Expression<Func<T, object>> sortExp)
{
    //We need to convert the key selector from Expression<Func<T, object>> to a strongly typed Expression<Func<T, TKey>>
    //in order for Entity Framework to be able to translate it to SQL
    MemberExpression orderByMemExp = ExpressionHelpers.RemoveConvert(sortExp.Body) as MemberExpression;
    ParameterExpression sourceParam = sortExp.Parameters[0];

    LambdaExpression orderByLamda = Expression.Lambda(orderByMemExp, new[] { sourceParam });

    MethodInfo orderByMethod = OrderByMethod.MakeGenericMethod(new[] { typeof(T), orderByMemExp.Type });

    //Call OrderBy or OrderByDescending on the source IQueryable<T>
    return (IQueryable<T>)orderByMethod.Invoke(null, new object[] { source, orderByLamda });
}

As I mentioned, I want to accept an unlimited number of order by key selectors and also have the ability to specify the ascending or descending direction so I made a wrapper class for the Expression<Func<T, object>> which I named DynamicSortExpression:

public class DynamicSortExpression<T>
{
    /// <summary>
    /// Creates a new ascending DynamicSortExpression
    /// </summary>
    /// <param name="keySelector">A MemberExpression identifying the property to sort on</param>
    public DynamicSortExpression(Expression<Func<T, object>> keySelector) : this(keySelector, false)
    {
    }

    public DynamicSortExpression(Expression<Func<T, object>> keySelector, bool descending)
    {
        this.KeySelector = keySelector;
        this.Desc = descending;
    }

    /// <summary>
    /// Gets the expression that selects the property of T to sort on
    /// </summary>
    public Expression<Func<T, object>> KeySelector { get; }

    /// <summary>
    /// Gets sort expression is in ascending or descending order
    /// </summary>
    public bool Desc { get; }
}

Then I updated the extension method to accept this type and created an overload for OrderBy that receives a List<DynamicSortExpression<T>> and adds them to the query using the extension method(s) one by one.  Here is the final result:

public static class Extensions
{
    private static readonly MethodInfo OrderByMethod = typeof(Queryable).GetMethods()
                                                        .Where(method => method.Name == "OrderBy")
                                                        .Where(method => method.GetParameters().Length == 2)
                                                        .Single();

    private static readonly MethodInfo OrderByDescMethod = typeof(Queryable).GetMethods()
                                                            .Where(method => method.Name == "OrderByDescending")
                                                            .Where(method => method.GetParameters().Length == 2)
                                                            .Single();

    private static readonly MethodInfo ThenByMethod = typeof(Queryable).GetMethods()
                                                    .Where(method => method.Name == "ThenBy")
                                                    .Where(method => method.GetParameters().Length == 2)
                                                    .Single();

    private static readonly MethodInfo ThenByDescMethod = typeof(Queryable).GetMethods()
                                                    .Where(method => method.Name == "ThenByDescending")
                                                    .Where(method => method.GetParameters().Length == 2)
                                                    .Single();

    internal static IQueryable<T> OrderBy<T>(this IQueryable<T> sourceQuery, List<DynamicSortExpression<T>> orderBy)
    {
        bool isFirst = true;
        foreach (var sortExpression in orderBy)
        {
            if (isFirst)
            {
                sourceQuery = sourceQuery.OrderByDynamic(sortExpression);
                isFirst = false;
            }
            else
                sourceQuery = sourceQuery.ThenByDynamic(sortExpression);
        }

        return sourceQuery;
    }

    internal static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> source, DynamicSortExpression<T> sortExpression)
    {
        //We need to convert the key selector from Expression<Func<T, object>> to a strongly typed Expression<Func<T, TKey>>
        //in order for Entity Framework to be able to translate it to SQL
        MemberExpression orderByMemExp = ExpressionHelpers.RemoveConvert(sortExpression.KeySelector.Body) as MemberExpression;
        ParameterExpression sourceParam = sortExpression.KeySelector.Parameters[0];

        LambdaExpression orderByLamda = Expression.Lambda(orderByMemExp, new[] { sourceParam });

        MethodInfo orderByMethod = sortExpression.Desc ?
                                        OrderByDescMethod.MakeGenericMethod(new[] { typeof(T), orderByMemExp.Type }) :
                                        OrderByMethod.MakeGenericMethod(new[] { typeof(T), orderByMemExp.Type });

        //Call OrderBy or OrderByDescending on the source IQueryable<T>
        return (IQueryable<T>)orderByMethod.Invoke(null, new object[] { source, orderByLamda });
    }

    internal static IQueryable<T> ThenByDynamic<T>(this IQueryable<T> source, DynamicSortExpression<T> sortExpression)
    {
        //We need to convert the key selector from Expression<Func<T, object>> to a strongly typed Expression<Func<T, TKey>>
        //in order for Entity Framework to be able to translate it to SQL
        Expression orderByMemExp = ExpressionHelpers.RemoveConvert(sortExpression.KeySelector.Body) as MemberExpression;
        ParameterExpression sourceParam = sortExpression.KeySelector.Parameters[0];

        LambdaExpression orderByLamda = Expression.Lambda(orderByMemExp, new[] { sourceParam });

        MethodInfo orderByMethod = sortExpression.Desc ?
                                        ThenByDescMethod.MakeGenericMethod(new[] { typeof(T), orderByMemExp.Type }) :
                                        ThenByMethod.MakeGenericMethod(new[] { typeof(T), orderByMemExp.Type });

        //Call OrderBy or OrderByDescending on the source IQueryable<T>
        return (IQueryable<T>)orderByMethod.Invoke(null, new object[] { source, orderByLamda });
    }
}

Now my data layer can have a method like List<T> GetList(Expression<Func<T, bool>> where, params DynamicSortExpression<T>[] orderBy) that can be called like

new MyClass<Person>().GetList(p => p.FirstName == "Billy", //where clause
                              new DynamicSortExpression<Person>(p => p.FirstName),
                              new DynamicSortExpression<Person>(p => p.LastName, true));

Where internally, MyClass<T>.GetList builds the query which calls my OrderBy extension method. Something like:

DBContext.Set<T>().Where(whereParam).OrderBy(orderByParams);

The RemoveConvert method is something I yanked out of the EntityFramework source code to recursively remove Convert calls from a MemberExpression:

internal static Expression RemoveConvert(Expression expression)
{
    System.Diagnostics.Debug.Assert(expression != null);

    while ((expression != null)
            && (expression.NodeType == ExpressionType.Convert
                || expression.NodeType == ExpressionType.ConvertChecked))
    {
        expression = RemoveConvert(((UnaryExpression)expression).Operand);
    }

    return expression;
}

I hope this is helpful! Thanks Jon!

ContentLicense: CC BY-SA 4.0


问:
Retrieving servlet context, session and request in a POJO outside container
Is there any way to retrieve a session from a POJO? Or ultimately to retrieve a bean from a POJO.

To clarify:

Basically I am creating a bean from a servlet and I need to access the properties of that bean from outside of the web container (from a POJO). I cannot pass the request to the pojo; and the request is needed to retrieve the session.

More specifically I have a web application that uses the Cactus framework to run JUnit tests from a web interface. However the servlet that invokes the JUnit test runner is compiled in a jar; I added extra drop down menus to change settings from which the JUnit test will read from to switch between different environments (WLI clusters), so given that the runner servlet is already compiled I cannot modify it to handle the extra parameters from the multiple environments. I have tried the persistence approach of writing to a .dat file fro which the JUnit test will read from by way of a Reader class; also I have have tried the bean approach which ultimately was not accessible from the JUnit test.

答:
Assuming that you are referring to Servlet programming ....

There's no direct way to get from a POJO to the Session. You need to get the Session from the HttpServletRequest object.

There are 2 popular solutions that I've seen for dealing with this.

First option is to create a context object of some sort that contains the Session. This context is then passed along down into your business layer so that your POJOs can get this information if they need it.

Second option is to leverage ThreadLocal storage. Often the session is placed on ThreadLocal storage by a filter or interceptor. Then any object in your system can fetch it from the thread. This pattern shows up in a lot of the web frameworks like Spring and Struts.


问:
Convert UTC offset to timezone or date
A head scratcher for you.

I am grabbing geo IP data from IPInfoDB's API and it returns a timezone offset from UTC including DST (if currently reflected).

For example, I live in EST (-5) and currently it's DST, so the geo IP API returns (-04:00) as the offset.

This is wonderful since DST is a freaking headache. But to my surprise, it caused another headache.

I load this data in PHP to be passed via AJAX to the application. I would like to have the live local time of the IP address on the app.

I have that all set perfectly, but I am going crazy trying to figure out how to set the PHP timezone to match the offset so I can just grab the current hours date('H'); and minutes date('i'); to pass to via AJAX.

I am unsure if there is a specific function that can just give me the current hours and minutes based on that offset or if there is a practical way to set the timezone based on the offset (which will have DST already applied if is in effect).

I've been searching and searching Google to find an answer to this, but what I am doing is more specific since DST is already applied.

I found one function on PHP.net that seems to do the trick (it works for my timezone and returns the correct time) although for other timezones such as PST, it's returning 1 hour later than it should be even though the offset is correct (-07:00 with DST).

The timezone returned from the function is Chile/EasterIsland which I have a feeling is the cause. If I could, I would make this only work for the USA, but I do need it to be worldwide.

This is the function I have now. Please excuse the extremely messy code. I have been playing around with tons of things over the last few hours trying to figure out a solution.

Most of the functionality was found online.

```<code>function offsetToTZ($offset) {
switch((string) $offset) {
    case '-04:30' : return 'America/Caracas'; break;
    case '-03:30' : return 'Canada/Newfoundland'; break;
    case '+03:30' : return 'Asia/Tehran'; break;
    case '+04:30' : return 'Asia/Kabul'; break;
    case '+05:30' : return 'Asia/Kolkata'; break;
    case '+05:45' : return 'Asia/Kathmandu'; break;
    case '+09:30' : return 'Australia/Darwin'; break;
}
$offset = (int) str_replace(array('0',0,':00',00,'30',30,'45',45,':','+'),'', (string) $offset);

$offset = $offset*60*60;
$abbrarray = timezone_abbreviations_list();
foreach ($abbrarray as $abbr) {
    foreach($abbr as $city) {
        if($city['offset'] == $offset) {
            return $city['timezone_id'];
        }
    }
}
return false;
}
</code>```

I included the switch/case for certain timezones that are :30 and :45 out there. There may be a way to include that also without the need of the switch/case.

NOTE: The offsets are always returned as such +00:00 or -00:00 from the geo IP API.

I would appreciate any help or a point in the right direction. I'm not very novice with PHP, but offsets are a new story for me. Thanks!

答:
Nowadays the DateTimeZone constructor can explicitly accept a UTC offset, which I understand you have.

So just:

```<code>$timeZone = new DateTimeZone('+0100');
</code>```

Documentation:

http://php.net/manual/en/datetimezone.construct.php

Note: per that documentation link, this new constructor usage has been available since PHP version 5.5.10.

Title: Convert UTC offset to timezone or date

Body:
A head scratcher for you.

I am grabbing geo IP data from IPInfoDB's API and it returns a timezone offset from UTC including DST (if currently reflected).

For example, I live in EST (-5) and currently it's DST, so the geo IP API returns (-04:00) as the offset.

This is wonderful since DST is a freaking headache. But to my surprise, it caused another headache.

I load this data in PHP to be passed via AJAX to the application. I would like to have the live local time of the IP address on the app.

I have that all set perfectly, but I am going crazy trying to figure out how to set the PHP timezone to match the offset so I can just grab the current hours date('H'); and minutes date('i'); to pass to via AJAX.

I am unsure if there is a specific function that can just give me the current hours and minutes based on that offset or if there is a practical way to set the timezone based on the offset (which will have DST already applied if is in effect).

I've been searching and searching Google to find an answer to this, but what I am doing is more specific since DST is already applied.

I found one function on PHP.net that seems to do the trick (it works for my timezone and returns the correct time) although for other timezones such as PST, it's returning 1 hour later than it should be even though the offset is correct (-07:00 with DST).

The timezone returned from the function is Chile/EasterIsland which I have a feeling is the cause. If I could, I would make this only work for the USA, but I do need it to be worldwide.

This is the function I have now. Please excuse the extremely messy code. I have been playing around with tons of things over the last few hours trying to figure out a solution.

Most of the functionality was found online.

function offsetToTZ($offset) {
switch((string) $offset) {
    case '-04:30' : return 'America/Caracas'; break;
    case '-03:30' : return 'Canada/Newfoundland'; break;
    case '+03:30' : return 'Asia/Tehran'; break;
    case '+04:30' : return 'Asia/Kabul'; break;
    case '+05:30' : return 'Asia/Kolkata'; break;
    case '+05:45' : return 'Asia/Kathmandu'; break;
    case '+09:30' : return 'Australia/Darwin'; break;
}
$offset = (int) str_replace(array('0',0,':00',00,'30',30,'45',45,':','+'),'', (string) $offset);

$offset = $offset*60*60;
$abbrarray = timezone_abbreviations_list();
foreach ($abbrarray as $abbr) {
    foreach($abbr as $city) {
        if($city['offset'] == $offset) {
            return $city['timezone_id'];
        }
    }
}
return false;
}

I included the switch/case for certain timezones that are :30 and :45 out there. There may be a way to include that also without the need of the switch/case.

NOTE: The offsets are always returned as such +00:00 or -00:00 from the geo IP API.

I would appreciate any help or a point in the right direction. I'm not very novice with PHP, but offsets are a new story for me. Thanks!

Body:
Nowadays the DateTimeZone constructor can explicitly accept a UTC offset, which I understand you have.

So just:

$timeZone = new DateTimeZone('+0100');

Documentation:

http://php.net/manual/en/datetimezone.construct.php

Note: per that documentation link, this new constructor usage has been available since PHP version 5.5.10.


问:
Delivered messages in Twilio Logs but it's not actually delivered
I have a local number in the US, I tried to send a SMS message to a US phone number, and the message is received, but when I try to send a message to Saudi Arabia, I can't receive any messages, I tried to text several numbers from several Carriers, it does not work. I tried to send a message from my phone number (Saudi) to the US number (Twilio) and it's received.

 here is the image with message details

why I can't send message to phone numbers in Saudi Arabia?

答:
Twilio developer evangelist here.

I recommend checking the SMS guidelines for Saudi Arabia. Some highlights include:

Saudi Arabian networks have implemented strong filtering. These filters will block most messages which come from numeric sender IDs, messages which contain objectionable content, and messages which contain URLs. Furthermore, if a message is sent that has identical content to a recent message, this message will be blocked.

We strongly encourage customers who wish to deliver messages to users in Saudi Arabia to use a preregistered Sender ID.

I see that you're sending verification codes. If this is for phone verification or two factor authentication, can I suggest using our Verify or Two Factor Authentication APIs? They are already optimised for sending codes all around the world, and should make building that feature easier for you.

Otherwise I would get in touch with Twilio support who can advise you further on sending messages to Saudi Arabia.


问:
SELECT WHERE Statement
I am trying to select the a value from the database such as

```<code> $stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = (the most recent value entered ');
</code>```

i tried :

```<code>$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = "26" ');
</code>```

and it was successful. However whenever I try something like  :

```<code>$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = :acc_id');
</code>```

or

```<code>$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = $acc_id ');
</code>```

i get the following error :

```<code>core.js:1350 ERROR SyntaxError: Unexpected token S in JSON at position 0
at JSON.parse (<anonymous>)
</code>```

my TS code :

```<code>load()
{
this.http.get('http://localhost:10080/ionic/patients.php')
  .map(res => res.json())
  .subscribe(data =>
  {
     this.items = data;
  });
 }

  viewEntry(param)
{
 this.navCtrl.push('AccInfoPage',param);
}
</code>```

and this is my HTML:

```<code><ion-item *ngFor="let item of items">
<h2>{{ item.acc_id }} </h2>
<button ion-button color="primary" item-right (click)="viewEntry({ account: item })">View</button>
 </ion-item>
</code>```

What am I doing wrong ? How can I fix it ??
 Thank you in advance!

答:
If you want to create and execute a prepared statement, you need to prepare the query first, bind parameters and then execute.</p>

```<code>$stmt = $pdo->prepare('SELECT acc_id FROM account_info WHERE acc_id = :acc_id');
$stmt->execute([':acc_id' => 26]);
$result = $stmt->fetchAll();
</code>```

Title: SELECT WHERE Statement

Body:
I am trying to select the a value from the database such as

 $stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = (the most recent value entered ');

i tried :

$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = "26" ');

and it was successful. However whenever I try something like  :

$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = :acc_id');

or

$stmt = $pdo->query('SELECT acc_id FROM account_info WHERE acc_id = $acc_id ');

i get the following error :

core.js:1350 ERROR SyntaxError: Unexpected token S in JSON at position 0
at JSON.parse (<anonymous>)

my TS code :

load()
{
this.http.get('http://localhost:10080/ionic/patients.php')
  .map(res => res.json())
  .subscribe(data =>
  {
     this.items = data;
  });
 }

  viewEntry(param)
{
 this.navCtrl.push('AccInfoPage',param);
}

and this is my HTML:

<ion-item *ngFor="let item of items">

{{ item.acc_id }}

<button ion-button color="primary" item-right (click)="viewEntry({ account: item })">View</button>
 </ion-item>

What am I doing wrong ? How can I fix it ??
 Thank you in advance!

Body:
If you want to create and execute a prepared statement, you need to prepare the query first, bind parameters and then execute.

$stmt = $pdo->prepare('SELECT acc_id FROM account_info WHERE acc_id = :acc_id');
$stmt->execute([':acc_id' => 26]);
$result = $stmt->fetchAll();


问:
create a folder on an SD card
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

```<code>public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}
</code>```

答:
```<code>if (!isDirectoryCreated) {
    isDirectoryCreated = appDirectory.mkdirs();
</code>```

change this to:

```<code>if (!isDirectoryCreated) {
    appDirectory.mkdirs();
</code>```

Hope this works

Title: create a folder on an SD card

Body:
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}

Body:
if (!isDirectoryCreated) {
    isDirectoryCreated = appDirectory.mkdirs();

change this to:

if (!isDirectoryCreated) {
    appDirectory.mkdirs();

Hope this works