问:
Create Makefile from build configuration
Does Xcode support exporting a build configuration (compiler & linker options and flags) to a Makefile? Or is there a 3rd party implementation available for such task?

We do most of our (native code) development with Xcode, but we need to also compile it against Windows / Linux libraries. Generally we have valid build configurations in Xcode, and we manually edit Makefiles before committing code modifications. This process is error prone and creates undesired differences between development environment and our build system.

Automatically exporting the build configurations to Makefiles would greatly simplify our flow.

答:
I think your answer is xcodebuild -showBuildSettings

```<code>$ xcodebuild -showBuildSettings
Build settings for action build and target YourApp:
ACTION = build
AD_HOC_CODE_SIGNING_ALLOWED = NO
ALTERNATE_GROUP = staff
ALTERNATE_MODE = u+w,go-w,a+rX
ALTERNATE_OWNER = Stanislaw
...
</code>```

You can combine it with normal options like -scheme, -configuration, -target etc.

Also people try to work with so called .xcconfig files when it comes about injection of some custom flags. This path can get you somewhere but is not a super convenient way of doing a cross-platform development because they work only on Mac. See this for example: Using xcconfig files for your XCode Project.

Another indirect way of getting the information is to get a dump of all compilation commands from Xcode, see this answer: How can I get all the compile commands from Xcode?.

As far as I know, Xcode is not really friendly when it comes to dealing with all of its flags separately.

Another option to consider is to switch from Makefiles to CMake. CMake is not perfect but so far it seems to be the best tool out there: it can generate Xcode projects and it can help you a lot in creating your libraries targeted for different platforms.

Body:
I think your answer is xcodebuild -showBuildSettings

$ xcodebuild -showBuildSettings
Build settings for action build and target YourApp:
ACTION = build
AD_HOC_CODE_SIGNING_ALLOWED = NO
ALTERNATE_GROUP = staff
ALTERNATE_MODE = u+w,go-w,a+rX
ALTERNATE_OWNER = Stanislaw
...

You can combine it with normal options like -scheme, -configuration, -target etc.

Also people try to work with so called .xcconfig files when it comes about injection of some custom flags. This path can get you somewhere but is not a super convenient way of doing a cross-platform development because they work only on Mac. See this for example: Using xcconfig files for your XCode Project.

Another indirect way of getting the information is to get a dump of all compilation commands from Xcode, see this answer: How can I get all the compile commands from Xcode?.

As far as I know, Xcode is not really friendly when it comes to dealing with all of its flags separately.

Another option to consider is to switch from Makefiles to CMake. CMake is not perfect but so far it seems to be the best tool out there: it can generate Xcode projects and it can help you a lot in creating your libraries targeted for different platforms.


来源: stackexchange

问:
How to reset AUTO_INCREMENT in MySQL for all tables within a DB?
Is there a way to run this or similiar AUTO_INCREMENT command for all tables in a database?</p>

```<code>ALTER TABLE tablename AUTO_INCREMENT = 1
</code>```

答:
Try this:

```<code>SELECT GROUP_CONCAT(`t`.`query` SEPARATOR '; ')
FROM
    (
        SELECT
            CONCAT('ALTER TABLE `', `a`.`table_name`, '` AUTO_INCREMENT = 1') AS `query`,
            '1' AS `id`
        FROM `information_schema`.`tables` AS `a`
        WHERE `a`.`TABLE_SCHEMA` = 'my_database' # <<< change this to your target database
          #AND `a`.`TABLE_TYPE` = 'BASE TABLE' << optional
          AND `a`.`AUTO_INCREMENT` IS NOT NULL
    ) AS `t`
GROUP BY `t`.`id`
</code>```

This will generate a query for each table, but will not run the queries, so you will have to run the generated queries yourself.

Result will look like this:

```<code>ALTER TABLE `tablename1` AUTO_INCREMENT = 1; ALTER TABLE `tablename2` AUTO_INCREMENT = 1; ALTER TABLE `tablename3` AUTO_INCREMENT = 1;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to run this or similiar AUTO_INCREMENT command for all tables in a database?

ALTER TABLE tablename AUTO_INCREMENT = 1

Body:
Try this:

SELECT GROUP_CONCAT(`t`.`query` SEPARATOR '; ')
FROM
    (
        SELECT
            CONCAT('ALTER TABLE `', `a`.`table_name`, '` AUTO_INCREMENT = 1') AS `query`,
            '1' AS `id`
        FROM `information_schema`.`tables` AS `a`
        WHERE `a`.`TABLE_SCHEMA` = 'my_database' # <<< change this to your target database
          #AND `a`.`TABLE_TYPE` = 'BASE TABLE' << optional
          AND `a`.`AUTO_INCREMENT` IS NOT NULL
    ) AS `t`
GROUP BY `t`.`id`

This will generate a query for each table, but will not run the queries, so you will have to run the generated queries yourself.

Result will look like this:

ALTER TABLE `tablename1` AUTO_INCREMENT = 1; ALTER TABLE `tablename2` AUTO_INCREMENT = 1; ALTER TABLE `tablename3` AUTO_INCREMENT = 1;

ContentLicense: CC BY-SA 4.0


问:
Xpages setvalue bug?

My database allow Anonymous to access the database and submit form to do process
It have 3 roles inside [Applicant],[Admin],[Reviewer]

problem:

I need to update "Email" field by combining 3 different "mail" field to combine it. So i use add element but it seem save wrong data, it give an extra [applicant]. Attached image will display how it display

```<code>var v;
//  Update mail 1 and mail 2 and mail3 into Email field!
if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)   //all not empty
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")===null && document1.getValue("Mail3")=="")
)   //  only have mail 1
    {
        document1.replaceItemValue("Email", document1.getValue("Mail1")+"@brookedockyard.com.my")
    }
else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")==null && document1.getValue("Mail3")=="")
)   //  only have mail 1 and mail 2
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)       //  only have mail 1 and mail 3
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

    }
</code>```

i am using serverside javascript to save document. But during save it add extra information inside the system.

答:
Where is your Vector (v) created? You're just adding elements to that existing Vector, so your code (Form setting if using computeWithForm, XPage setting, SSJS code) must be initialising that Vector with an "[Applicant]" value or retrieving a Vector that already includes the "[Applicant]" value.

The chances of IBM code adding "[Applicant]" to the Item during the setValue() method are nil. The bug is almost certainly in your application code, not introduced by setValue(). Eclipse search should help identify where application code is setting that value.

Title: Xpages setvalue bug?

Body:
My database allow Anonymous to access the database and submit form to do process
It have 3 roles inside [Applicant],[Admin],[Reviewer]

problem:

I need to update "Email" field by combining 3 different "mail" field to combine it. So i use add element but it seem save wrong data, it give an extra [applicant]. Attached image will display how it display

var v;
//  Update mail 1 and mail 2 and mail3 into Email field!
if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)   //all not empty
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")===null && document1.getValue("Mail3")=="")
)   //  only have mail 1
    {
        document1.replaceItemValue("Email", document1.getValue("Mail1")+"@brookedockyard.com.my")
    }
else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")==null && document1.getValue("Mail3")=="")
)   //  only have mail 1 and mail 2
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)       //  only have mail 1 and mail 3
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

    }

i am using serverside javascript to save document. But during save it add extra information inside the system.


问:
Is <Password Type="">*****</Password> in XML is correct or not, if correct then what is the meaning of this?
I am having a XML in which I have *****, here type is just a blank string so what it means that?</p>

答:
It's correct XML (at least if you replace the typographical quotes by ASCII quotes: <Password Type="">****</Password>).

As to what it means, XML means whatever the sender and recipient agree to make it mean. Consult the documentation for the particular XML vocabulary or document type.


问:
Does anyone know how to access the ringer and vibrate settings for WP7 in code?
I'm doing a location aware app that will turn on and off the ringer and vibration according to location, I cannot find how to access these features in code.</p>

答: That's not possible with the current SDK.</p>

ContentLicense: CC BY-SA 2.5


问:
issue while taking photo wtth flash On using AVCapturePhotoOutput
I am working on camera app. i am using AVCapturePhotoOutput for ios 10.x device and AVCaptureStillImageOutput for below 10.x devices.

I am using below capture settings while capturing Photo

```<code>let settings = AVCapturePhotoSettings()

let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first!
        let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType,
                             kCVPixelBufferWidthKey as String: 1080,
                             kCVPixelBufferHeightKey as String: 1080,
                             ]
settings.previewPhotoFormat = previewFormat
settings.isHighResolutionPhotoEnabled = true
settings.flashMode = .on
settings.isAutoStillImageStabilizationEnabled = true
self.captureOutputPhoto?.capturePhoto(with: settings, delegate: self)
</code>```

when i am try to capture photo using above setting

```<code>captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error
</code>```

above delegate throws error first time. I am beginner for AVCapturePhotoSettings. the problem is occurs after every successful photo capture with flash mode.

答:
From Apple documentation:

You may not enable image stabilization if the flash mode is
  on
  . (Enabling the flash takes priority over the
  isAutoStillImageStabilizationEnabled
   setting.)

Not sure, if it should throw error, but you can try to remove this string

```<code>settings.isAutoStillImageStabilizationEnabled = true
</code>```

Body:
I am working on camera app. i am using AVCapturePhotoOutput for ios 10.x device and AVCaptureStillImageOutput for below 10.x devices.

I am using below capture settings while capturing Photo

let settings = AVCapturePhotoSettings()

let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first!
        let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType,
                             kCVPixelBufferWidthKey as String: 1080,
                             kCVPixelBufferHeightKey as String: 1080,
                             ]
settings.previewPhotoFormat = previewFormat
settings.isHighResolutionPhotoEnabled = true
settings.flashMode = .on
settings.isAutoStillImageStabilizationEnabled = true
self.captureOutputPhoto?.capturePhoto(with: settings, delegate: self)

when i am try to capture photo using above setting

captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error

above delegate throws error first time. I am beginner for AVCapturePhotoSettings. the problem is occurs after every successful photo capture with flash mode.

Body:
From Apple documentation:

You may not enable image stabilization if the flash mode is
  on
  . (Enabling the flash takes priority over the
  isAutoStillImageStabilizationEnabled
   setting.)

Not sure, if it should throw error, but you can try to remove this string

settings.isAutoStillImageStabilizationEnabled = true


问:
the simcardio is not available in java 1.7?
I am trying to work the Java smartcardio API but I can not find its classes in Java 1.7.  At this page stands it is in JSR 268 which was released on 11 Dec, 2006
https://docs.oracle.com/javase/7/docs/jre/api/security/smartcardio/spec/
Do someone know the reason why I can not import the ATR classes? Do I have to import the api? if yes where can I find the jar?

答: Most probably Eclipse is fitlering requested packages. To check that out, go to Window->Preferences->Java->Appearance->TypeFilters - remove required package from filter list and/or uncheck Hide forbidden references/Hide dscouraged references on the bottom. Now classes are available in my case.


问:
Where to pass an id when testing editing functions using $this->JSON('PUT', 'url',[])
I am writing Laravel 5.4 tests, I need to test the update method and I am not sure where to pass the $id for the record to be edited. When testing the store method, I just used this

```<code>$this->json('POST', "/example/url", [(form input here)]
</code>```

It works fine, for the update, I do this,

```<code>$this->json('PUT', "/example/url", [(form input here)]
</code>```

but for it to work I need to pass an id for the record I want edited. So ideally, I want to create a record using factories, then after I call the update method in the test I will assert that the fields have been edited.

```<code>$record = factory(Record::class)->create(['name' => 'New Name']);

$response = $this->json('PUT', "/example/url",
             ['name' => 'Edited Name']);
// I should pass the record->id here, I just don't know how

$this->assertDatabaseHas('records', ['name' => 'Edited Name']);
$this->assertDatabaseMissing('records', ['name' => 'New Name']);
</code>```

答:
The id should be passed as part of of the URL,

e.g; $this->json('PUT', "/example/url/{id}", [(form input here)]

Body:
I am writing Laravel 5.4 tests, I need to test the update method and I am not sure where to pass the $id for the record to be edited. When testing the store method, I just used this

$this->json('POST', "/example/url", [(form input here)]

It works fine, for the update, I do this,

$this->json('PUT', "/example/url", [(form input here)]

but for it to work I need to pass an id for the record I want edited. So ideally, I want to create a record using factories, then after I call the update method in the test I will assert that the fields have been edited.

$record = factory(Record::class)->create(['name' => 'New Name']);

$response = $this->json('PUT', "/example/url",
             ['name' => 'Edited Name']);
// I should pass the record->id here, I just don't know how

$this->assertDatabaseHas('records', ['name' => 'Edited Name']);
$this->assertDatabaseMissing('records', ['name' => 'New Name']);


问:
React Native: How to make Listview with with local images
I made an album that looks sort of like this:

```<code><ScrollView>
  <Image1
     <Text1>
        smth
     </Text1>    />

  <Image2
     <Text2>
        smthElse
     </Text2>    />' ... and so on 20 times.
</code>```

I have 5 albums, which I access with tabs on top.
The problem is that sometimes when I switch between the tabs, some images are blank and don't load. The images are all required like this:

```<code>source={require('../assets/Image1.png')}
</code>```

I want them to be required from the app and not via uri.

I thought the problem is because of the memory and on weaker phones it's possible that they don't always load, because I use a ScrollView and it loads all the images at once. I read that a ListView quite solve my problem, but I can't figure out how to make a ListView that renders 20 specific images with a specific text for each one.

If anyone can give me some clues it would be much appreciated.

Thank you !

答:
In order to use <ListView> You can require all the images on your .js file. On the top of your .js file you can do is

index.js

```<code>import React, { Component } from 'react';
import {Listview} from 'react-native'; //Import your other imports ofcourse

// Require all your images here
const image1 = require('../assets/Image1.png')
const image2 = require('../assets/Image2.png')

//.. And so on
export default class ClassName extends Component{
//...
}
</code>```

Next is create an array object and add it to your constructor  on your index.js like so

index.js

```<code>import React, { Component } from 'react';
import {Listview} from 'react-native'; //Import your other imports ofcourse

// Require all your images here
const image1 = require('../assets/Image1.png')
const image2 = require('../assets/Image2.png')

var data = [{title:"You image title", image: image1}, {title:"Your Image title",image: image2}]

export default class ClassName extends Component{
   constructor(props) {
     super(props);
     const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
     this.state = {
       dataSource: ds.cloneWithRows(data),
     };
  }
}
</code>```

Next Create a Row.js

Row.js

```<code>import React from 'react'
import { StyleSheet, Dimensions, Platform, Image, View, Text } from 'react-native';
const Row = (props) => (
  <View style={{flex:1, flexDirection: 'row'}}> //Don't forget this
    <Image source={props.image}>
      <Text>{props.title}</Text>
    </Image>
  </View>
)

export default Row
</code>```

Lastly Import your Row.js file on your index.js and add the <ListView> on your render()

index.js

```<code>import React, { Component } from 'react';
import {View,Listview} from 'react-native'; //Import your other imports ofcourse
import Row from './Row'; //If it's on the same folder

// Require all your images here
const image1 = require('../assets/Image1.png')
const image2 = require('../assets/Image2.png')

var data = [{title:"You image title", image: image1}, {title:"Your Image title",image: image2}]

export default class ClassName extends Component{
   constructor(props) {
     super(props);
     const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
     this.state = {
       dataSource: ds.cloneWithRows(data),
     };
  }
  render(){
     <View>
       <ListView
         style={{flex:1}} //Don't forget this too
         dataSource={this.state.dataSource}
         renderRow={(data) => <Row {...data} />}
       />
     </View>
  }
}
</code>```

Hope this helps you. Cheers!

Body:
I made an album that looks sort of like this:

<ScrollView>
  <Image1
     <Text1>
        smth
     </Text1>    />

  <Image2
     <Text2>
        smthElse
     </Text2>    />' ... and so on 20 times.

I have 5 albums, which I access with tabs on top.
The problem is that sometimes when I switch between the tabs, some images are blank and don't load. The images are all required like this:

source={require('../assets/Image1.png')}

I want them to be required from the app and not via uri.

I thought the problem is because of the memory and on weaker phones it's possible that they don't always load, because I use a ScrollView and it loads all the images at once. I read that a ListView quite solve my problem, but I can't figure out how to make a ListView that renders 20 specific images with a specific text for each one.

If anyone can give me some clues it would be much appreciated.

Thank you !

Body:
In order to use <ListView> You can require all the images on your .js file. On the top of your .js file you can do is

index.js

import React, { Component } from 'react';
import {Listview} from 'react-native'; //Import your other imports ofcourse

// Require all your images here
const image1 = require('../assets/Image1.png')
const image2 = require('../assets/Image2.png')

//.. And so on
export default class ClassName extends Component{
//...
}

Next is create an array object and add it to your constructor  on your index.js like so

index.js

import React, { Component } from 'react';
import {Listview} from 'react-native'; //Import your other imports ofcourse

// Require all your images here
const image1 = require('../assets/Image1.png')
const image2 = require('../assets/Image2.png')

var data = [{title:"You image title", image: image1}, {title:"Your Image title",image: image2}]

export default class ClassName extends Component{
   constructor(props) {
     super(props);
     const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
     this.state = {
       dataSource: ds.cloneWithRows(data),
     };
  }
}

Next Create a Row.js

Row.js

import React from 'react'
import { StyleSheet, Dimensions, Platform, Image, View, Text } from 'react-native';
const Row = (props) => (
  <View style={{flex:1, flexDirection: 'row'}}> //Don't forget this
    <Image source={props.image}>
      <Text>{props.title}</Text>
    </Image>
  </View>
)

export default Row

Lastly Import your Row.js file on your index.js and add the <ListView> on your render()

index.js

import React, { Component } from 'react';
import {View,Listview} from 'react-native'; //Import your other imports ofcourse
import Row from './Row'; //If it's on the same folder

// Require all your images here
const image1 = require('../assets/Image1.png')
const image2 = require('../assets/Image2.png')

var data = [{title:"You image title", image: image1}, {title:"Your Image title",image: image2}]

export default class ClassName extends Component{
   constructor(props) {
     super(props);
     const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
     this.state = {
       dataSource: ds.cloneWithRows(data),
     };
  }
  render(){
     <View>
       <ListView
         style={{flex:1}} //Don't forget this too
         dataSource={this.state.dataSource}
         renderRow={(data) => <Row {...data} />}
       />
     </View>
  }
}

Hope this helps you. Cheers!


问:
Jackson: deserialize epoch to LocalDate
I have following JSON:

```<code>{
      "id" : "1",
      "birthday" : 401280850089
}
</code>```

And POJO class:

```<code>public class FbProfile {
    long id;
    @JsonDeserialize(using = LocalDateDeserializer.class)
    LocalDate birthday;
}
</code>```

I am using Jackson to do deserialization:

```<code>public FbProfile loadFbProfile(File file) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    FbProfile profile = mapper.readValue(file, FbProfile.class);
    return profile;
}
</code>```

But it throws an exception:

com.fasterxml.jackson.databind.JsonMappingException: Unexpected token
  (VALUE_NUMBER_INT), expected VALUE_STRING: Expected array or string.

How can I deserialize epoch to LocalDate? I would like to add that if I change the datatype from LocalDate to java.util.Date it works perfectly fine. So maybe it's better to deserialize to java.util.Date and create the getter and setter which will do the conversion to/from LocalDate.

答:
I've managed to do it writing my own deserializer (thank you @Ole V.V. to point me to the post Java 8 LocalDate Jackson format):

```<code>public class LocalDateTimeFromEpochDeserializer extends StdDeserializer<LocalDateTime> {

    private static final long serialVersionUID = 1L;

    protected LocalDateTimeFromEpochDeserializer() {
        super(LocalDate.class);
    }

    @Override
    public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        return Instant.ofEpochMilli(jp.readValueAs(Long.class)).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

}
</code>```

Notice about timezone is also very useful. Thank you!

The still open question is if it can be done without writing own deserializer?

Title: Jackson: deserialize epoch to LocalDate

Body:
I have following JSON:

{
      "id" : "1",
      "birthday" : 401280850089
}

And POJO class:

public class FbProfile {
    long id;
    @JsonDeserialize(using = LocalDateDeserializer.class)
    LocalDate birthday;
}

I am using Jackson to do deserialization:

public FbProfile loadFbProfile(File file) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    FbProfile profile = mapper.readValue(file, FbProfile.class);
    return profile;
}

But it throws an exception:

com.fasterxml.jackson.databind.JsonMappingException: Unexpected token
  (VALUE_NUMBER_INT), expected VALUE_STRING: Expected array or string.

How can I deserialize epoch to LocalDate? I would like to add that if I change the datatype from LocalDate to java.util.Date it works perfectly fine. So maybe it's better to deserialize to java.util.Date and create the getter and setter which will do the conversion to/from LocalDate.

Body:
I've managed to do it writing my own deserializer (thank you @Ole V.V. to point me to the post Java 8 LocalDate Jackson format):

public class LocalDateTimeFromEpochDeserializer extends StdDeserializer<LocalDateTime> {

    private static final long serialVersionUID = 1L;

    protected LocalDateTimeFromEpochDeserializer() {
        super(LocalDate.class);
    }

    @Override
    public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        return Instant.ofEpochMilli(jp.readValueAs(Long.class)).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

}

Notice about timezone is also very useful. Thank you!

The still open question is if it can be done without writing own deserializer?


问:
Formatting Date and Time with a function in C#
So I am getting the driver date from graphic card and display it into a TextBox but the value comes like this 20161216000000.000000-000 and I want to convert it into a real date.

I already got a function to convert this kind of dates, but it this case does does not work and after using it shows me like this 01-01-0001 00:00:00.

This is my function code:

```<code>private static string FormatDateTime(object ObjInstallDate)
{
    object FinalDate = DBNull.Value;
    string strDate = Convert.ToString(ObjInstallDate);
    DateTime dtm;
    DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" },
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out dtm);
    if (!String.IsNullOrEmpty(strDate))
    {
        FinalDate = dtm;
    }
    return FinalDate.ToString();
}
</code>```

Do you have any idea how I can get in this case 20161216000000.000000-000 something like 2016-12-16?

答:
Taking a substring does the job (if the format is always like shown):

```<code>DateTime.TryParseExact(strDate.Substring(0, 8), "yyyyMMdd",
    System.Globalization.CultureInfo.InvariantCulture,
    System.Globalization.DateTimeStyles.None, out DateTime dtm);
</code>```

To get the required format to present the result you can use

```<code>dtm.ToString("yyyy-MM-dd");
</code>```

Body:
So I am getting the driver date from graphic card and display it into a TextBox but the value comes like this 20161216000000.000000-000 and I want to convert it into a real date.

I already got a function to convert this kind of dates, but it this case does does not work and after using it shows me like this 01-01-0001 00:00:00.

This is my function code:

private static string FormatDateTime(object ObjInstallDate)
{
    object FinalDate = DBNull.Value;
    string strDate = Convert.ToString(ObjInstallDate);
    DateTime dtm;
    DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" },
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out dtm);
    if (!String.IsNullOrEmpty(strDate))
    {
        FinalDate = dtm;
    }
    return FinalDate.ToString();
}

Do you have any idea how I can get in this case 20161216000000.000000-000 something like 2016-12-16?

Body:
Taking a substring does the job (if the format is always like shown):

DateTime.TryParseExact(strDate.Substring(0, 8), "yyyyMMdd",
    System.Globalization.CultureInfo.InvariantCulture,
    System.Globalization.DateTimeStyles.None, out DateTime dtm);

To get the required format to present the result you can use

dtm.ToString("yyyy-MM-dd");


问:
How to read JSON {"success": true} in Retrofit 2?
In normal JSONObject jsonResponse, I simply use boolean success = jsonResponse.getBoolean("success"); . Now, I am required to use Retrofit library.
I know that the response is in GSON format. That's why I'm having a hard time figuring out how to deal with the $response["success"] in my php file.

I tried this:

```<code>   call.enqueue(new Callback<User_Account_Model>() {
        @Override
        public void onResponse(Call<User_Account_Model> call, Response<User_Account_Model> response) {

            try {
                JSONObject jsonResponse = new JSONObject(new Gson().toJson(response));
                boolean success = jsonResponse.getBoolean("success");
                Toast.makeText(MainActivity.this,String.valueOf(success),Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
</code>```

but what's inside the try and catch seems not to be executed. No Toast messages showing. Is my method correct and just missing something or it's completely wrong?

答:
Add key in User_Account_Model for success like

```<code>public class User_Account_Model{
    @Expose
    private boolean success;

    // Add Getter and setter for **success**
}
</code>```

Now in onResponse method add like

```<code>try {
    String json =response.body().string();
    JSONObject jsonResponse = new JSONObject(json);
    boolean success = jsonResponse.getBoolean("success");
    Toast.makeText(MainActivity.this,String.valueOf(success),Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
    e.printStackTrace();
}
</code>```

Body:
In normal JSONObject jsonResponse, I simply use boolean success = jsonResponse.getBoolean("success"); . Now, I am required to use Retrofit library.
I know that the response is in GSON format. That's why I'm having a hard time figuring out how to deal with the $response["success"] in my php file.

I tried this:

   call.enqueue(new Callback<User_Account_Model>() {
        @Override
        public void onResponse(Call<User_Account_Model> call, Response<User_Account_Model> response) {

            try {
                JSONObject jsonResponse = new JSONObject(new Gson().toJson(response));
                boolean success = jsonResponse.getBoolean("success");
                Toast.makeText(MainActivity.this,String.valueOf(success),Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }

but what's inside the try and catch seems not to be executed. No Toast messages showing. Is my method correct and just missing something or it's completely wrong?

Body:
Add key in User_Account_Model for success like

public class User_Account_Model{
    @Expose
    private boolean success;

    // Add Getter and setter for **success**
}

Now in onResponse method add like

try {
    String json =response.body().string();
    JSONObject jsonResponse = new JSONObject(json);
    boolean success = jsonResponse.getBoolean("success");
    Toast.makeText(MainActivity.this,String.valueOf(success),Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
    e.printStackTrace();
}


问:
installing imagick with PHP+NGINX Windows
I have googling, and only found tutorial for APACHE+ PHP http://refreshless.com/blog/imagick-pecl-imagemagick-windows/
i follow the instruction, but I don't know what should I do with "CORE_RL_*" files because I'm running NGINX not Apache.

thanks

答: We solved this by moving the CORE_RL_* files to C:\Windows\System32. They just need to be in any directory that is included in the system variable PATH.</p>


问:
How to create a boolean property/binding whose value is based on an integer?
I want to create a class which holds boolean information via an int: if its value is greater than 0 the boolean's value is true, otherwise false.

This is a class that encapsulates this behavior:

```<code>public class CumulativeBoolean {

    private int cumulative = 0;

    public boolean get() {
        return cumulative > 0;
    }

    public void set(boolean val) {
        cumulative += val ? 1 : -1;
    }
}
</code>```

I want to create a JavaFX class from this design that allows binding and listening. I looked at extending either BooleanBinding or BooleanPropertyBase, they both hold a private boolean value as their value while what I want is an int.

This is what I have for BooleanBinding:

```<code>public class CumulativeBooleanBinding extends BooleanBinding {

    private int cumulative = 0;

    public void set(boolean val) {
        cumulative += val ? 1 : -1;
        invalidate();
    }

    @Override
    protected boolean computeValue() {
        return cumulative != 0;
    }
}
</code>```

However, I don't think that the idea of BooleanBinding was to support a set functionality, and there is also the issue of setting the value while the value is bound.

BooleanPropertyBase, on the other hand, does not allow me to invalidate when updating since its markInvalid method and valid fields are private.

How could I achieve this?

答:
If you want to use the binding-functionality of JavaFX, you have to use a ObservableValue (such as SimpleIntegerProperty).

The following code shows a quick example how to implement it:

```<code>SimpleIntegerProperty intProp = new SimpleIntegerProperty(0);
BooleanBinding binding = intProp.greaterThanOrEqualTo(0);
</code>```

If you don't want to use an ObservableValue of Integer in your class, the other option is to update a BooleanProperty when setting your int:

```<code>SimpleBooleanProperty fakeBinding = new SimpleBooleanProperty(value >= 0);
</code>```

and after every call to the set method:

```<code>fakeBinding.set(value >= 0);
</code>```

EDIT: Seems like MBec was faster than me :p

Body:
I want to create a class which holds boolean information via an int: if its value is greater than 0 the boolean's value is true, otherwise false.

This is a class that encapsulates this behavior:

public class CumulativeBoolean {

    private int cumulative = 0;

    public boolean get() {
        return cumulative > 0;
    }

    public void set(boolean val) {
        cumulative += val ? 1 : -1;
    }
}

I want to create a JavaFX class from this design that allows binding and listening. I looked at extending either BooleanBinding or BooleanPropertyBase, they both hold a private boolean value as their value while what I want is an int.

This is what I have for BooleanBinding:

public class CumulativeBooleanBinding extends BooleanBinding {

    private int cumulative = 0;

    public void set(boolean val) {
        cumulative += val ? 1 : -1;
        invalidate();
    }

    @Override
    protected boolean computeValue() {
        return cumulative != 0;
    }
}

However, I don't think that the idea of BooleanBinding was to support a set functionality, and there is also the issue of setting the value while the value is bound.

BooleanPropertyBase, on the other hand, does not allow me to invalidate when updating since its markInvalid method and valid fields are private.

How could I achieve this?

Body:
If you want to use the binding-functionality of JavaFX, you have to use a ObservableValue (such as SimpleIntegerProperty).

The following code shows a quick example how to implement it:

SimpleIntegerProperty intProp = new SimpleIntegerProperty(0);
BooleanBinding binding = intProp.greaterThanOrEqualTo(0);

If you don't want to use an ObservableValue of Integer in your class, the other option is to update a BooleanProperty when setting your int:

SimpleBooleanProperty fakeBinding = new SimpleBooleanProperty(value >= 0);

and after every call to the set method:

fakeBinding.set(value >= 0);

EDIT: Seems like MBec was faster than me :p


问:
what is typeof((c) + 1) in C
I came across an expression in C like

```<code>typeof((c) + 1) _tmp = c;
</code>```

What exactly does this mean?

Thanks for the reply.

Just one doubt? What if the type of c is struct instead of the primitive types, then what will +1 do?

答:
In addition to the other answer, the + here is quite subtle. It allows for c to be either an expression or a type.

If it is an expression then, as said,
c is promoted to int (at least)
and the type of the whole expression
has at least integer rank of int.

If it is a type expression the
parenthesis surrounding c make it a
cast of the value +1. So then the resulting type is just c.

For both kinds of acrobatic it is important that c is of arithmetic type and it is also to note that this trick here might loose the signedness of c. So this use of the typeof extension is not so useful as it might look like. In most cases using uintmax_t or intmax_t would be sufficient.

Title: what is typeof((c) + 1) in C

Body:
I came across an expression in C like

typeof((c) + 1) _tmp = c;

What exactly does this mean?

Thanks for the reply.

Just one doubt? What if the type of c is struct instead of the primitive types, then what will +1 do?


问:
Creating html elements through nested JSON objects
So I've managed to successfully create HTML elements through JSON objects before, but now that I've changed my JSON objects to nested JSON, I am not able to reproduce the HTML elements accordingly. I am pretty new to programming so can anyone help me find out where I have gone wrong?

JSON File:

```<code>{
  "ThreeG": [
    {
        "title":"Testing 1",
        "filePath":"https://example.com",
        "imagePath":"images/test.jpg"
    },
    {
        "title":"Testing 2",
        "filePath":"https://example.com",
        "imagePath":"images/test2.jpg"
    }
   ]
}
</code>```

Script:

```<code><script>
    $.ajax({
      url : "TestFiles.json",
      type : "post",
      contentType:"application/json",
      success : function(list){
          var divCol  = "<div class='col-md-offset-1 col-sm-5 col-md-5'>";
          var divWell = "<div class='well' style='position:relative'>";
          var divClose= "</div>";

          list.forEach(function(obj, index) {

            var title     = "<h4>"      + obj.ThreeG.title    + "</h4>";
            var linkStart = "<a href='" + obj.ThreeG.filePath + "' target='_blank'>" ;
            var image     = "<img data-toggle='tooltip' data-placement='left' title='Click to open data' src='" + obj.ThreeG.imagePath + "' height='100%' width='100%'/>"
            var linkEnd   =  "</a>";

            var div = divCol    +
            divWell     +
            title       +
            linkStart       +
            image       +
            linkEnd +
            divClose +
            divClose;

            console.log(obj);
           $("#test").append(div);

           })
        }
    });
  </script>
</code>```

答:
The list param in the success callback is an object with property / key ThreeG. So instead of list.forEach, you should do list.ThreeG.forEach, then each obj in the forEach callback will be the json object that you can use to create HTML elements.

```<code>list.ThreeG.forEach(function(obj, index) {
         console.log(obj); // { "title":"Testing 1", "filePath":"https://example.com", "imagePath":"images/test.jpg" } for the first object
}
</code>```

Body:
So I've managed to successfully create HTML elements through JSON objects before, but now that I've changed my JSON objects to nested JSON, I am not able to reproduce the HTML elements accordingly. I am pretty new to programming so can anyone help me find out where I have gone wrong?

JSON File:

{
  "ThreeG": [
    {
        "title":"Testing 1",
        "filePath":"https://example.com",
        "imagePath":"images/test.jpg"
    },
    {
        "title":"Testing 2",
        "filePath":"https://example.com",
        "imagePath":"images/test2.jpg"
    }
   ]
}

Script:

Body:
The list param in the success callback is an object with property / key ThreeG. So instead of list.forEach, you should do list.ThreeG.forEach, then each obj in the forEach callback will be the json object that you can use to create HTML elements.

list.ThreeG.forEach(function(obj, index) {
         console.log(obj); // { "title":"Testing 1", "filePath":"https://example.com", "imagePath":"images/test.jpg" } for the first object
}


问:
Search a particular String in entire Mysql table(All fields)
I am currently working with below query with single field search

```<code>SELECT *
FROM user_college_tbl
WHERE college_name LIKE '%Impulse%';
</code>```

How to Search a particular String in entire table(All fields)?

答:
You can also do a dynamic sql query.

Query

```<code>set @query = null;
select
  group_concat(
    concat(
       column_name, '', ' like \'%Impulse%\' or '
    ) separator ''
  ) into @query
from information_schema.columns
where table_name = 'user_college_tbl';

set @query = concat('select * from user_college_tbl where ',
           left(@query, length(@query) - 4));

prepare stmt from @query;
execute stmt;
deallocate prepare stmt;
</code>```

Body:
I am currently working with below query with single field search

SELECT *
FROM user_college_tbl
WHERE college_name LIKE '%Impulse%';

How to Search a particular String in entire table(All fields)?

Body:
You can also do a dynamic sql query.

Query

set @query = null;
select
  group_concat(
    concat(
       column_name, '', ' like \'%Impulse%\' or '
    ) separator ''
  ) into @query
from information_schema.columns
where table_name = 'user_college_tbl';

set @query = concat('select * from user_college_tbl where ',
           left(@query, length(@query) - 4));

prepare stmt from @query;
execute stmt;
deallocate prepare stmt;


问:
Gulp `build` not working as expected, gives only `index.html` as output
I am packing my application using gulp. But I am getting only the index.html as a out put.

I am not able to see vendar.js,app.js files with all css files added in the index.html file.

my expectation is :

get all files from index.html href and src. from there compress as per serial what it's there in index file and send to dest folder.

here is my code:

```<code>var gulp = require("gulp");
var ghtmlSrc = require('gulp-html-src');
var templateCache = require("gulp-angular-templatecache");
var gulpif = require('gulp-if');
var ngAnnotate = require('gulp-ng-annotate');
var minifyCss = require('gulp-minify-css');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');

gulp.task('templates', function() {
    return gulp.src('./WebContent/src/**/*.html')
    .pipe(templateCache({
        root:'src/',
        module: 'newPCSApp.templates',
        standalone: true
    }))
    .pipe(gulp.dest('WebContent/src/app/'));
});

gulp.task('compress', function() {
            return gulp.src('./WebContent/index.html')
            .pipe(useref())
            .pipe(gulpif('*.js', ngAnnotate()))
            .pipe(gulpif('*.js', uglify({ mangle: false })))
            .pipe(gulpif('*.css', minifyCss()))
            .pipe(gulp.dest('./dist'));
        });

gulp.task('build',['templates', 'compress' ]);
</code>```

Body:
I am packing my application using gulp. But I am getting only the index.html as a out put.

I am not able to see vendar.js,app.js files with all css files added in the index.html file.

my expectation is :

get all files from index.html href and src. from there compress as per serial what it's there in index file and send to dest folder.

here is my code:

var gulp = require("gulp");
var ghtmlSrc = require('gulp-html-src');
var templateCache = require("gulp-angular-templatecache");
var gulpif = require('gulp-if');
var ngAnnotate = require('gulp-ng-annotate');
var minifyCss = require('gulp-minify-css');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');

gulp.task('templates', function() {
    return gulp.src('./WebContent/src/**/*.html')
    .pipe(templateCache({
        root:'src/',
        module: 'newPCSApp.templates',
        standalone: true
    }))
    .pipe(gulp.dest('WebContent/src/app/'));
});

gulp.task('compress', function() {
            return gulp.src('./WebContent/index.html')
            .pipe(useref())
            .pipe(gulpif('*.js', ngAnnotate()))
            .pipe(gulpif('*.js', uglify({ mangle: false })))
            .pipe(gulpif('*.css', minifyCss()))
            .pipe(gulp.dest('./dist'));
        });

gulp.task('build',['templates', 'compress' ]);

Body:
after I added the comment line in to html file, the issue fixed.

<!--build:css css/style.min.css -->    <!-- endbuild -->
<!-- build:js js/vendor.min.js --> <!-- endbuild -->
<!-- build:js js/app.min.js --> <!-- endbuild -->


问:
mariadb cannot start with error
i'd rebooted server.

and mariadb did not started automatically.

so i'd type service mysqld start. but shows me cannot start with error.

mariadb cannot start with collation error

i wanna start without error

i'm using centos 6.5

```<code>**# mysql --version**
mysql  Ver 15.1 Distrib 10.1.19-MariaDB, for Linux (x86_64) using readline 5.1

**# ./mysqld_safe &**
mysqld_safe Logging to '/var/lib/mysql/localhost.localdomain.err'

**localhost.localdomain.err shows me**
mysqld_safe mysqld from pid file /var/lib/mysql/localhost.localdomain.pid ended
mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
[Warning] '--skip-locking' is deprecated and will be removed in a future release. Please use '--skip-external-locking' instead.
[ERROR] Unknown collation: 'utf8mb4_unicode_ci'
[ERROR] Aborting
[Note] /usr/libexec/mysqld: Shutdown complete

**my.cnf**
[client]
default-character-set=utf8mb4

[mysql]
default-character-set=utf8mb4

[mysqld]
collation-server = utf8mb4_unicode_ci
character-set-server = utf8mb4
</code>```

答:
Add

```<code>skip-character-set-client-handshake
</code>```

under mysqld in my.cnf to resolve any conflicts if collation is set via startup-options.

https://dev.mysql.com/doc/refman/5.7/en/charset-server.html

Title: mariadb cannot start with error

Body:
i'd rebooted server.

and mariadb did not started automatically.

so i'd type service mysqld start. but shows me cannot start with error.

mariadb cannot start with collation error

i wanna start without error

i'm using centos 6.5

**# mysql --version**
mysql  Ver 15.1 Distrib 10.1.19-MariaDB, for Linux (x86_64) using readline 5.1

**# ./mysqld_safe &**
mysqld_safe Logging to '/var/lib/mysql/localhost.localdomain.err'

**localhost.localdomain.err shows me**
mysqld_safe mysqld from pid file /var/lib/mysql/localhost.localdomain.pid ended
mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
[Warning] '--skip-locking' is deprecated and will be removed in a future release. Please use '--skip-external-locking' instead.
[ERROR] Unknown collation: 'utf8mb4_unicode_ci'
[ERROR] Aborting
[Note] /usr/libexec/mysqld: Shutdown complete

**my.cnf**
[client]
default-character-set=utf8mb4

[mysql]
default-character-set=utf8mb4

[mysqld]
collation-server = utf8mb4_unicode_ci
character-set-server = utf8mb4

Body:
Add

skip-character-set-client-handshake

under mysqld in my.cnf to resolve any conflicts if collation is set via startup-options.

https://dev.mysql.com/doc/refman/5.7/en/charset-server.html


问:
log4j2 configuration logging to file but not to console
My log4j2 version is 2.8

I have the following log4j2.xml in src/main/resources:

```<code><?xml version="1.0" encoding="UTF-8"?>

<Configuration status="WARN" monitorInterval="120">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH.mm.ss} %5p %c{1}:%L - %m%n</Pattern>
            </PatternLayout>
        </Console>
        <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="${env:CATALINA_HOME:-.}/logs/applicationlogs.log"
                                 filePattern="${env:CATALINA_HOME:-.}/logs/$${date:yyyy-MM}/applicationlogs-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH.mm.ss} %5p %c{1}:%L - %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <OnStartupTriggeringPolicy />
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="50 MB"/>
            </Policies>
        </RollingRandomAccessFile>
    </Appenders>
    <Loggers>
        <AsyncLogger name="com.mypackage" level="trace" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <AsyncLogger name="org.springframework.jdbc" level="debug" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <Root level="info" includeLocation="true">
            <AppenderRef ref="STDOUT"/>
            <AppenderRef ref="RollingRandomAccessFile"/>
        </Root>
    </Loggers>
</Configuration>
</code>```

This logs correctly to the file, but nothing appears on Console.

What's wrong here ?

答:
It is because of additivity attribute

Once an event reaches a logger with its additivity set to false the
  event will not be passed to any of its parent loggers, regardless of
  their additivity setting.

So log event just not passed to the root level.
To log to console add

```<code><AsyncLogger name="com.mypackage" level="info" includeLocation="true" additivity="false">
            <AppenderRef ref="STDOUT"/>
        </AsyncLogger>
</code>```

Body:
My log4j2 version is 2.8

I have the following log4j2.xml in src/main/resources:

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

<Configuration status="WARN" monitorInterval="120">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH.mm.ss} %5p %c{1}:%L - %m%n</Pattern>
            </PatternLayout>
        </Console>
        <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="${env:CATALINA_HOME:-.}/logs/applicationlogs.log"
                                 filePattern="${env:CATALINA_HOME:-.}/logs/$${date:yyyy-MM}/applicationlogs-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH.mm.ss} %5p %c{1}:%L - %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <OnStartupTriggeringPolicy />
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="50 MB"/>
            </Policies>
        </RollingRandomAccessFile>
    </Appenders>
    <Loggers>
        <AsyncLogger name="com.mypackage" level="trace" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <AsyncLogger name="org.springframework.jdbc" level="debug" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <Root level="info" includeLocation="true">
            <AppenderRef ref="STDOUT"/>
            <AppenderRef ref="RollingRandomAccessFile"/>
        </Root>
    </Loggers>
</Configuration>

This logs correctly to the file, but nothing appears on Console.

What's wrong here ?

Body:
It is because of additivity attribute

Once an event reaches a logger with its additivity set to false the
  event will not be passed to any of its parent loggers, regardless of
  their additivity setting.

So log event just not passed to the root level.
To log to console add

<AsyncLogger name="com.mypackage" level="info" includeLocation="true" additivity="false">
            <AppenderRef ref="STDOUT"/>
        </AsyncLogger>


问:
select only year and month in where clause
I have this value in my database 101101-2017-06-000
It is value for column lddap_no I want to select value with year equal to current year and current month my query is

SELECT lddap_no FROM lddap WHERE YEAR(lddap_no) = '2017'  AND MONTH(lddap_no) = '06'   ORDER BY sys_id  DESC LIMIT 1

I used YEAR() and MONTH() respectively but it didnt work I get no result even if I have one entry.

How to correctly compare year and month from a column value that is not formatted date.

UPDATE

Used WHERE YEAR(substring(lddap_no,7,10)) = '2017'  AND MONTH(substring(lddap_no,12,13)) = '06' Still same no result found

tried using this

```<code>WHERE YEAR(SUBSTRING(CAST(lddap_no AS VARCHAR(100)), 7, 10)) = '2017'  AND MONTH(SUBSTRING(CAST(lddap_no AS VARCHAR(100)), 12, 13)) = '06'
</code>```

答:
Maybe you can try :</p>

```<code>SELECT * FROM lddap WHERE lddap_no LIKE '%2017-06%';
</code>```

Body:
I have this value in my database 101101-2017-06-000
It is value for column lddap_no I want to select value with year equal to current year and current month my query is

SELECT lddap_no FROM lddap WHERE YEAR(lddap_no) = '2017'  AND MONTH(lddap_no) = '06'   ORDER BY sys_id  DESC LIMIT 1

I used YEAR() and MONTH() respectively but it didnt work I get no result even if I have one entry.

How to correctly compare year and month from a column value that is not formatted date.

UPDATE

Used WHERE YEAR(substring(lddap_no,7,10)) = '2017'  AND MONTH(substring(lddap_no,12,13)) = '06' Still same no result found

tried using this

WHERE YEAR(SUBSTRING(CAST(lddap_no AS VARCHAR(100)), 7, 10)) = '2017'  AND MONTH(SUBSTRING(CAST(lddap_no AS VARCHAR(100)), 12, 13)) = '06'

Body:
Maybe you can try :

SELECT * FROM lddap WHERE lddap_no LIKE '%2017-06%';


问:
Responsive Filemanager Thumbnails not showing
Using Responsive Filemanager 9.11.3
Thumbnails are not showing/blank in dialog window (GUI). In ftp thumbnails pictures are okay created successfully. Folder "thumbs" permission 755 files permission 644. i changed to 755 still not showing up in dialog window. thumb sizes are 2.4kb</p>

答:
I faced the same problem, if you resize that iframe or the div where responsive file manager is, then thumbnails will show up...

Work around:

set iframe height/width to be 101%

set onLoad attribute to iframe that will resize iframe width/height to 100%

Example:

```<code><script>
function loadThumbs() {
    var rfm = document.getElementById("rfm");
    rfm.style.height = "100%"
}
</script>
<iframe id="rfm" onload="loadThumbs()" src="..." style="height: 101%; width: 100%;" />
</code>```

Body:
I faced the same problem, if you resize that iframe or the div where responsive file manager is, then thumbnails will show up...

Work around:

set iframe height/width to be 101%

set onLoad attribute to iframe that will resize iframe width/height to 100%

Example:

<script>
function loadThumbs() {
    var rfm = document.getElementById("rfm");
    rfm.style.height = "100%"
}
</script>
<iframe id="rfm" onload="loadThumbs()" src="..." style="height: 101%; width: 100%;" />


问:
Achieve a square aligned with 3 rows with bootstrap
I'm trying to get this result with boostrap :

The idea would be that : the black square stay as a square, even with the right "rows" being resized (on mobile for example)
And the red rows would be having the same height/width (I failed that on the image, just a quick paint mockup)

I'd love to show you some code that would be a starting point but after a few hours I'm unable to achieve this effect...

I found that template that use this kind of structure :
Gridus

答:
Using flexbox as a wrapper.

* {
  box-sizing: border-box;
}

.flexbox {
  display: flex;
  justify-content: left;
  align-items: flex-start;
}

.col-md-10 {
  border: thin solid darkgray;
  max-height: 50px;
  overflow: hidden;
  height: 50px;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="row nopadding flexbox">

    <div class="col-md-4 vc-photo photo-01"><img src="http://placehold.it/150" /></div>

  <div class="col-md-8 nopadding">
    <div class="row nopadding">
      <div class="col-md-10">
        <p>Bla</p>
      </div>
    </div>
    <div class="row nopadding">
      <div class="col-md-10">
        <p>Bla</p>
      </div>
    </div>
    <div class="row nopadding">
      <div class="col-md-10">
        <p>Bla</p>
      </div>
    </div>
  </div>
</div></code>```

Body:
Using flexbox as a wrapper.

* {
  box-sizing: border-box;
}

.flexbox {
  display: flex;
  justify-content: left;
  align-items: flex-start;
}

.col-md-10 {
  border: thin solid darkgray;
  max-height: 50px;
  overflow: hidden;
  height: 50px;
  width: 100%;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="row nopadding flexbox">
  <a href="#">
    <div class="col-md-4 vc-photo photo-01"><img src="http://placehold.it/150" /></div>
  </a>
  <div class="col-md-8 nopadding">
    <div class="row nopadding">
      <div class="col-md-10">
        <p>Bla</p>
      </div>
    </div>
    <div class="row nopadding">
      <div class="col-md-10">
        <p>Bla</p>
      </div>
    </div>
    <div class="row nopadding">
      <div class="col-md-10">
        <p>Bla</p>
      </div>
    </div>
  </div>
</div>


问:
Make hive returns the value only
I want to make hive only returns the value only! not other words like information about the processing!

```<code>hive> select max(temp) from temp where dtime like '2014-07%' ;
Query ID = hduser_20170608003255_d35b8a43-8cc5-4662-89ce-9ee5f87d3ba0
Total jobs = 1
Launching Job 1 out of 1
Number of reduce tasks determined at compile time: 1
In order to change the average load for a reducer (in bytes):
  set hive.exec.reducers.bytes.per.reducer=<number>
In order to limit the maximum number of reducers:
  set hive.exec.reducers.max=<number>
In order to set a constant number of reducers:
  set mapreduce.job.reduces=<number>
Starting Job = job_1496864651740_0008, Tracking URL = http://localhost:8088/proxy/application_1496864651740_0008/
Kill Command = /home/hduser/hadoop/bin/hadoop job  -kill job_1496864651740_0008
Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 1
2017-06-08 00:33:01,955 Stage-1 map = 0%,  reduce = 0%
2017-06-08 00:33:08,187 Stage-1 map = 100%,  reduce = 0%, Cumulative CPU 4.13 sec
2017-06-08 00:33:14,414 Stage-1 map = 100%,  reduce = 100%, Cumulative CPU 5.91 sec
MapReduce Total cumulative CPU time: 5 seconds 910 msec
Ended Job = job_1496864651740_0008
MapReduce Jobs Launched:
Stage-Stage-1: Map: 1  Reduce: 1   Cumulative CPU: 5.91 sec   HDFS Read: 853158 HDFS Write: 5 SUCCESS
Total MapReduce CPU Time Spent: 5 seconds 910 msec
OK
44.4
Time taken: 20.01 seconds, Fetched: 1 row(s)
</code>```

I want it to return  the value only which is  44.4

Thanks in advance...

答:
You can also use -S </p>

```<code>hive -S -e  "select max(temp) from temp where dtime like '2014-07%';"
</code>```

Title: Make hive returns the value only

Body:
I want to make hive only returns the value only! not other words like information about the processing!

hive> select max(temp) from temp where dtime like '2014-07%' ;
Query ID = hduser_20170608003255_d35b8a43-8cc5-4662-89ce-9ee5f87d3ba0
Total jobs = 1
Launching Job 1 out of 1
Number of reduce tasks determined at compile time: 1
In order to change the average load for a reducer (in bytes):
  set hive.exec.reducers.bytes.per.reducer=<number>
In order to limit the maximum number of reducers:
  set hive.exec.reducers.max=<number>
In order to set a constant number of reducers:
  set mapreduce.job.reduces=<number>
Starting Job = job_1496864651740_0008, Tracking URL = http://localhost:8088/proxy/application_1496864651740_0008/
Kill Command = /home/hduser/hadoop/bin/hadoop job  -kill job_1496864651740_0008
Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 1
2017-06-08 00:33:01,955 Stage-1 map = 0%,  reduce = 0%
2017-06-08 00:33:08,187 Stage-1 map = 100%,  reduce = 0%, Cumulative CPU 4.13 sec
2017-06-08 00:33:14,414 Stage-1 map = 100%,  reduce = 100%, Cumulative CPU 5.91 sec
MapReduce Total cumulative CPU time: 5 seconds 910 msec
Ended Job = job_1496864651740_0008
MapReduce Jobs Launched:
Stage-Stage-1: Map: 1  Reduce: 1   Cumulative CPU: 5.91 sec   HDFS Read: 853158 HDFS Write: 5 SUCCESS
Total MapReduce CPU Time Spent: 5 seconds 910 msec
OK
44.4
Time taken: 20.01 seconds, Fetched: 1 row(s)

I want it to return  the value only which is  44.4

Thanks in advance...

Body:
You can also use -S

hive -S -e  "select max(temp) from temp where dtime like '2014-07%';"


问:
Angularjs md-autocomplete with profile pictures
I have a search bar in the top my page for searching profiles.
I would like to have an autocompletion feature like in facebook or linkedin.
I'm using angularjs in the front.

I need to show records of the found profiles with their images alongside with their full names.

How can I set the images of the found profiles in the md-items of md-autocomplete (is that possible at all)?
Is there a better way for such autocompletion without re-inventing the whole wheel, except the md-autocopmlete?

Thanks

答:
yes, you can. use md-icon to add an icon to your autocomplete result.

```<code><md-autocomplete class="no-float" flex md-no-cache="noCache" md-selected-item="selectedItem" md-search-text="searchText" md-items="item in vm.querySearch(searchText)" md-item-text="item.display" md-floating-label="Project">
    <md-item-template>
        <span class="item-title">
          <md-icon md-svg-icon="{{item.image}}"></md-icon>
        </span>
        <span class="item-metadata">
            <span class="item-metastat">
                <strong>{{item.email}}</strong>
            </span>
        </span>
    </md-item-template>
</md-autocomplete>
</code>```

Body:
yes, you can. use md-icon to add an icon to your autocomplete result.

<md-autocomplete class="no-float" flex md-no-cache="noCache" md-selected-item="selectedItem" md-search-text="searchText" md-items="item in vm.querySearch(searchText)" md-item-text="item.display" md-floating-label="Project">
    <md-item-template>
        <span class="item-title">
          <md-icon md-svg-icon="{{item.image}}"></md-icon>
        </span>
        <span class="item-metadata">
            <span class="item-metastat">
                <strong>{{item.email}}</strong>
            </span>
        </span>
    </md-item-template>
</md-autocomplete>


问:
Angular - Dynamic ng-model inside ng-repeater
I have a form for search data, some fields are generated dinamically inside a ng-repeat. The problem is to assign ng-model to all fields that i must get to do the search.

I need to use the {{masterAttribute.Name}} as ng-model, or whatever that i can read to do in my search.

HTML is

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="MyApp" ng-controller="ricercaAttivita">
    <div class="accordion-group" ng-repeat="masterAttribute in masterAttributes">
        <select class="trip dark" ng-model="{{masterAttribute.Name}}" ng-options="attr.Id as attr.Value for attr in masterAttribute.Values">
            <option value="">TUTTE</option>
        </select>
    </div>
    <button class="btn btn-default btn-green btn-3-column sidebar-filtri-button" ng-click="search()">Cerca</button>
</body>
</code>```

答:
Change ng-model="{{masterAttribute.Name}}" to ng-model="masterAttribute.Name".

since it's already in Angular scope, so no need of interpolation operator({{..}}).

Further : search() method is part of your ricercaAttivita controller, then you also have access to masterAttributes as well in controller., you can find all Name props there.

Body:
I have a form for search data, some fields are generated dinamically inside a ng-repeat. The problem is to assign ng-model to all fields that i must get to do the search.

I need to use the {{masterAttribute.Name}} as ng-model, or whatever that i can read to do in my search.

HTML is

        <select class="trip dark" ng-model="{{masterAttribute.Name}}" ng-options="attr.Id as attr.Value for attr in masterAttribute.Values">
            <option value="">TUTTE</option>
        </select>

    <button class="btn btn-default btn-green btn-3-column sidebar-filtri-button" ng-click="search()">Cerca</button>


问:
Working with EventListener in Firebase for Android
Consider, I store the following Key-Value pair in Firebase Database.

Key: "CarBrand" and Value: "Audi"

I read the Value for this Key from Firebase Database and display the Value in TextView. For this, I use an EventListener.

The problem I face with an EventListsner is since it runs on a separate thread, the TextView returns a NullPointerException even before the Value is fetched from Firebase.

To overcome the issue I have been using this dirty trick (using a Handler with 500 to 1000 ms delay). Can someone guide me the right way to fetch and display the Value in TextView or any other Views

PS: Apologies for this codeless Question

Thanks

EDIT: More the Code, better the question. The sample code is as follows

```<code>String CardBrand;

private ValueEventListener contentListener() {
    contentListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pull Values for all available Keys
            CarBrand = dataSnapshot.child("CarBrand").getValue(String.class);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    return contentListener;
}

dbContent.addListenerForSingleValueEvent(contentListener());
mTextView.setText(CarBrand);
</code>```

The above code results in error. To avoid this, I replaced the last line of code with

```<code>    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mTextView.setText(CarBrand);
        }
    }, 1000);
</code>```

So this is what I have been doing. What would be the right way to display the Text in TextView in my Case?

答:
If you want to work with the result of some callback (like ValueEventListener) you should execute your code inside the overriding methods.</p>

```<code>String cardBrand;

private ValueEventListener contentListener() {
    contentListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pull Values for all available Keys
            carBrand = dataSnapshot.child("CarBrand").getValue(String.class);
            mTextView.setText(carBrand);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    return contentListener;
}

dbContent.addListenerForSingleValueEvent(contentListener());
</code>```

Body:
Consider, I store the following Key-Value pair in Firebase Database.

Key: "CarBrand" and Value: "Audi"

I read the Value for this Key from Firebase Database and display the Value in TextView. For this, I use an EventListener.

The problem I face with an EventListsner is since it runs on a separate thread, the TextView returns a NullPointerException even before the Value is fetched from Firebase.

To overcome the issue I have been using this dirty trick (using a Handler with 500 to 1000 ms delay). Can someone guide me the right way to fetch and display the Value in TextView or any other Views

PS: Apologies for this codeless Question

Thanks

EDIT: More the Code, better the question. The sample code is as follows

String CardBrand;

private ValueEventListener contentListener() {
    contentListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pull Values for all available Keys
            CarBrand = dataSnapshot.child("CarBrand").getValue(String.class);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    return contentListener;
}

dbContent.addListenerForSingleValueEvent(contentListener());
mTextView.setText(CarBrand);

The above code results in error. To avoid this, I replaced the last line of code with

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mTextView.setText(CarBrand);
        }
    }, 1000);

So this is what I have been doing. What would be the right way to display the Text in TextView in my Case?

Body:
If you want to work with the result of some callback (like ValueEventListener) you should execute your code inside the overriding methods.

String cardBrand;

private ValueEventListener contentListener() {
    contentListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pull Values for all available Keys
            carBrand = dataSnapshot.child("CarBrand").getValue(String.class);
            mTextView.setText(carBrand);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    return contentListener;
}

dbContent.addListenerForSingleValueEvent(contentListener());


问:
django.core.exceptions.ValidationError: [u"'' value has an invalid
models.py

```<code>    # -*- coding:utf-8 -*-
    from __future__ import unicode_literals
    from django.db import models
    # Create your models here.

    class moption(models.Model):

        pub_date = models.DateTimeField('pub time', auto_now_add=True, editable=True)
</code>```

when I command "python manage.py migrate"

```<code>Operations to perform:
  Apply all migrations: Price, admin, auth, contenttypes, sessions
Running migrations:
  Applying Price.0006_moption_pub_date...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Python27\lib\site-packages\django\db\backends\mysql\schema.py", line 43, in add_field
    super(DatabaseSchemaEditor, self).add_field(model, field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 395, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 147, in column_sql
    default_value = self.effective_default(field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 221, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 755, in get_db_prep_save
    prepared=False)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1440, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1419, in get_prep_value
    value = super(DateTimeField, self).get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1275, in get_prep_value
    return self.to_python(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1403, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: [u"'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
</code>```

who can tell me,thanks,

答:
Remove the editable=True from the pub_date,

```<code>    pub_date = models.DateTimeField(auto_now_add=True)
</code>```

Try clearing all your migrations and recreate the database,

If you are using SQLite3, then run,

```<code>rm -r Price/migrations #Assume Price is your app_name
rm -rf db.sqlite3

python manage.py makemigrations
python manage.py migrate
</code>```

Body:
models.py

    # -*- coding:utf-8 -*-
    from __future__ import unicode_literals
    from django.db import models
    # Create your models here.

    class moption(models.Model):

        pub_date = models.DateTimeField('pub time', auto_now_add=True, editable=True)

when I command "python manage.py migrate"

Operations to perform:
  Apply all migrations: Price, admin, auth, contenttypes, sessions
Running migrations:
  Applying Price.0006_moption_pub_date...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Python27\lib\site-packages\django\db\backends\mysql\schema.py", line 43, in add_field
    super(DatabaseSchemaEditor, self).add_field(model, field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 395, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 147, in column_sql
    default_value = self.effective_default(field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 221, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 755, in get_db_prep_save
    prepared=False)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1440, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1419, in get_prep_value
    value = super(DateTimeField, self).get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1275, in get_prep_value
    return self.to_python(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1403, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: [u"'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]

who can tell me,thanks,

Body:
Remove the editable=True from the pub_date,

    pub_date = models.DateTimeField(auto_now_add=True)

Try clearing all your migrations and recreate the database,

If you are using SQLite3, then run,

rm -r Price/migrations #Assume Price is your app_name
rm -rf db.sqlite3

python manage.py makemigrations
python manage.py migrate


问:
Why is Firefox missing the border on some HTML tables
I am using Firefox 3.5.7 and I have the same CSS used in multiple HTML tables, but there are some examples where parts of the borders are not shown.

What makes no sense to me is that the same CSS on the same page for another HTML table works fine. Also, the same page in Internet Explorer looks fine from a border point of view.

Here is an image with an example, as you can see in this case the bottom of the first table is missing a border.

Does anyone have a clue why this would happen here?

答:
worked for me realisation of answer @Donald Payne

*( .table - bootstrap class )

```<code>table.table {
    border-collapse: separate !important;
}

table.table tr,
table.table th,
table.table td {
    border-right-width: 0 !important;
    border-bottom-width: 0 !important;
    border-left: 1px solid #DDD !important;
    border-top: 1px solid #DDD !important;
}

table.table td:last-child,
table.table th:last-child {
    border-right: 1px solid #DDD !important;
}

table.table tr:last-child td {
    border-bottom: 1px solid #DDD !important;
}

table.table {
    border: 0 !important;
}

table.table thead tr:last-child th,
table.table thead tr:last-child td {
  border-bottom: 1px solid #DDD !important;
}

table.table tbody tr:first-child th,
table.table tbody tr:first-child td {
  border-top-width: 0 !important;
}
</code>```

Body:
worked for me realisation of answer @Donald Payne

*( .table - bootstrap class )

table.table {
    border-collapse: separate !important;
}

table.table tr,
table.table th,
table.table td {
    border-right-width: 0 !important;
    border-bottom-width: 0 !important;
    border-left: 1px solid #DDD !important;
    border-top: 1px solid #DDD !important;
}

table.table td:last-child,
table.table th:last-child {
    border-right: 1px solid #DDD !important;
}

table.table tr:last-child td {
    border-bottom: 1px solid #DDD !important;
}

table.table {
    border: 0 !important;
}

table.table thead tr:last-child th,
table.table thead tr:last-child td {
  border-bottom: 1px solid #DDD !important;
}

table.table tbody tr:first-child th,
table.table tbody tr:first-child td {
  border-top-width: 0 !important;
}


问:
How do I pull the clientID of an asp:button inside an asp:listview for use with jQuery?
I'm attempting to do something which should be relatively simple.  I'm using a ListView to show a number of items, using the ItemTemplate.  Inside the ItemTemplate I have a div surrounding the full item, so that I can highlight on a hover event, (being handled already by jQuery).

What I would like to do is have the click event on the div fire a button to open a details view for that specific item.  The problem I'm having is pulling back the ClientID for that button while using jQuery.  I've tried the:

```<code>$('#<%= Button1.ClientID %>')
</code>```

route, but that doesn't work, as the Button doesn't exist when the page loads.

The basic code is as follows:

```<code><asp:listview>
 <itemtemplate>
  <td runat="server">
   <div class="container">
    <asp:linkbutton id="Button1" runat="server" text="View Details" />
     fun and exciting stuff here...
   </div>
  </td>
 </itemtemplate>
</asp:listview>
</code>```

Any suggestions or help are much appreciated!

答:
Why don't you just give those linkbuttons a specific css class?

```<code><asp:linkbutton id="Button1" runat="server" text="View Details" CssClass="detailsButtons" />
</code>```

Then in jquery just select the class to assign them all in one call.

```<code>$(".detailsButtons").click( function() { .... } );
</code>```

If that doesn't work because the objects aren't made at that time, you can use the new live() method in jquery.  It will assign the events to any dynamically added elements as well.

Hope this helps

OwnerDisplayName: riceboyler

Body:
I'm attempting to do something which should be relatively simple.  I'm using a ListView to show a number of items, using the ItemTemplate.  Inside the ItemTemplate I have a div surrounding the full item, so that I can highlight on a hover event, (being handled already by jQuery).

What I would like to do is have the click event on the div fire a button to open a details view for that specific item.  The problem I'm having is pulling back the ClientID for that button while using jQuery.  I've tried the:

$('#<%= Button1.ClientID %>')

route, but that doesn't work, as the Button doesn't exist when the page loads.

The basic code is as follows:

<asp:listview>
 <itemtemplate>

    <asp:linkbutton id="Button1" runat="server" text="View Details" />
     fun and exciting stuff here...

 </itemtemplate>
</asp:listview>

Any suggestions or help are much appreciated!

Body:
Why don't you just give those linkbuttons a specific css class?

<asp:linkbutton id="Button1" runat="server" text="View Details" CssClass="detailsButtons" />

Then in jquery just select the class to assign them all in one call.

$(".detailsButtons").click( function() { .... } );

If that doesn't work because the objects aren't made at that time, you can use the new live() method in jquery.  It will assign the events to any dynamically added elements as well.

Hope this helps

OwnerDisplayName: Jesse Brown

LastEditorDisplayName: Jesse Brown


问:
How to add objective c xcode project into another swift project
I am having objective c project and it has lot of classes & libraries.
I want to add this project to existing swift project but one way is, I can add bridge header write all header files names and another way I am adding Xcode project directly to another project, added dependency, header search path but unable to access project objective c file in swift.
Anything I am missing here?</p>

答:
I don't think so this is possible because a project doesn't contain only classes and headers, it is bunch of settings , compatibility and etc...
As apple said in this page :

Swift and Objective-C in the Same Project

Apple only mentioned files not mixing projects :

Swift’s compatibility with Objective-C lets you create a project that contains files written in either language. You can use this feature, called mix and match, to write apps that have a mixed-language codebase. Using mix and match, you can implement part of your app’s functionality using the latest Swift features and seamlessly incorporate it back into your existing Objective-C codebase.


问:
Getting all nulls when reading file with list
Hi there is problem with reading a file. My file content is:

```<code>Alcohol 0,000425 0,000385 0,00003 0,89.
</code>```

It shows that all variables are equal to null.
I can't find mistakes in this code. Maybe somtehing is wrong with filter or foreach loop.

```<code>public class FileReading  {
    List<Double> Mass1 = new ArrayList<>();
    List<Double> Mass2 = new ArrayList<>();
    List <Double> Voulume = new ArrayList<>();
    List<Double> Height = new ArrayList<>();

    void Reading(String name,int sk) throws IOException{
        List<String> Material= new ArrayList<>();
        Material = Files.lines(Paths.get("D:/Desktop/NewFolder/26laboratorinis.txt")).
                filter(s->s.contains(name))
                .map(s ->s.substring(sk)).collect(Collectors.toList());

        for(String number : Material){

            String[] l = number.split(" ");
            Mass1.add(Double.parseDouble(l[0]));
            Mass2.add(Double.parseDouble(l[1]));
            Volume.add(Double.parseDouble(l[2]));
            Height.add(Double.parseDouble(l[3]));
        }

    }
    public void setMass1(List<Double> PAM) {
        this.Mass1 = PAM;
    }

    public void setMass2(List<Double> TAM) {
        this.Mass2 = TAM;
    }
    public void setVolume(List<Double> T) {
        this.Volume =T;
    }

    public void setHeight(List<Double> VSA) {
        this.Height = VSA;
    }
    public List<Double> getMass1() {
        return Mass1;
    }
    public List<Double> getMass2() {
        return Mass2;
    }
    public List<Double> getVolume() {
        return Volume;
    }
    public List<Double> getHeight() {
        return Height;
    }

}
</code>```

答:
Which values do you pass to Reading method when you call it?

Anyway:

Files.lines - read all lines from file as a Stream.
After that you put each line in filter method. So, if line doesn't contains your parameter name it'll just "throw away" this line.

After that method map convert all filtered lines to s.substring(sk).

And finally collect method convert your stream to List.

So, maybe you passed name which doesn't content in any line of your document, that's why you're getting null.

Body:
Hi there is problem with reading a file. My file content is:

Alcohol 0,000425 0,000385 0,00003 0,89.

It shows that all variables are equal to null.
I can't find mistakes in this code. Maybe somtehing is wrong with filter or foreach loop.

public class FileReading  {
    List<Double> Mass1 = new ArrayList<>();
    List<Double> Mass2 = new ArrayList<>();
    List <Double> Voulume = new ArrayList<>();
    List<Double> Height = new ArrayList<>();

    void Reading(String name,int sk) throws IOException{
        List<String> Material= new ArrayList<>();
        Material = Files.lines(Paths.get("D:/Desktop/NewFolder/26laboratorinis.txt")).
                filter(s->s.contains(name))
                .map(s ->s.substring(sk)).collect(Collectors.toList());

        for(String number : Material){

            String[] l = number.split(" ");
            Mass1.add(Double.parseDouble(l[0]));
            Mass2.add(Double.parseDouble(l[1]));
            Volume.add(Double.parseDouble(l[2]));
            Height.add(Double.parseDouble(l[3]));
        }

    }
    public void setMass1(List<Double> PAM) {
        this.Mass1 = PAM;
    }

    public void setMass2(List<Double> TAM) {
        this.Mass2 = TAM;
    }
    public void setVolume(List<Double> T) {
        this.Volume =T;
    }

    public void setHeight(List<Double> VSA) {
        this.Height = VSA;
    }
    public List<Double> getMass1() {
        return Mass1;
    }
    public List<Double> getMass2() {
        return Mass2;
    }
    public List<Double> getVolume() {
        return Volume;
    }
    public List<Double> getHeight() {
        return Height;
    }

}


答:
This is an XY problem. The real problem here is that you are storing your data in the wrong format. Store dates as dates or datetimes, then you can start querying using the MySQL date functions.

In the meantime since it's a varchar, for a cheap hack, you could try a LIKE clause:

......WHERE ldap_no LIKE "%-2017-06-%"

Might be worth a shot.

Title: select only year and month in where clause


问:
Pairs of duplicate, identical rows. Update just one of them
Working on pretty large table in SQL-Server. Table has some identical rows. I need to remove duplicate rows. Problem is I cannot alter this table i.e. to create an ID column.

I could update one column value of the other row on pairs of duplicates. Then delete afterwards using this value.

How to update only one these rows?
For example: Firstly / lastly inserted, First occurrence, newest / oldest..

Thanks!

table Structure

```<code>NrValue |   Comment |   Value1  |   Value2  |   Value3      |
--------|-----------|-----------|-----------|---------------|
00000   |   data0   |   zz      |   top     |   vivalasvegas|
00100   |   NULL    |   N/A     |   sex     |   no          |
00100   |   NULL    |   N/A     |   sex     |   no          |
00200   |   NULL    |   female  |   sex     |   yes         |
00200   |   NULL    |   female  |   sex     |   yes         |
00300   |   NULL    |   male    |   sex     |   yesplease   |
00300   |   NULL    |   male    |   sex     |   yesplease   |
00400   |   data21  |   M       |   --      |   na          |
00500   |   NULL    |   F       |   ezig    |   na          |
</code>```

So, I could use 'Comment' -column to update but I cannot touch other than duplicate rows. I know by NrValue which rows can be updated.
Result would be:

```<code>NrValue |   Comment |   Value1  |   Value2  |   Value3      |
--------|-----------|-----------|-----------|---------------|
00000   |   data0   |   zz      |   top     |   vivalasvegas|
00100   |   1       |   N/A     |   sex     |   no          |
00100   |   2       |   N/A     |   sex     |   no          |
00200   |   3       |   female  |   sex     |   yes         |
00200   |   4       |   female  |   sex     |   yes         |
00300   |   5       |   male    |   sex     |   yesplease   |
00300   |   6       |   male    |   sex     |   yesplease   |
00400   |   data21  |   M       |   --      |   na          |
00500   |   NULL    |   F       |   ezig    |   na          |
</code>```

Lastly I delete rows where NrValue = 00100, 00200 or 00300 AND Comment = 2, 4 or 6.

答:
You don't need update, you want to delete duplicates so why do you want that intermediate step?

Yor code should look like this:

```<code>    declare @t table (col1 int, col2 int);
    insert into @t values
    (1, 1), (1, 1),
    (1, 2), (1, 2),(1, 2), (1, 2),
    (3, 2), (3, 2),(3, 2);

    with cte as
    (
    select *, row_number() over (partition by col1, col2 order by 1/0) rn
    from @t
    )

    delete cte
    where rn > 1;

     select *
     from @t;
</code>```

Sorry for not posting it in comment (rows limit and code formatting lost there)

Body:
Working on pretty large table in SQL-Server. Table has some identical rows. I need to remove duplicate rows. Problem is I cannot alter this table i.e. to create an ID column.

I could update one column value of the other row on pairs of duplicates. Then delete afterwards using this value.

How to update only one these rows?
For example: Firstly / lastly inserted, First occurrence, newest / oldest..

Thanks!

table Structure

NrValue |   Comment |   Value1  |   Value2  |   Value3      |
--------|-----------|-----------|-----------|---------------|
00000   |   data0   |   zz      |   top     |   vivalasvegas|
00100   |   NULL    |   N/A     |   sex     |   no          |
00100   |   NULL    |   N/A     |   sex     |   no          |
00200   |   NULL    |   female  |   sex     |   yes         |
00200   |   NULL    |   female  |   sex     |   yes         |
00300   |   NULL    |   male    |   sex     |   yesplease   |
00300   |   NULL    |   male    |   sex     |   yesplease   |
00400   |   data21  |   M       |   --      |   na          |
00500   |   NULL    |   F       |   ezig    |   na          |

So, I could use 'Comment' -column to update but I cannot touch other than duplicate rows. I know by NrValue which rows can be updated.
Result would be:

NrValue |   Comment |   Value1  |   Value2  |   Value3      |
--------|-----------|-----------|-----------|---------------|
00000   |   data0   |   zz      |   top     |   vivalasvegas|
00100   |   1       |   N/A     |   sex     |   no          |
00100   |   2       |   N/A     |   sex     |   no          |
00200   |   3       |   female  |   sex     |   yes         |
00200   |   4       |   female  |   sex     |   yes         |
00300   |   5       |   male    |   sex     |   yesplease   |
00300   |   6       |   male    |   sex     |   yesplease   |
00400   |   data21  |   M       |   --      |   na          |
00500   |   NULL    |   F       |   ezig    |   na          |

Lastly I delete rows where NrValue = 00100, 00200 or 00300 AND Comment = 2, 4 or 6.

Body:
You don't need update, you want to delete duplicates so why do you want that intermediate step?

Yor code should look like this:

    declare @t table (col1 int, col2 int);
    insert into @t values
    (1, 1), (1, 1),
    (1, 2), (1, 2),(1, 2), (1, 2),
    (3, 2), (3, 2),(3, 2);

    with cte as
    (
    select *, row_number() over (partition by col1, col2 order by 1/0) rn
    from @t
    )

    delete cte
    where rn > 1;

     select *
     from @t;

Sorry for not posting it in comment (rows limit and code formatting lost there)


问:
a gcc sqrt function bug?
The following program cannot compile in gcc. But it compiles OK with g++ and MSC++ with .c extension.

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

int main()
{
  double t = 10;
  double t2 = 200;

  printf("%lf\n", sqrt(t*t2));

  return 0;
}
</code>```

My system is CentOS, the version info.

```<code>> gcc --version
gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

The error info:

```<code>> gcc test.c
/tmp/ccyY3Hiw.o: In function `main':
test.c:(.text+0x55): undefined reference to `sqrt'
collect2: ld returned 1 exit status
</code>```

Is this a bug?

Any one can do a test for me?

答: The thing is,   gcc -lm test.c -o test  won't work because gcc will treat the -lm as a compiler and not a linker option.  You need to put the -lm at the end of the command instead, i.e.    gcc -o test test.c -lm

Title: a gcc sqrt function bug?

Body:
The following program cannot compile in gcc. But it compiles OK with g++ and MSC++ with .c extension.

#include <math.h>
#include <stdio.h>

int main()
{
  double t = 10;
  double t2 = 200;

  printf("%lf\n", sqrt(t*t2));

  return 0;
}

My system is CentOS, the version info.

> gcc --version
gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

The error info:

> gcc test.c
/tmp/ccyY3Hiw.o: In function `main':
test.c:(.text+0x55): undefined reference to `sqrt'
collect2: ld returned 1 exit status

Is this a bug?

Any one can do a test for me?


问:
Replacement for stringByAddingPercentEscapesUsingEncoding in ios9?
In iOS8 and prior I can use:

```<code>NSString *str = ...; // some URL
NSString *result = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
</code>```

in iOS9 stringByAddingPercentEscapesUsingEncoding has been replaced with stringByAddingPercentEncodingWithAllowedCharacters:

```<code>NSString *str = ...; // some URL
NSCharacterSet *set = ???; // where to find set for NSUTF8StringEncoding?
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
</code>```

and my question is: where to find needed NSCharacterSet (NSUTF8StringEncoding) for proper replacement of stringByAddingPercentEscapesUsingEncoding?

答:
What is the meaning of "This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string." ? – GeneCode Sep 1 '16 at 8:30

It means that you are not supposed to encode the https://xpto.example.com/path/subpath of the url, but only what goes after the ?.

Supposed, because there are use-cases for doing it in cases like:

```<code>https://example.com?redirectme=xxxxx
</code>```

Where xxxxx is a fully encoded URL.

Body:
In iOS8 and prior I can use:

NSString *str = ...; // some URL
NSString *result = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

in iOS9 stringByAddingPercentEscapesUsingEncoding has been replaced with stringByAddingPercentEncodingWithAllowedCharacters:

NSString *str = ...; // some URL
NSCharacterSet *set = ???; // where to find set for NSUTF8StringEncoding?
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];

and my question is: where to find needed NSCharacterSet (NSUTF8StringEncoding) for proper replacement of stringByAddingPercentEscapesUsingEncoding?

Body:
What is the meaning of "This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string." ? – GeneCode Sep 1 '16 at 8:30

It means that you are not supposed to encode the https://xpto.example.com/path/subpath of the url, but only what goes after the ?.

Supposed, because there are use-cases for doing it in cases like:

https://example.com?redirectme=xxxxx

Where xxxxx is a fully encoded URL.