问:
How to initialise an OutputStream with a Url?
I try to create an OutputStream to an app group folder, which is created as follows:

```<code> func createProjectDirectoryPath(path:String) -> String
    {
        let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.xyz")
        let logsPath = containerURL!.appendingPathComponent(path)
        NSLog("12345- folder path: %@", logsPath.path)

        do {
            try FileManager.default.createDirectory(atPath: logsPath.path, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog("12345- Unable to create directory %@", error.debugDescription)
        }
        return logsPath.path
    }
</code>```

This function gives me a path like this

```<code>/private/var/mobile/Containers/Shared/AppGroup/40215F20-4713-4E23-87EF-1E21CCFB45DF/pcapFiles
</code>```

This folder exists, because the line FileManager.default.fileExists(path) returns true. The next step is to append a generated filename to the path, which I am doing here

```<code>let urlToFile = URL(string: createProjectDirectoryPath(path: "pcapFiles").appending("/\(filename)"))
</code>```

which gives me the correct new path

```<code>/private/var/mobile/Containers/Shared/AppGroup/40215F20-4713-4E23-87EF-1E21CCFB45DF/pcapFiles/39CC2DB4-A6D9-412E-BAAF-2FAA4AD70B22.pcap
</code>```

If I call this line, ostream is always nil

```<code>let ostream = OutputStream(url: urlToFile!, append: false)
</code>```

Do I miss something? The OutputStream should create the file on this path, but for unknown reason, it is not possible.

PS: AppGroup is enabled in Capabilities and in developers console.

答:
Your createProjectDirectoryPath() function returns a file path,
therefore you must use URL(fileURLWithPath:) to convert that to an
URL. Alternatively, modify your function to return an URL instead:

```<code>func createProjectDirectoryPath(path:String) -> URL? {
    let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.xyz")
    let logsURL = containerURL!.appendingPathComponent(path)
    do {
        try FileManager.default.createDirectory(at: logsURL, withIntermediateDirectories: true)
    } catch let error as NSError {
        NSLog("Unable to create directory %@", error.debugDescription)
        return nil
    }
    return logsURL
}
</code>```

In addition, you have to call open() on all Stream objects before
they can be used, this will also create the file if it did not exist
before:

```<code>guard let logsURL = createProjectDirectoryPath(path: "pcapFiles") else {
    fatalError("Cannot create directory")
}
let urlToFile = logsURL.appendingPathComponent(filename)
guard let ostream = OutputStream(url: urlToFile, append: false) else {
    fatalError("Cannot open file")
}
ostream.open()
</code>```

Body:
I try to create an OutputStream to an app group folder, which is created as follows:

 func createProjectDirectoryPath(path:String) -> String
    {
        let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.xyz")
        let logsPath = containerURL!.appendingPathComponent(path)
        NSLog("12345- folder path: %@", logsPath.path)

        do {
            try FileManager.default.createDirectory(atPath: logsPath.path, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog("12345- Unable to create directory %@", error.debugDescription)
        }
        return logsPath.path
    }

This function gives me a path like this

/private/var/mobile/Containers/Shared/AppGroup/40215F20-4713-4E23-87EF-1E21CCFB45DF/pcapFiles

This folder exists, because the line FileManager.default.fileExists(path) returns true. The next step is to append a generated filename to the path, which I am doing here

let urlToFile = URL(string: createProjectDirectoryPath(path: "pcapFiles").appending("/\(filename)"))

which gives me the correct new path

/private/var/mobile/Containers/Shared/AppGroup/40215F20-4713-4E23-87EF-1E21CCFB45DF/pcapFiles/39CC2DB4-A6D9-412E-BAAF-2FAA4AD70B22.pcap

If I call this line, ostream is always nil

let ostream = OutputStream(url: urlToFile!, append: false)

Do I miss something? The OutputStream should create the file on this path, but for unknown reason, it is not possible.

PS: AppGroup is enabled in Capabilities and in developers console.

Body:
Your createProjectDirectoryPath() function returns a file path,
therefore you must use URL(fileURLWithPath:) to convert that to an
URL. Alternatively, modify your function to return an URL instead:

func createProjectDirectoryPath(path:String) -> URL? {
    let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.xyz")
    let logsURL = containerURL!.appendingPathComponent(path)
    do {
        try FileManager.default.createDirectory(at: logsURL, withIntermediateDirectories: true)
    } catch let error as NSError {
        NSLog("Unable to create directory %@", error.debugDescription)
        return nil
    }
    return logsURL
}

In addition, you have to call open() on all Stream objects before
they can be used, this will also create the file if it did not exist
before:

guard let logsURL = createProjectDirectoryPath(path: "pcapFiles") else {
    fatalError("Cannot create directory")
}
let urlToFile = logsURL.appendingPathComponent(filename)
guard let ostream = OutputStream(url: urlToFile, append: false) else {
    fatalError("Cannot open file")
}
ostream.open()


来源: stackexchange

问:
Setting character encoding doesn't take effect
In JSP , I post utf-8 form to server, I capture the post message：

The text "中文" utf-8 code is E4B8AD E69687

so I am sure the JSP code is utf-8

In Java I set a filter in web.xml

```<code><filter>
    <description>desc-CharacterEncodingFilter</description>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.linkage.rainbow.ui.filter.SetCharacterEncodingFilter</filter-class>
     <init-param>
         <param-name>encoding</param-name>
         <param-value>UTF-8</param-value>
     </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern></filter-mapping>
</code>```

filter code i hava set

```<code>{
    if(this.ignore || request.getCharacterEncoding() == null) {
        String encoding = this.selectEncoding(request);
        if(encoding != null) {
            request.setCharacterEncoding(encoding);
            response.setCharacterEncoding(encoding);
        }
    }

    chain.doFilter(request, response);
}
</code>```

debug info encoding is utf-8 I set Tomcat config file conf/server.xml

```<code><Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8"/>
</code>```

IDEA tomcat setting VM options:

```<code> -server -XX:PermSize=128M -XX:MaxPermSize=512M
</code>```

My development tool is IDEA, platform is Windows, bug it don't effect. Can anyone help me !!

I modify my code ：

```<code>String test = new String(contract.getDescriptor().getBytes("iso-8859-1"),"UTF-8");
</code>```

it work !!
my form data is :

```<code>contract.name:pro-i_srv_synch_chain_chl
contract.contractId:100000372
contract.code:pro-i_srv_synch_chain_chl
contract.isBase:0
contract.baseContractId:
contract.descriptor:中文
</code>```

dost HttpServletRequest#setCharacterEncoding() not effect Child node?
I still don't understand the reason

答:
the Reason is my filter

```<code><filter>
    <description>desc-CharacterEncodingFilter</description>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.linkage.rainbow.ui.filter.SetCharacterEncodingFilter</filter-class>
     <init-param>
         <param-name>encoding</param-name>
         <param-value>UTF-8</param-value>
     </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern></filter-mapping>
</code>```

is after my XSSFilter.

so I adjust the CharacterEncodingFilter to the first filter, it work ok!

ContentLicense: CC BY-SA 3.0

Body:
In JSP , I post utf-8 form to server, I capture the post message：

The text "中文" utf-8 code is E4B8AD E69687

so I am sure the JSP code is utf-8

In Java I set a filter in web.xml

<filter>
    <description>desc-CharacterEncodingFilter</description>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.linkage.rainbow.ui.filter.SetCharacterEncodingFilter</filter-class>
     <init-param>
         <param-name>encoding</param-name>
         <param-value>UTF-8</param-value>
     </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern></filter-mapping>

filter code i hava set

{
    if(this.ignore || request.getCharacterEncoding() == null) {
        String encoding = this.selectEncoding(request);
        if(encoding != null) {
            request.setCharacterEncoding(encoding);
            response.setCharacterEncoding(encoding);
        }
    }

    chain.doFilter(request, response);
}

debug info encoding is utf-8 I set Tomcat config file conf/server.xml

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8"/>

IDEA tomcat setting VM options:

 -server -XX:PermSize=128M -XX:MaxPermSize=512M

My development tool is IDEA, platform is Windows, bug it don't effect. Can anyone help me !!

I modify my code ：

String test = new String(contract.getDescriptor().getBytes("iso-8859-1"),"UTF-8");

it work !!
my form data is :

contract.name:pro-i_srv_synch_chain_chl
contract.contractId:100000372
contract.code:pro-i_srv_synch_chain_chl
contract.isBase:0
contract.baseContractId:
contract.descriptor:中文

dost HttpServletRequest#setCharacterEncoding() not effect Child node?
I still don't understand the reason

Body:
the Reason is my filter

<filter>
    <description>desc-CharacterEncodingFilter</description>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.linkage.rainbow.ui.filter.SetCharacterEncodingFilter</filter-class>
     <init-param>
         <param-name>encoding</param-name>
         <param-value>UTF-8</param-value>
     </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern></filter-mapping>

is after my XSSFilter.

so I adjust the CharacterEncodingFilter to the first filter, it work ok!


问:
C# date part of dateTime extension property
I have extension method on DateTime class:

```<code>public static DateTime? SafeConvertToDateTime(this string value, bool dateOnly)
{
    DateTime parsedDateTime;
    if (DateTime.TryParse(value, out parsedDateTime))
    {
        return DateTime.SpecifyKind(parsedDateTime, DateTimeKind.Utc);
    } else {
        return new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    }
}
</code>```

If "dateOnly=true" i should return Datetime with only Date property and all conversions later on client (to local or utc) should be skipped if there is DateTime with only Date.
But how can i know that this DateTime holds only Date(since time can be valid as 0)?
I could add extension property (dateOnly), but as I know, I can't add extension property in C#, only methods?
Can I use some existing property of Datetime to tell, there is only date which should be consider later in code?

答: See this question on how to check if a datetime string contains a time. You Need to use the TimeOfDay property.

Body:
I have extension method on DateTime class:

public static DateTime? SafeConvertToDateTime(this string value, bool dateOnly)
{
    DateTime parsedDateTime;
    if (DateTime.TryParse(value, out parsedDateTime))
    {
        return DateTime.SpecifyKind(parsedDateTime, DateTimeKind.Utc);
    } else {
        return new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    }
}

If "dateOnly=true" i should return Datetime with only Date property and all conversions later on client (to local or utc) should be skipped if there is DateTime with only Date.
But how can i know that this DateTime holds only Date(since time can be valid as 0)?
I could add extension property (dateOnly), but as I know, I can't add extension property in C#, only methods?
Can I use some existing property of Datetime to tell, there is only date which should be consider later in code?


问:
How does Java makes use of multiple cores?
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. Then how does JVM make use of multiple cores which provide multiple OS threads for high concurrency?</p>

答:
You can make use of multiple cores using multiple threads. But using a higher number of threads than the number of cores present in a machine can simply be a waste of resources. You can use availableProcessors() to get the number of cores.

In Java 7 there is fork/join framework to make use of multiple cores.

Related Questions:

Is Multi-Threaded algorithm required to make use of Multi-core processors ?

Threads per Processor

Correctly multithreaded quicksort or mergesort algo in Java?


问:
Use contents of 1 form to set focus on a field in another form
I have a table that needs the contents of multiple fields manipulated. I have written the code to do the manipulation but want it to be performed on many fields. I have set up another table that contains the name of the fields that need to be changed and then want to use it to set the field name that needs to be inspected next.
I have tried

```<code>Dim FieldName  As Control
Dim FieldName1  As String
DoCmd.OpenForm "FieldsForm", acNormal, "", "", , acNormal
DoCmd.GoToRecord , Fields, acFirst
FieldName1 = Forms!FieldsForm.Field
FieldName = FieldName1
</code>```

it comes up with error
Object variable or With block variable not set

答:
Not clear enough what should be done with data in fields, here is an example - you read target field name from another form, then using this name you access the field on current form, set the focus tho this field and change the value:</p>

```<code>Dim FieldControl  As Control
Dim FieldName  As String

DoCmd.OpenForm "FieldsForm"
DoCmd.GoToRecord , , acFirst

'read target field name from textbox with name "FieldReference"
FieldName = Forms!FieldsForm.FieldReference.Value

'get the control by name
Set FieldControl = Me.Controls(FieldName)

'Now you can operate with target control
FieldControl.SetFocus
FieldControl.Value = "some data"
</code>```

Body:
I have a table that needs the contents of multiple fields manipulated. I have written the code to do the manipulation but want it to be performed on many fields. I have set up another table that contains the name of the fields that need to be changed and then want to use it to set the field name that needs to be inspected next.
I have tried

Dim FieldName  As Control
Dim FieldName1  As String
DoCmd.OpenForm "FieldsForm", acNormal, "", "", , acNormal
DoCmd.GoToRecord , Fields, acFirst
FieldName1 = Forms!FieldsForm.Field
FieldName = FieldName1

it comes up with error
Object variable or With block variable not set

Body:
Not clear enough what should be done with data in fields, here is an example - you read target field name from another form, then using this name you access the field on current form, set the focus tho this field and change the value:

Dim FieldControl  As Control
Dim FieldName  As String

DoCmd.OpenForm "FieldsForm"
DoCmd.GoToRecord , , acFirst

'read target field name from textbox with name "FieldReference"
FieldName = Forms!FieldsForm.FieldReference.Value

'get the control by name
Set FieldControl = Me.Controls(FieldName)

'Now you can operate with target control
FieldControl.SetFocus
FieldControl.Value = "some data"


问:
Extract the sub string from end offline to a special character in batch file
HI i am trying to get the sub string ZoomIn10X,ZoomIn20X,ZoomIn30X etc, from a file which contain following lines below and out put that to another file

```<code>Job Name : STANALONE/1234/JobId/Date/ZoomIn10X

Job Name : STANALONE/1234/JobId/Date/ZoomIn20X

Job Name : STANALONE/JobId/Date/ZoomIn30X

Job Name : STANALONE/1234/JobId/Date/ZoomIn40X

Job Name : STANALONE/1234/Date/ZoomIn10X
</code>```

i Have tried

```<code>for /F "tokens=*" %%A in (input.txt) do (

   echo %%A r "/" "\n" %%A | tail -1 >> output.txt

)
</code>```

but its not working as properly.Can you please help

答:
Using awk you could define / as field separator and output the last field:

```<code>$ awk -F/ '{print $NF}' input.txt
ZoomIn10X

ZoomIn20X

ZoomIn30X

ZoomIn40X

ZoomIn10X
</code>```

Solution outputs the last field of every line, including the empty lines you had between the data lines. If you need to filter the output somehow, please update the requirements to the OP.

Body:
HI i am trying to get the sub string ZoomIn10X,ZoomIn20X,ZoomIn30X etc, from a file which contain following lines below and out put that to another file

Job Name : STANALONE/1234/JobId/Date/ZoomIn10X

Job Name : STANALONE/1234/JobId/Date/ZoomIn20X

Job Name : STANALONE/JobId/Date/ZoomIn30X

Job Name : STANALONE/1234/JobId/Date/ZoomIn40X

Job Name : STANALONE/1234/Date/ZoomIn10X

i Have tried

for /F "tokens=*" %%A in (input.txt) do (

   echo %%A r "/" "\n" %%A | tail -1 >> output.txt

)

but its not working as properly.Can you please help

Body:
Using awk you could define / as field separator and output the last field:

$ awk -F/ '{print $NF}' input.txt
ZoomIn10X

ZoomIn20X

ZoomIn30X

ZoomIn40X

ZoomIn10X

Solution outputs the last field of every line, including the empty lines you had between the data lines. If you need to filter the output somehow, please update the requirements to the OP.


问:
Android BLE API : multiple Notification
According to google BLE Sample code , I design a android application , it's need to connect another BLE Device (TI CC2640 device), the protocol has two UUID ,
so in SampleGattAttributes.java , I add like this :

```<code>public static String UBI_ONGOING_INFO_SERVICE_UUID = "3d963d11-d107-4d7d-918f-61ca2aa836af";

public static String UBI_SYSTEM_INFO_SERVICE_UUID = "3d963d13-d107-4d7d-918f-61ca2aa836af";
</code>```

now I need to read/write Characteristic
in BluetoothLeService.java:

```<code>public final static String EXTRA_DATA_ONGOING =
        "com.example.bluetooth.le.EXTRA_DATA_ONGOING";

public final static String EXTRA_DATA_SYSTEM_INFO =
        "com.example.bluetooth.le.EXTRA_DATA_SYSTEM_INFO";

public final static UUID UUID_UBI_ONGOING_INFO_SERVICE_UUID =
        UUID.fromString(SampleGattAttributes.UBI_ONGOING_INFO_SERVICE_UUID);

public final static UUID UUID_UBI_SYSTEM_INFO_SERVICE_UUID =
        UUID.fromString(SampleGattAttributes.UBI_SYSTEM_INFO_SERVICE_UUID);

private void broadcastUpdate(final String action,final BluetoothGattCharacteristic characteristic){
...
...
if (UUID_UBI_SYSTEM_INFO_SERVICE_UUID.equals(characteristic.getUuid())){
  final byte[] data1 = characteristic.getValue();
  ....
  ....
  intent.putExtra(EXTRA_DATA, stringBuilder.toString());
  intent.putExtra(EXTRA_DATA_SYSTEM_INFO, strBuilder.toString());
}else{
  ...
  ...
  intent.putExtra(EXTRA_DATA, stringBuilder.toString());
  intent.putExtra(EXTRA_DATA_ONGOING, strBuilder.toString());
}

public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled) {
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    if (UUID_UBI_SERVICE_SERVICE_UUID.equals(characteristic.getUuid())) {
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(00002902-0000-1000-8000-00805f9b34fb));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
     }

if (UUID_UBI_SYSTEM_INFO_SERVICE_UUID.equals(characteristic.getUuid())){
   BluetoothGattDescriptor descriptor1 = characteristic.getDescriptor(00002902-0000-1000-8000-00805f9b34fb);
     descriptor1.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
     mBluetoothGatt.writeDescriptor(descriptor1);
}
</code>```

then , I can only receive notifications for the first characteristics.
how can I receive notifications from both characteristics and show data
in DeviceControlActivity.java ?

I am stuck in here for long time , hope someone can help me , thanks.

In fact , I don't need to revise broadcastUpdate function , cause
EXTRA_DATA should be process in DeviceControlActivity.

答:
@Emil , like this:

```<code>if (UUID_UBI_SERVICE_SERVICE_UUID.equals(characteristic.getUuid())) {
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(00002902-0000-1000-8000-00805f9b34fb));
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    mBluetoothGatt.writeDescriptor(descriptor);
//add sleep delay 500
try {
    Thread.sleep(500);
}catch (InterruptedException e) {
    e.printStackTrace();
}

if (UUID_UBI_SYSTEM_INFO_SERVICE_UUID.equals(characteristic.getUuid())){
    BluetoothGattDescriptor descriptor1 = characteristic.getDescriptor(00002902-0000-1000-8000-00805f9b34fb);
    descriptor1.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
     mBluetoothGatt.writeDescriptor(descriptor1);
}
</code>```

My mistakes , I should not revise Notification function.

Title: Android BLE API : multiple Notification

Body:
According to google BLE Sample code , I design a android application , it's need to connect another BLE Device (TI CC2640 device), the protocol has two UUID ,
so in SampleGattAttributes.java , I add like this :

public static String UBI_ONGOING_INFO_SERVICE_UUID = "3d963d11-d107-4d7d-918f-61ca2aa836af";

public static String UBI_SYSTEM_INFO_SERVICE_UUID = "3d963d13-d107-4d7d-918f-61ca2aa836af";

now I need to read/write Characteristic
in BluetoothLeService.java:

public final static String EXTRA_DATA_ONGOING =
        "com.example.bluetooth.le.EXTRA_DATA_ONGOING";

public final static String EXTRA_DATA_SYSTEM_INFO =
        "com.example.bluetooth.le.EXTRA_DATA_SYSTEM_INFO";

public final static UUID UUID_UBI_ONGOING_INFO_SERVICE_UUID =
        UUID.fromString(SampleGattAttributes.UBI_ONGOING_INFO_SERVICE_UUID);

public final static UUID UUID_UBI_SYSTEM_INFO_SERVICE_UUID =
        UUID.fromString(SampleGattAttributes.UBI_SYSTEM_INFO_SERVICE_UUID);

private void broadcastUpdate(final String action,final BluetoothGattCharacteristic characteristic){
...
...
if (UUID_UBI_SYSTEM_INFO_SERVICE_UUID.equals(characteristic.getUuid())){
  final byte[] data1 = characteristic.getValue();
  ....
  ....
  intent.putExtra(EXTRA_DATA, stringBuilder.toString());
  intent.putExtra(EXTRA_DATA_SYSTEM_INFO, strBuilder.toString());
}else{
  ...
  ...
  intent.putExtra(EXTRA_DATA, stringBuilder.toString());
  intent.putExtra(EXTRA_DATA_ONGOING, strBuilder.toString());
}

public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled) {
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    if (UUID_UBI_SERVICE_SERVICE_UUID.equals(characteristic.getUuid())) {
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(00002902-0000-1000-8000-00805f9b34fb));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
     }

if (UUID_UBI_SYSTEM_INFO_SERVICE_UUID.equals(characteristic.getUuid())){
   BluetoothGattDescriptor descriptor1 = characteristic.getDescriptor(00002902-0000-1000-8000-00805f9b34fb);
     descriptor1.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
     mBluetoothGatt.writeDescriptor(descriptor1);
}

then , I can only receive notifications for the first characteristics.
how can I receive notifications from both characteristics and show data
in DeviceControlActivity.java ?

I am stuck in here for long time , hope someone can help me , thanks.

In fact , I don't need to revise broadcastUpdate function , cause
EXTRA_DATA should be process in DeviceControlActivity.

Body:
@Emil , like this:

if (UUID_UBI_SERVICE_SERVICE_UUID.equals(characteristic.getUuid())) {
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(00002902-0000-1000-8000-00805f9b34fb));
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    mBluetoothGatt.writeDescriptor(descriptor);
//add sleep delay 500
try {
    Thread.sleep(500);
}catch (InterruptedException e) {
    e.printStackTrace();
}

if (UUID_UBI_SYSTEM_INFO_SERVICE_UUID.equals(characteristic.getUuid())){
    BluetoothGattDescriptor descriptor1 = characteristic.getDescriptor(00002902-0000-1000-8000-00805f9b34fb);
    descriptor1.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
     mBluetoothGatt.writeDescriptor(descriptor1);
}

My mistakes , I should not revise Notification function.


问:
Does TCP ensure packet is received by sequence that server send it
I'm working on an gameServer that communicate with game client, but wonder whether the packet server send to client remain sequence when client received it ?

like server sends packets A,B,C
but the client received B,A,C ?

I have read the great blog http://packetlife.net/blog/2010/jun/7/understanding-tcp-sequence-acknowledgment-numbers/
It seems that every packet send by the server has an ack corresponding by client, but it does not say why the packet received by client has the same sequence with server

答:
TCP guarantees sequence and integrity of the byte stream. You will not receive data out of sequence. From RFC 793:

Reliable Communication: A stream of data sent on a TCP connection is delivered reliably and in
order at the destination.


问:
Override core files using module prestashop
Actually I'm a newbie to prestashop,

and I have changes in the following file in these locations

classes/Product.php

src/PrestaShopBundle/Controller/Admin/ProductController.php

src/PrestaShopBundle/Resources/views/Admin/Product/form.html.twig

I have created a module named as My Kit while this module is configured all these changes should work..If the module is set to be disabled these changes should not affect in front end(I mean in admin panel)

For this I've created an override folder in my_kit module and place all those above mentioned files into this my_kit\override path..

like

my_kit\override\classes/Product.php

my_kit\override\src/PrestaShopBundle/Controller/Admin/ProductController.php

my_kit\override\src/PrestaShopBundle/Resources/views/Admin/Product/form.html.twig

But it won't work for me :(

how should I do this one..

Someone help me out of this..

答:
I'm not really sure how you will work around the part with the custom module (maybe when the module is not configured, you will leave the override classes only defined, and when its configured, you will put the changes there)... still changes in the core files should be done like this - for the Product class:

Make a new file in (basefolder)/override/classes/Product.php

Define the class ass:

```<code>class Product extends ProductCore
</code>```

Do your changes. (override functions, or adding new ones)

Body:
I'm not really sure how you will work around the part with the custom module (maybe when the module is not configured, you will leave the override classes only defined, and when its configured, you will put the changes there)... still changes in the core files should be done like this - for the Product class:

Make a new file in (basefolder)/override/classes/Product.php

Define the class ass:

class Product extends ProductCore

Do your changes. (override functions, or adding new ones)


问:
Modal shared between components using services and eventEmitters in angular2/4 App
I am a newbie in angular2/4. I want to build shared modals with dynamic body and footer, then listen to which button of the footer that the user has pressed. I was inspired by the contribution of @echonax in plunker, I edited it as follows. I bound the button to eventEmitters

Template:

The Label

        <button class="btn btn-primary" (click)="submit()">save</button>
        <button class="btn btn-primary" (click)="edit()">edit</button>
        <button type="button" class="btn btn-default">Close</button>

```

<p>Component:</p>

<pre class="lang-ts prettyprint-override"><code>@Output() modalOutput: EventEmitter = new EventEmitter();

edit() {
  if (this.cmpRef) {
      this.cmpRef.destroy();
  }
  this.cmpRef = null;
  $('#theModal').modal('hide');
  this.modalOuput.emit('edit');
}

submit() {
  if (this.cmpRef) {
     this.cmpRef.destroy();
  }
  this.cmpRef = null;
  $('#theModal').modal('hide');
  this.modalOuput.emit('submit');
}
</code>```

and in the index.html:

<modal-comp (modalOutput)="modalData($event)"></modal-comp>
```

I used eventEmitter to catch the pressed button but I dont know how to listen to that event from the component which launched the modal.

答:
We propose a solution that goes as follows:
Make a shared service that handles the modal events (show, hide and callbacks when the modal buttons are clicked), then call that service from any component by passing custom callbacks (and why not a custom modal body).
the modal component:

```<code>  export class ModalComponent {
  @ViewChild('theBody', {read: ViewContainerRef}) theBody;
  cmp:ComponentRef;
  data;

  constructor(
    private sharedService:SharedService,
    private componentFactoryResolver: ComponentFactoryResolver,
    injector: Injector) {

    sharedService.modalEvents.subscribe(data => {
      console.log("data", data);
      this.data = data.data;
      if(data.cmd == "show"){
        if(this.cmpRef) {
          this.cmpRef.destroy();
        }
        let factory = this.componentFactoryResolver.resolveComponentFactory(data.component);
        this.cmpRef = this.theBody.createComponent(factory)
        $('#theModal').modal('show');
      }else{
        this.dispose();
      }

    });
  }

   close() {
        //this.dispose();
        this.sharedService.hideModal(true, this.data);
    }

    dispose() {
        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
        this.cmpRef = null;
        $('#theModal').modal('hide');
    }
  edit() {
    this.dispose();
     this.sharedService.modalEvents.next("edit");
  }

  submit() {
    this.dispose();
    this.sharedService.modalEvents.next("submit");
  }
}
</code>```

and the shared service:

```<code>@Injectable()
export class SharedService {

  modalEvents: Subject = new Subject();

  popupData;
  hasModalShown;

  showModal(component:any, data?:any, callback?:any, cancelCallback?:any)  {
        //this.showModal.next(component);

        var innerFunc = ()=> {
            this.popupData = {cmd: "show", component: component, data: data,
            callback: callback, cancelCallback: cancelCallback };
            this.modalEvents.next(this.popupData);
            this.hasModalShown = true;
        }

        if (this.hasModalShown) {
            this.hideModal();
            //setTimeout(innerFunc,600);
        } else {
            innerFunc();
        }
    }

    hideModal(isSubmit:boolean=false, data?:any) {
        if (this.hasModalShown) {
            this.modalEvents.next({cmd: "hide"});
            if(isSubmit && this.popupData.callback){
              this.popupData.callback(data);
            }else if(this.popupData.cancelCallback){
              this.popupData.cancelCallback(data);

            }

            this.hasModalShown = false;
        }
    }
}
</code>```

this is a working example in plunker

Body:
I am a newbie in angular2/4. I want to build shared modals with dynamic body and footer, then listen to which button of the footer that the user has pressed. I was inspired by the contribution of @echonax in plunker, I edited it as follows. I bound the button to eventEmitters

Template:

The Label

        <button class="btn btn-primary" (click)="submit()">save</button>
        <button class="btn btn-primary" (click)="edit()">edit</button>
        <button type="button" class="btn btn-default">Close</button>

Component:

@Output() modalOutput: EventEmitter = new EventEmitter();

edit() {
  if (this.cmpRef) {
      this.cmpRef.destroy();
  }
  this.cmpRef = null;
  $('#theModal').modal('hide');
  this.modalOuput.emit('edit');
}

submit() {
  if (this.cmpRef) {
     this.cmpRef.destroy();
  }
  this.cmpRef = null;
  $('#theModal').modal('hide');
  this.modalOuput.emit('submit');
}

and in the index.html:

<modal-comp (modalOutput)="modalData($event)"></modal-comp>

I used eventEmitter to catch the pressed button but I dont know how to listen to that event from the component which launched the modal.

Body:
We propose a solution that goes as follows:
Make a shared service that handles the modal events (show, hide and callbacks when the modal buttons are clicked), then call that service from any component by passing custom callbacks (and why not a custom modal body).
the modal component:

  export class ModalComponent {
  @ViewChild('theBody', {read: ViewContainerRef}) theBody;
  cmp:ComponentRef;
  data;

  constructor(
    private sharedService:SharedService,
    private componentFactoryResolver: ComponentFactoryResolver,
    injector: Injector) {

    sharedService.modalEvents.subscribe(data => {
      console.log("data", data);
      this.data = data.data;
      if(data.cmd == "show"){
        if(this.cmpRef) {
          this.cmpRef.destroy();
        }
        let factory = this.componentFactoryResolver.resolveComponentFactory(data.component);
        this.cmpRef = this.theBody.createComponent(factory)
        $('#theModal').modal('show');
      }else{
        this.dispose();
      }

    });
  }

   close() {
        //this.dispose();
        this.sharedService.hideModal(true, this.data);
    }

    dispose() {
        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
        this.cmpRef = null;
        $('#theModal').modal('hide');
    }
  edit() {
    this.dispose();
     this.sharedService.modalEvents.next("edit");
  }

  submit() {
    this.dispose();
    this.sharedService.modalEvents.next("submit");
  }
}

and the shared service:

@Injectable()
export class SharedService {

  modalEvents: Subject = new Subject();

  popupData;
  hasModalShown;

  showModal(component:any, data?:any, callback?:any, cancelCallback?:any)  {
        //this.showModal.next(component);

        var innerFunc = ()=> {
            this.popupData = {cmd: "show", component: component, data: data,
            callback: callback, cancelCallback: cancelCallback };
            this.modalEvents.next(this.popupData);
            this.hasModalShown = true;
        }

        if (this.hasModalShown) {
            this.hideModal();
            //setTimeout(innerFunc,600);
        } else {
            innerFunc();
        }
    }

    hideModal(isSubmit:boolean=false, data?:any) {
        if (this.hasModalShown) {
            this.modalEvents.next({cmd: "hide"});
            if(isSubmit && this.popupData.callback){
              this.popupData.callback(data);
            }else if(this.popupData.cancelCallback){
              this.popupData.cancelCallback(data);

            }

            this.hasModalShown = false;
        }
    }
}

this is a working example in plunker


问:
3d models, LOD, pics, etc
I need to program a util for a 3d model. What i need to do is pass the 3d model to the util and have it extract multiple information. Things like poly count, size/scale (if applicable) and anything else i can grab. Then i need to take a screen shot of the model 8 times (45deg from 0 to 360). Maybe 16. Is there an app that i can use to extract data from the model and is there another app i can use to create the image? if so i can write a php script to do this all for me :) if not i'll post more question about specifics.

My OS is debian etch
the models will be any format. I may make it 3ds only or limit it to what the app(s) support. Or i may have another app to convert one format to the other and extract the data from that format.

答:
I haven't tried this, but you could try 3ds2pov to convert your 3DS files into POV-Ray format, and then render with POV-Ray.

The 3ds2pov program is quite old, so I don't know how compatible it is with current 3DS files.  The archive comes with source code so ought to build without too much difficulty on Debian.

POV-Ray itself runs easily on Linux.

nb: other 3DS to POV converters may exist.  This one just happens to be the first one returned by Googling for "3ds to pov".

LastEditorDisplayName: Alnitak

ContentLicense: CC BY-SA 2.5

Title: 3d models, LOD, pics, etc

OwnerDisplayName: Alnitak


问:
Node.js asynchronous requests with APDU
Thanks to ponury-kostek I solved half of my problem. The initial sequential functions already work. Now I only have troubles with a cycle.

Here I need to read 6 chunks of sequential data by order. I need to do 6 requests changing one parameter, the offset (that increases by one each time).

Let's say I got the data in the format of ABCDEF, each one being a chunk of 258 bytes. I want to read it in that order and store it in a variable or a file.

Since the functions are async I'm getting AEFDBC or ABFDEC or ...

```<code>console.log("---get bin "+offset+"---")
</code>```

Can I also make it work with promises?

The code:

```<code>function getBinPromise(){
    var foffset = 0x00;
    var i = 0;
    for(i=0; i<6;){
        getBinChunkPromise(foffset).then(i++)
        foffset = foffset + 0x01;
    }
}

function getBinChunkPromise(offset){
    return new Promise(function(resolve, reject) {
        GetBinApdu = new
        Buffer( [0x00, 0xB0, offset, 0x00, 0x00] );
        reader.transmit(GetBinApdu, 258, protocol, function (err, data) {
            if(err){
                console.log(err);
                reject(err);
            } else {
                console.log("---get bin "+offset+"---")
                console.log('Data received:', data);
                console.log('Last two:', data[data.length-2], data[data.length-1]);
                fs.appendFileSync("data.txt", data);
                console.log("------");
                resolve(data);
            }
        })
    })
}
</code>```

Sorry if this is idiot, I'm new with JS

答:
You need to resolve/reject inside transmit callback function. So you will get something like this:

```<code>function selectAppPromise(){
    return new Promise(function(resolve, reject) {
        SelectAppletApdu = new Buffer( [0x00,  0xA4,  0x04, 0x00, 0x07, 0x60, 0x46, 0x32, 0xff, 0x00, appletoffset, 0x02] );
        console.log("---select app---");
        reader.transmit(SelectAppletApdu, 40, protocol, function (err, data) {
            if (err) {
                console.log(err);
                reject(err);
            } else {
                console.log('Data received:', data);
                console.log('Last two:',data[data.length-2],data[data.length-1]);
                resolve(data);
            }
        });
    })
}
</code>```

EDIT:

```<code>function getBinPromise() {
    var foffset = 0x00;
    var promises = [];
    for (var i = 0; i < 6; i++) {
        promises.push(getBinChunkPromise);
    }
    promises.reduce((prevTask, current) => {
        return prevTask.then(current);
    }, Promise.resolve(foffset)).then(() => {
        console.log('all done');
    });
}
function getBinChunkPromise(offset) {
    return new Promise(function (resolve, reject) {
        GetBinApdu = new Buffer([
            0x00,
            0xB0,
            offset,
            0x00,
            0x00
        ]);
        reader.transmit(GetBinApdu, 258, protocol, function (err, data) {
            if (err) {
                console.log(err);
                reject(err);
            } else {
                console.log("---get bin " + offset + "---");
                console.log('Data received:', data);
                console.log('Last two:', data[data.length - 2], data[data.length - 1]);
                fs.appendFileSync("data.txt", data);
                console.log("------");
                resolve(offset + 0x01);
            }
        })
    })
}
</code>```

Title: Node.js asynchronous requests with APDU

Body:
Thanks to ponury-kostek I solved half of my problem. The initial sequential functions already work. Now I only have troubles with a cycle.

Here I need to read 6 chunks of sequential data by order. I need to do 6 requests changing one parameter, the offset (that increases by one each time).

Let's say I got the data in the format of ABCDEF, each one being a chunk of 258 bytes. I want to read it in that order and store it in a variable or a file.

Since the functions are async I'm getting AEFDBC or ABFDEC or ...

console.log("---get bin "+offset+"---")

Can I also make it work with promises?

The code:

function getBinPromise(){
    var foffset = 0x00;
    var i = 0;
    for(i=0; i<6;){
        getBinChunkPromise(foffset).then(i++)
        foffset = foffset + 0x01;
    }
}

function getBinChunkPromise(offset){
    return new Promise(function(resolve, reject) {
        GetBinApdu = new
        Buffer( [0x00, 0xB0, offset, 0x00, 0x00] );
        reader.transmit(GetBinApdu, 258, protocol, function (err, data) {
            if(err){
                console.log(err);
                reject(err);
            } else {
                console.log("---get bin "+offset+"---")
                console.log('Data received:', data);
                console.log('Last two:', data[data.length-2], data[data.length-1]);
                fs.appendFileSync("data.txt", data);
                console.log("------");
                resolve(data);
            }
        })
    })
}

Sorry if this is idiot, I'm new with JS

Body:
You need to resolve/reject inside transmit callback function. So you will get something like this:

function selectAppPromise(){
    return new Promise(function(resolve, reject) {
        SelectAppletApdu = new Buffer( [0x00,  0xA4,  0x04, 0x00, 0x07, 0x60, 0x46, 0x32, 0xff, 0x00, appletoffset, 0x02] );
        console.log("---select app---");
        reader.transmit(SelectAppletApdu, 40, protocol, function (err, data) {
            if (err) {
                console.log(err);
                reject(err);
            } else {
                console.log('Data received:', data);
                console.log('Last two:',data[data.length-2],data[data.length-1]);
                resolve(data);
            }
        });
    })
}

EDIT:

function getBinPromise() {
    var foffset = 0x00;
    var promises = [];
    for (var i = 0; i < 6; i++) {
        promises.push(getBinChunkPromise);
    }
    promises.reduce((prevTask, current) => {
        return prevTask.then(current);
    }, Promise.resolve(foffset)).then(() => {
        console.log('all done');
    });
}
function getBinChunkPromise(offset) {
    return new Promise(function (resolve, reject) {
        GetBinApdu = new Buffer([
            0x00,
            0xB0,
            offset,
            0x00,
            0x00
        ]);
        reader.transmit(GetBinApdu, 258, protocol, function (err, data) {
            if (err) {
                console.log(err);
                reject(err);
            } else {
                console.log("---get bin " + offset + "---");
                console.log('Data received:', data);
                console.log('Last two:', data[data.length - 2], data[data.length - 1]);
                fs.appendFileSync("data.txt", data);
                console.log("------");
                resolve(offset + 0x01);
            }
        })
    })
}


问:
How to map an array object with key from different array set in javascript
I'm building a small application in VueJS where I'm getting a response in following format:

```<code>"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        "client_name":"Test Company 5",
    }
]
</code>```

And I'm having a data set of nature as:

```<code>const nature = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"},
    {value: 3, label: "Demo 3"}
]
</code>```

I want to map my meeting_summaries with this data set were in meeting_summaries -> nature points to nature -> value so that my final output can look something like this:

```<code>"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        'nature_name": "Demo 1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        'nature_name": "Demo 2",
        "client_name":"Test Company 5",
    }
]
</code>```

答:
You could use a hash table and then iterate the meeting_summaries.

const object = { meeting_summaries: [{ interaction_id: 22, nature: "1", client_name: "Test Company 4" }, { interaction_id: 22, nature: "2", client_name: "Test Company 5", mention_name: "Analyst" }] },
      nature = [{ value: 1, label: "Demo 1" }, { value: 2, label: "Demo 2" }, { value: 3, label: "Demo 3" }],
      natureMap = Object.assign(...nature.map(o => ({ [o.value]: o.label })));

object.meeting_summaries.forEach(o => o.nature_name = natureMap[o.nature]);

console.log(object);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm building a small application in VueJS where I'm getting a response in following format:

"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        "client_name":"Test Company 5",
    }
]

And I'm having a data set of nature as:

const nature = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"},
    {value: 3, label: "Demo 3"}
]

I want to map my meeting_summaries with this data set were in meeting_summaries -> nature points to nature -> value so that my final output can look something like this:

"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        'nature_name": "Demo 1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        'nature_name": "Demo 2",
        "client_name":"Test Company 5",
    }
]

Body:
You could use a hash table and then iterate the meeting_summaries.

const object = { meeting_summaries: [{ interaction_id: 22, nature: "1", client_name: "Test Company 4" }, { interaction_id: 22, nature: "2", client_name: "Test Company 5", mention_name: "Analyst" }] },
      nature = [{ value: 1, label: "Demo 1" }, { value: 2, label: "Demo 2" }, { value: 3, label: "Demo 3" }],
      natureMap = Object.assign(...nature.map(o => ({ [o.value]: o.label })));

object.meeting_summaries.forEach(o => o.nature_name = natureMap[o.nature]);

console.log(object);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Cordova SQLite not returning rows after query
I have a Cordova app and I'm using cordova-sqlite-storage plugin

My query is very simple:

```<code>SELECT * FROM clients;
</code>```

This is the Javascript code:

```<code>  ctx.transaction(function(tx) {
        tx.executeSql("SELECT * FROM cards;", [], function(tx, rs) {
            alert(JSON.stringify(rs));
            onSuccess(rs);
        }, function(tx, error) {
            onfail();
        });
    });
</code>```

the rs doesn't contain the row data, the alert shows:

```<code>{"rows":{"length":1},"rowsAffected":0}
</code>```

so I have 1 row somewhere but it's not returning it

what I'm missing here?

答:
to get back data you need to use rs.rows.item(0).fieldname

try alert (rs.rows.item(0));

Body:
I have a Cordova app and I'm using cordova-sqlite-storage plugin

My query is very simple:

SELECT * FROM clients;

This is the Javascript code:

  ctx.transaction(function(tx) {
        tx.executeSql("SELECT * FROM cards;", [], function(tx, rs) {
            alert(JSON.stringify(rs));
            onSuccess(rs);
        }, function(tx, error) {
            onfail();
        });
    });

the rs doesn't contain the row data, the alert shows:

{"rows":{"length":1},"rowsAffected":0}

so I have 1 row somewhere but it's not returning it

what I'm missing here?


问:
LINQ to NHibernate: could not resolve property
Fluent nHibernate using nHibernate v. 2.1.2.4, nHibernate.Linq v. 1.1.0.1001, and Fluent NHibernate v. 1.1.0.685.

I have a domain object with a DateTime field called DateOfEvent. This is an actual date/time field in the database. I've also added 2 new properties YearOfEvent which grabs the Year from the DateOfEvent field as well as MontOfEvent which grabs the Month from the DateOfEvent field.

```<code>public class Event
{
    public Event() { }
    public virtual Int32 Id { get; set; }
    public virtual String Title { get; set; }
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent
    {
        get { return DateOfEvent.Year; }
    }
    public virtual Int32 MonthOfEvent
    {
        get { return DateOfEvent.Month; }
    }
    public virtual String Location { get; set; }
    public virtual String City { get; set; }
    public virtual String State { get; set; }
    public virtual String Zip { get; set; }
    public virtual String Description { get; set; }
    public virtual Boolean HasImage { get; set; }
    public virtual Boolean IsActive { get; set; }
}
</code>```

However, when running this method:

```<code>public IList<Event> GetActiveEvents(int pageNumber, int pageSize, out int totalItems)
    {
        Int32 skip = Misc.NumberToSkip(pageNumber, pageSize);
        totalItems = (from e in _session.Linq<Event>()
                      where e.IsActive
                      select e).Count();

        return (from e in _session.Linq<Event>()
                where e.IsActive
                select e)
            .Skip(skip)
            .Take(pageSize)
            .ToList();
    }
</code>```

NHibernate.QueryException: could not resolve property: YearOfEvent of: ....Event

FWIW, I've blurred out the name of the project. ;)

Any idea how to get this query working?

Thanks!
-Steve

EDIT:
Here's my mapping class:

```<code>public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.Description, "description");
        Map(x => x.Title, "title");
        Map(x => x.Location, "location");
        Map(x => x.State, "state");
        Map(x => x.City, "city");
        Map(x => x.Zip, "zip");
        Map(x => x.HasImage, "hasImage");
        Map(x => x.IsActive, "isActive");
    }
}
</code>```

...and my config:

```<code>public Configuration GetConfiguration()
    {
        Configuration configuration;
        var assembly = Assembly.Load(".....Data");
        var fluentConfig = Fluently.Configure()
                            .Database(MySQLConfiguration.Standard.ConnectionString(
                                          c => c.FromConnectionStringWithKey("......")
                                          ))
                            .Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
        configuration = fluentConfig.BuildConfiguration();
        configuration.Properties.Add("hbm2ddl.keywords", "none");
        return configuration;
    }
</code>```

I also just tried the Criteria API:

```<code>return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();
</code>```

No workie either.

答:
Your criteria query is not working, because your "YearOfEvent" property is not listed in your mapping. NHibernate does not know this property, and cannot translate it into a column name.

Try querying on properties that are actually mapped instead of calculated properties, or calculate the property directly in your query...

However, your linq query looks like it should be working, I don't see how this error can occur with that query & mapping...

Body:
Fluent nHibernate using nHibernate v. 2.1.2.4, nHibernate.Linq v. 1.1.0.1001, and Fluent NHibernate v. 1.1.0.685.

I have a domain object with a DateTime field called DateOfEvent. This is an actual date/time field in the database. I've also added 2 new properties YearOfEvent which grabs the Year from the DateOfEvent field as well as MontOfEvent which grabs the Month from the DateOfEvent field.

public class Event
{
    public Event() { }
    public virtual Int32 Id { get; set; }
    public virtual String Title { get; set; }
    public virtual DateTime DateOfEvent { get; set; }
    public virtual Int32 YearOfEvent
    {
        get { return DateOfEvent.Year; }
    }
    public virtual Int32 MonthOfEvent
    {
        get { return DateOfEvent.Month; }
    }
    public virtual String Location { get; set; }
    public virtual String City { get; set; }
    public virtual String State { get; set; }
    public virtual String Zip { get; set; }
    public virtual String Description { get; set; }
    public virtual Boolean HasImage { get; set; }
    public virtual Boolean IsActive { get; set; }
}

However, when running this method:

public IList<Event> GetActiveEvents(int pageNumber, int pageSize, out int totalItems)
    {
        Int32 skip = Misc.NumberToSkip(pageNumber, pageSize);
        totalItems = (from e in _session.Linq<Event>()
                      where e.IsActive
                      select e).Count();

        return (from e in _session.Linq<Event>()
                where e.IsActive
                select e)
            .Skip(skip)
            .Take(pageSize)
            .ToList();
    }

NHibernate.QueryException: could not resolve property: YearOfEvent of: ....Event

FWIW, I've blurred out the name of the project. ;)

Any idea how to get this query working?

Thanks!
-Steve

EDIT:
Here's my mapping class:

public class EventMap : ClassMap<Event>
{
    public EventMap()
    {
        Table("tbl_event");
        Id(x => x.Id, "eventId");
        Map(x => x.DateOfEvent, "dateOfEvent");
        Map(x => x.Description, "description");
        Map(x => x.Title, "title");
        Map(x => x.Location, "location");
        Map(x => x.State, "state");
        Map(x => x.City, "city");
        Map(x => x.Zip, "zip");
        Map(x => x.HasImage, "hasImage");
        Map(x => x.IsActive, "isActive");
    }
}

...and my config:

public Configuration GetConfiguration()
    {
        Configuration configuration;
        var assembly = Assembly.Load(".....Data");
        var fluentConfig = Fluently.Configure()
                            .Database(MySQLConfiguration.Standard.ConnectionString(
                                          c => c.FromConnectionStringWithKey("......")
                                          ))
                            .Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
        configuration = fluentConfig.BuildConfiguration();
        configuration.Properties.Add("hbm2ddl.keywords", "none");
        return configuration;
    }

I also just tried the Criteria API:

return _session.CreateCriteria(typeof (Event))
            .Add(Expression.Eq("IsActive", true))
            .Add(Expression.Eq("YearOfEvent", year))
            .List<Event>();

No workie either.


问:
PayPal donation button with price options dropdown sending empty/zero value
I am trying to generate a PayPal donation button with a price drop down and a Yes-No drop down. Button is working fine but the amount/price is going empty. Below is the html generated from PayPal's website. Could anyone please help? Thanks!</p>

```<code><form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="my@email.com">
<input type="hidden" name="lc" value="GB">
<input type="hidden" name="item_name" value="IICC">
<input type="hidden" name="item_number" value="GT7">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="rm" value="1">
<input type="hidden" name="return" value="http://website.org/">
<input type="hidden" name="cancel_return" value="http://website.org/">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHosted">
<table>
<tr><td><input type="hidden" name="on0" value="Select a donation category">Select a donation category</td></tr><tr><td><select name="os0">
<option value="Red">Red £50.00 GBP</option>
<option value="Bronze">Bronze £100.00 GBP</option>
<option value="Silver">Silver £200.00 GBP</option>
<option value="Gold">Gold £300.00 GBP</option>
<option value="Platinum">Platinum £500.00 GBP</option>
<option value="Diamond">Diamond £1,000.00 GBP</option>
</select> </td></tr>
<tr><td><input type="hidden" name="on1" value="Do you agree?">Do you agree?</td></tr><tr><td><select name="os1">
<option value="NO">NO</option>
<option value="YES">YES</option>
</select> </td></tr>
</table>
<input type="hidden" name="currency_code" value="GBP">
<input type="hidden" name="option_select0" value="Red">
<input type="hidden" name="option_amount0" value="50.00">
<input type="hidden" name="option_select1" value="Bronze">
<input type="hidden" name="option_amount1" value="100.00">
<input type="hidden" name="option_select2" value="Silver">
<input type="hidden" name="option_amount2" value="200.00">
<input type="hidden" name="option_select3" value="Gold">
<input type="hidden" name="option_amount3" value="300.00">
<input type="hidden" name="option_select4" value="Platinum">
<input type="hidden" name="option_amount4" value="500.00">
<input type="hidden" name="option_select5" value="Diamond">
<input type="hidden" name="option_amount5" value="1000.00">
<input type="hidden" name="option_index" value="0">
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</code>```

答:
AFAIK, option_index is not supported by donation buttons (cmd = _donations). You may try to use a BuyNow button (cmd = _xclick) instead, or change the amount field into a drop down menu, like

<select name="amount">
 <option value="50">Red</option>
 <option value="100">Bronze</option>
 <option value="200">Silver</option>
 ...
</select>```

Body:
I am trying to generate a PayPal donation button with a price drop down and a Yes-No drop down. Button is working fine but the amount/price is going empty. Below is the html generated from PayPal's website. Could anyone please help? Thanks!

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="my@email.com">
<input type="hidden" name="lc" value="GB">
<input type="hidden" name="item_name" value="IICC">
<input type="hidden" name="item_number" value="GT7">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="rm" value="1">
<input type="hidden" name="return" value="http://website.org/">
<input type="hidden" name="cancel_return" value="http://website.org/">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHosted">

<input type="hidden" name="on0" value="Select a donation category">Select a donation category

<select name="os0">
<option value="Red">Red £50.00 GBP</option>
<option value="Bronze">Bronze £100.00 GBP</option>
<option value="Silver">Silver £200.00 GBP</option>
<option value="Gold">Gold £300.00 GBP</option>
<option value="Platinum">Platinum £500.00 GBP</option>
<option value="Diamond">Diamond £1,000.00 GBP</option>
</select>

<input type="hidden" name="on1" value="Do you agree?">Do you agree?

<select name="os1">
<option value="NO">NO</option>
<option value="YES">YES</option>
</select>

<input type="hidden" name="currency_code" value="GBP">
<input type="hidden" name="option_select0" value="Red">
<input type="hidden" name="option_amount0" value="50.00">
<input type="hidden" name="option_select1" value="Bronze">
<input type="hidden" name="option_amount1" value="100.00">
<input type="hidden" name="option_select2" value="Silver">
<input type="hidden" name="option_amount2" value="200.00">
<input type="hidden" name="option_select3" value="Gold">
<input type="hidden" name="option_amount3" value="300.00">
<input type="hidden" name="option_select4" value="Platinum">
<input type="hidden" name="option_amount4" value="500.00">
<input type="hidden" name="option_select5" value="Diamond">
<input type="hidden" name="option_amount5" value="1000.00">
<input type="hidden" name="option_index" value="0">
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">

</form>


问:
Retrieve an Integer part from a String
I have to use an int value "nid" to work on. But this int value should be an combination of int "did" and String "a"!

```<code>int did = 123456;
String a = "_b";
int nid = Integer.parseInt((did+a).toString());
</code>```

But for this code i get the error message

```<code>java.lang.NumberFormatException: For input string: "123456_b"
</code>```

Is there any way, to convert a combination of int and string to int?

答:
I don't understand what you want.
The error is normal, b is not a number and you can't declare nid as int.

Maybe you want just to concatenate a with did ?

On this case, nid must be a String, not a int.

Title: Retrieve an Integer part from a String

Body:
I have to use an int value "nid" to work on. But this int value should be an combination of int "did" and String "a"!

int did = 123456;
String a = "_b";
int nid = Integer.parseInt((did+a).toString());

But for this code i get the error message

java.lang.NumberFormatException: For input string: "123456_b"

Is there any way, to convert a combination of int and string to int?


问:
C# Debug Property Name displayed as box
I am getting boxes instead of property/member name while debugging in Visual Studio 2015. And this issue does not occur for all the variables. Please refer the image.
enter image description here

I referred the post What does it mean when my text is displayed as boxes?. But it does not help me to set steps to set the font. Any help to fix this issue is much appreciated.

答:
This is happening because your variable names are written in Unicode.

Since Visual Studio debugger window does not support Unicode, the only way to solve this issue is to rename your variables to plain English (no Unicode characters).

Title: C# Debug Property Name displayed as box


问:
Dictionary and object to web service content type string
I have Dictionary with values how to convert them to string of format  application/json and application/x-www-form-urlencoded simplest standard  way:

```<code>    var values = new Dictionary<string, string>
    {
        {"id", "1"},
        {"amount", "5"}
    };
</code>```

The same question regarding class object with the same fields:

```<code>class values
{
    public String id  { get; set; }
    public string amount { get; set; }

}
</code>```

答:
It's not clear from your question if you want to manually serialize your dictionary or object and then send it using a custom way or if you would like to automatically serialize and send them to a web service.

The manual way:

Json

```<code>PM > Install-Package Newtonsoft.Json
</code>```

Json.NET natively supports dictionary to Json object and, of course, object to json object serialization. You simply install it and than serialize using:

```<code>var jsonString = JsonConvert.SerializeObject(values); // values can be Dictionary<string, Anything> OR an object
</code>```

Result:

```<code>{
    "id": "1",
    "amount", "5"
}
</code>```

Form URL encoded

The cleanest way is to use the .NET built-in utility HttpUtility.ParseQueryString (which also encodes any non-ASCII character):

```<code>var nvc = HttpUtility.ParseQueryString("");
foreach(var item in values)
    nvc.Add(item.Key, item.Value);

var urlEncodedString = nvc.ToString();
</code>```

Result:

```<code>id=1&amount=5
</code>```

Please note that there is no direct way to serialize an object into a Form URL encoded string without adding its members manually, e.g.:

```<code>nvc.Add(nameof(values.id), values.id);
nvc.Add(nameof(values.amount), values.amount);
</code>```

The automatic way:

Everything is simpler if you just use HttpClient:

```<code>PM > Install-Package Microsoft.AspNet.WebApi.Client
</code>```

Json

You may need to also use HttpClientExtensions extension methods for automatic Json serialization (without it you need to serialize it manually as shown above):

```<code>using (var client = new HttpClient())
{
    // set any header here
    var response = await client.PostAsJsonAsync("http://myurl", values); // values can be a dictionary or an object

    var result = await response.Content.ReadAsAsync<MyResultClass>();
}
</code>```

Form URL encoded

```<code>using (var client = new HttpClient())
{
    using (var content = new FormUrlEncodedContent(values)) // this must be a dictionary or a IEnumerable<KeyValuePair<string, string>>
    {
        content.Headers.Clear();
        content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

        var response = await client.PostAsync(url, content);

        var result = await response.Content.ReadAsAsync<MyResultClass>();
    }
}
</code>```

This way you may serialize dictionaries directly. Again for objects you need to convert them manually as shown above.

Body:
I have Dictionary with values how to convert them to string of format  application/json and application/x-www-form-urlencoded simplest standard  way:

    var values = new Dictionary<string, string>
    {
        {"id", "1"},
        {"amount", "5"}
    };

The same question regarding class object with the same fields:

class values
{
    public String id  { get; set; }
    public string amount { get; set; }

}

Body:
It's not clear from your question if you want to manually serialize your dictionary or object and then send it using a custom way or if you would like to automatically serialize and send them to a web service.

The manual way:

Json

PM > Install-Package Newtonsoft.Json

Json.NET natively supports dictionary to Json object and, of course, object to json object serialization. You simply install it and than serialize using:

var jsonString = JsonConvert.SerializeObject(values); // values can be Dictionary<string, Anything> OR an object

Result:

{
    "id": "1",
    "amount", "5"
}

Form URL encoded

The cleanest way is to use the .NET built-in utility HttpUtility.ParseQueryString (which also encodes any non-ASCII character):

var nvc = HttpUtility.ParseQueryString("");
foreach(var item in values)
    nvc.Add(item.Key, item.Value);

var urlEncodedString = nvc.ToString();

Result:

id=1&amount=5

Please note that there is no direct way to serialize an object into a Form URL encoded string without adding its members manually, e.g.:

nvc.Add(nameof(values.id), values.id);
nvc.Add(nameof(values.amount), values.amount);

The automatic way:

Everything is simpler if you just use HttpClient:

PM > Install-Package Microsoft.AspNet.WebApi.Client

Json

You may need to also use HttpClientExtensions extension methods for automatic Json serialization (without it you need to serialize it manually as shown above):

using (var client = new HttpClient())
{
    // set any header here
    var response = await client.PostAsJsonAsync("http://myurl", values); // values can be a dictionary or an object

    var result = await response.Content.ReadAsAsync<MyResultClass>();
}

Form URL encoded

using (var client = new HttpClient())
{
    using (var content = new FormUrlEncodedContent(values)) // this must be a dictionary or a IEnumerable<KeyValuePair<string, string>>
    {
        content.Headers.Clear();
        content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

        var response = await client.PostAsync(url, content);

        var result = await response.Content.ReadAsAsync<MyResultClass>();
    }
}

This way you may serialize dictionaries directly. Again for objects you need to convert them manually as shown above.


问:
How to compare current value with old value in TextWatcher?
I'm rendering the values from my database and placing those values in respective EditText field, so generally allowing the users to modify their save data.

I have a SAVE button on my page, where by default disabled. It should be enabled only when the EditText fields are really modified.

When comparing with the Database value,

If the edit text value is changed  - modified

If the EditText Value is edited but not changed (user may copy paste the same value)- not modified.

Here is my code,

```<code>EditText text1  = (EditText) findViewById(R.id.text1);
EditText text2  = (EditText) findViewById(R.id.text2);
EditText text3  = (EditText) findViewById(R.id.text3);
EditText text4  = (EditText) findViewById(R.id.text4);
EditText text5  = (EditText) findViewById(R.id.text5);

ArrayList<EditText> editTextList = new ArrayList();
editTextList.add(text1);
editTextList.add(text2);
editTextList.add(text3);
editTextList.add(text4);
editTextList.add(text5);

for(EditText e : editTextList)
  e.addTextChangedListener(textWatcher);

private TextWatcher textWatcher = new TextWatcher() {

public void afterTextChanged(Editable s){}
public void beforeTextChanged(CharSequence s, int start, int count, int
after) {}
 public void onTextChanged(CharSequence s, int start, int before,int
count) {}
};
</code>```

Is there any way to compare the database value with current given value in EditText?

NOTE:

Since the TextWatcher function is common to all EditText, I want to do the comparison common.

答: you have to control it by yourself with a global variable. or reactive object or use databinding. </p>

Body:
I'm rendering the values from my database and placing those values in respective EditText field, so generally allowing the users to modify their save data.

I have a SAVE button on my page, where by default disabled. It should be enabled only when the EditText fields are really modified.

When comparing with the Database value,

If the edit text value is changed  - modified

If the EditText Value is edited but not changed (user may copy paste the same value)- not modified.

Here is my code,

EditText text1  = (EditText) findViewById(R.id.text1);
EditText text2  = (EditText) findViewById(R.id.text2);
EditText text3  = (EditText) findViewById(R.id.text3);
EditText text4  = (EditText) findViewById(R.id.text4);
EditText text5  = (EditText) findViewById(R.id.text5);

ArrayList<EditText> editTextList = new ArrayList();
editTextList.add(text1);
editTextList.add(text2);
editTextList.add(text3);
editTextList.add(text4);
editTextList.add(text5);

for(EditText e : editTextList)
  e.addTextChangedListener(textWatcher);

private TextWatcher textWatcher = new TextWatcher() {

public void afterTextChanged(Editable s){}
public void beforeTextChanged(CharSequence s, int start, int count, int
after) {}
 public void onTextChanged(CharSequence s, int start, int before,int
count) {}
};

Is there any way to compare the database value with current given value in EditText?

NOTE:

Since the TextWatcher function is common to all EditText, I want to do the comparison common.


问:
Adding TinyMCE on the fly
I am using the TinyMCE editor. I have a div element. When an edit link is clicked, I would like to replace it with a TinyMCE editor. I added the mceEditor class in the javascript file that will get executed when the edit link is clicked.But it is not working. TinyMCE editor works when I have a textarea during page load. Can someone please tell me how to do it. Thanks.

```<code><textarea id='answer' rows='25' cols='100' class='span-15 mceEditor'></textarea><br />
</code>```

答: I added it using tinyMCE.execCommand('mceAddControl',false,'elementId') and removed it using tinyMCE.execCommand('mceRemoveControl',false,'elementId')

Title: Adding TinyMCE on the fly

Body:
I am using the TinyMCE editor. I have a div element. When an edit link is clicked, I would like to replace it with a TinyMCE editor. I added the mceEditor class in the javascript file that will get executed when the edit link is clicked.But it is not working. TinyMCE editor works when I have a textarea during page load. Can someone please tell me how to do it. Thanks.

<textarea id='answer' rows='25' cols='100' class='span-15 mceEditor'></textarea>


问:
Center All Elements to a Certain Width
I'm trying to get everything to center and to about 80% of the page. Everything seems fine, except for my two main divs extend over my banner and nav bar by about 1px, even though they are set to 80%.

Here is the CSS: https://pastebin.com/HM7PLqX0

body {
  background: url('bg.png');
  background-size: cover;
  background-repeat: none;
}

.banner {
  font-family: 'Raleway', sans-serif;
  color: #f2f2f2;
  margin-top: 20px;
  text-align: center;
  background: url('bg.jpg') no-repeat;
  background-size: cover;
  background-position: center;
  line-height: 120px;
  font-size: 40px;
  text-shadow: 2px 2px 2px black;
  width: 80%;
  height: 120px;
  margin: 0 auto;
}

.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 60%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.stats {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 20%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.logo {
  margin-top: 50px;
  font-family: myFirstFont;
  color: white;
  text-align: center;
  font-size: 50px;
}

.topnav {
  background-color: #333;
  overflow: hidden;
  width: 80%;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='logo'>
  The Realm MC
</div>

<div class="topnav" id="myTopnav">
  <i class="fa fa-home" aria-hidden="true"></i>
     Home
  <i class="fa fa-play" aria-hidden="true"></i>
     Play
  <i class="fa fa-comment-o" aria-hidden="true"></i>
     Forums
  <i class="fa fa-heart-o" aria-hidden="true"></i>
     Donate
</div>

<div class='banner'>
  There are 7 out of 10 players online!
</div>
<br />

<div id='wrapper' style='text-align:center;'>
  <div class='about'>
    Lorem ipsum<br /> dolor sit amet
  </div>

  <div class='stats'>
    Lorem ipsum<br /> dolor sit amet
  </div>
</div></code>```

答:
You must assign a width:80% for wrapper.

use of float property instead of display:inline-block.

So,Change Like this :

```<code>#wrapper {
    width: 80%;/*/<-------------------/*/
    margin: 0 auto;/*/<-------------------/*/
    box-sizing: border-box;/*/<-------------------/*/
}

.about {
  background-color: #333;
  opacity: 0.8;
  vertical-align: top;
  text-align: center;
  width: 70%;/*/<-------------------/*/
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
  float: left;/*/<-------------------/*/
  /*/-------Remove display:inline-block-----------/*/
}

.stats {
  background-color: #333;
  opacity: 0.8;
  vertical-align: top;
  text-align: center;
  width: 29%;/*/<---------1% for margin-left ----------/*/
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
  float: right;/*/<-------------------/*/
   /*/-------Remove display:inline-block-----------/*/
}
</code>```

This is Demo

Title: Center All Elements to a Certain Width

Body:
I'm trying to get everything to center and to about 80% of the page. Everything seems fine, except for my two main divs extend over my banner and nav bar by about 1px, even though they are set to 80%.

Here is the CSS: https://pastebin.com/HM7PLqX0

body {
  background: url('bg.png');
  background-size: cover;
  background-repeat: none;
}

.banner {
  font-family: 'Raleway', sans-serif;
  color: #f2f2f2;
  margin-top: 20px;
  text-align: center;
  background: url('bg.jpg') no-repeat;
  background-size: cover;
  background-position: center;
  line-height: 120px;
  font-size: 40px;
  text-shadow: 2px 2px 2px black;
  width: 80%;
  height: 120px;
  margin: 0 auto;
}

.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 60%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.stats {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 20%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.logo {
  margin-top: 50px;
  font-family: myFirstFont;
  color: white;
  text-align: center;
  font-size: 50px;
}

.topnav {
  background-color: #333;
  overflow: hidden;
  width: 80%;
  margin: 0 auto;
}

  The Realm MC

     Home

     Play

     Forums

     Donate

  There are 7 out of 10 players online!

    Lorem ipsum
 dolor sit amet

    Lorem ipsum
 dolor sit amet

Body:
You must assign a width:80% for wrapper.

use of float property instead of display:inline-block.

So,Change Like this :

#wrapper {
    width: 80%;/*/<-------------------/*/
    margin: 0 auto;/*/<-------------------/*/
    box-sizing: border-box;/*/<-------------------/*/
}

.about {
  background-color: #333;
  opacity: 0.8;
  vertical-align: top;
  text-align: center;
  width: 70%;/*/<-------------------/*/
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
  float: left;/*/<-------------------/*/
  /*/-------Remove display:inline-block-----------/*/
}

.stats {
  background-color: #333;
  opacity: 0.8;
  vertical-align: top;
  text-align: center;
  width: 29%;/*/<---------1% for margin-left ----------/*/
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
  float: right;/*/<-------------------/*/
   /*/-------Remove display:inline-block-----------/*/
}

This is Demo


问:
Implementing a custom event handler from interface
I am in the process of creating a system that can receive messages from a variety of different sources.

Using the interface approach, I am adding a custom event which will pass the message back to the calling application.

I've used Vistual Studio's "scaffolding" using Ctrl-. to provide the implementation for the concrete class, but its added the add and remove elements but I dont really know how to wire that bit up.

Interface class

```<code>public class MessageEventArgs : EventArgs
{
    public Message { get; set; }
}

public interface MessageBroker
{
    void Start();

    event EventHandler<MessageEventArgs> OnMessageReceived;
}
</code>```

Implementation class

```<code>public class MessageSourceA : MessageBroker
{
    event EventHandler<MessageEventArgs> MessageBroker.OnMessageReceived
    {
        add
        {
            // What goes here
        }

        remove
        {
            // What goes here
        }
    }

    void MessageBroker.Start()
    {
    }
}
</code>```

Main Program

```<code>    static void Main(string[] args)
    {
        MessageBroker sourceA = new MessageSourceA ();
        sourceA.OnMessageReceived += sourceA_OnMessageReceived;
    }

    private static void sourceA_OnMessageReceived(object sender, MessageEventArgs e)
    {
        // Do stuff with message
    }
</code>```

Thanks...

答:
You could normally implement from interface.

```<code>public class MessageSourceA : IMessageBroker
{
    public void Start();
    public event EventHandler<MessageEventArgs> OnMessageReceived;
 }
</code>```

I suggest you to rename MessageBroker to IMessageBroker as its a naming convention. Since "I" helps to differentiate between class and interface when looking at code.

If there is proper reason to implement interface explicitly you need private event handler.

```<code>private event EventHandler<MessageEventArgs> _onMessageReceived;

event EventHandler<MessageEventArgs> MessageBroker.OnMessageReceived
{
    add
    {
        _onMessageRecieved += value;
    }
    remove
    {
        _onMessageRecieved -= value;
    }
}
</code>```

Body:
I am in the process of creating a system that can receive messages from a variety of different sources.

Using the interface approach, I am adding a custom event which will pass the message back to the calling application.

I've used Vistual Studio's "scaffolding" using Ctrl-. to provide the implementation for the concrete class, but its added the add and remove elements but I dont really know how to wire that bit up.

Interface class

public class MessageEventArgs : EventArgs
{
    public Message { get; set; }
}

public interface MessageBroker
{
    void Start();

    event EventHandler<MessageEventArgs> OnMessageReceived;
}

Implementation class

public class MessageSourceA : MessageBroker
{
    event EventHandler<MessageEventArgs> MessageBroker.OnMessageReceived
    {
        add
        {
            // What goes here
        }

        remove
        {
            // What goes here
        }
    }

    void MessageBroker.Start()
    {
    }
}

Main Program

    static void Main(string[] args)
    {
        MessageBroker sourceA = new MessageSourceA ();
        sourceA.OnMessageReceived += sourceA_OnMessageReceived;
    }

    private static void sourceA_OnMessageReceived(object sender, MessageEventArgs e)
    {
        // Do stuff with message
    }

Thanks...

Body:
You could normally implement from interface.

public class MessageSourceA : IMessageBroker
{
    public void Start();
    public event EventHandler<MessageEventArgs> OnMessageReceived;
 }

I suggest you to rename MessageBroker to IMessageBroker as its a naming convention. Since "I" helps to differentiate between class and interface when looking at code.

If there is proper reason to implement interface explicitly you need private event handler.

private event EventHandler<MessageEventArgs> _onMessageReceived;

event EventHandler<MessageEventArgs> MessageBroker.OnMessageReceived
{
    add
    {
        _onMessageRecieved += value;
    }
    remove
    {
        _onMessageRecieved -= value;
    }
}


问:
Get All Objects From Glade File
I know it's possible to import specific objects from a glade file using:

```<code>builder.add_objects_from_file("example.glade", ("button1", "button2"))
</code>```

But as you can see, I have to pass a list of the objects I want to import.

Is there a way to import everything in the .glade file? All the objects without having to specify their names here?

答:
When you use gtk_builder_add_objects_from_file, you are merging specific objects to an existing GtkBuilder instance which will then instantiate those same objects. Using this function/method is only useful if you need a specific set of objects from a UI definition file.

The normal use of GtkBuilder, would be to load it entirely and then retrieve the object you want to deal with gtk_builder_get_object. But if your goal is to retrieve all the objects, then use gtk_builder_get_objects which will return a GSList. Using this function/method assumes that you already loaded a UI definition file from a file or from another possible source.

As documented:

GSList *gtk_builder_get_objects (GtkBuilder *builder);

Gets all objects that have been constructed by builder . Note that
  this function does not increment the reference counts of the returned
  objects.

Returns

a newly-allocated GSList containing all the objects constructed by the
  GtkBuilder instance. It should be freed by g_slist_free().

Title: Get All Objects From Glade File

Body:
I know it's possible to import specific objects from a glade file using:

builder.add_objects_from_file("example.glade", ("button1", "button2"))

But as you can see, I have to pass a list of the objects I want to import.

Is there a way to import everything in the .glade file? All the objects without having to specify their names here?


问:
Is it possible to use a circle (SKShapeNode) as a mask in Sprite Kit?
I'm trying to create a circular mask in a Sprite Kit project. I create the circle like this (positioning it at the centre of the screen):

```<code>SKCropNode *cropNode = [[SKCropNode alloc] init];

SKShapeNode *circleMask = [[SKShapeNode alloc ]init];
CGMutablePathRef circle = CGPathCreateMutable();
CGPathAddArc(circle, NULL, CGRectGetMidX(self.frame), CGRectGetMidY(self.frame), 50, 0, M_PI*2, YES);
circleMask.path = circle;
circleMask.lineWidth = 0;
circleMask.fillColor = [SKColor blueColor];
circleMask.name=@"circleMask";
</code>```

and further down the code, I set it as the mask for the cropNode:

```<code>[cropNode setMaskNode:circleMask];
</code>```

... but instead of the content showing inside a circle, the mask appears as a square.

Is it possible to use a SKShapeNode as a mask, or do I need to use an image?

答:
There is a slightly awkward solution to this issue that I believe is slightly less nasty than any of the mooted hacks around this issue. Simply wrap your SKShapeNode in an SKNode. I haven't tested what kind of performance hit this might cause, but given that SKNode is non-drawing, I'm hoping it won't be too significant.

i.e.

```<code>let background = SKSpriteNode(imageNamed: "Background")
let maskNode = SKShapeNode(path: MyPath)
let wrapperNode = SKNode()
let cropNode = SKCropNode()

wrapperNode.addChild(maskNode)
cropNode.maskNode = wrapperNode
cropNode.addChild(background)
</code>```

Body:
I'm trying to create a circular mask in a Sprite Kit project. I create the circle like this (positioning it at the centre of the screen):

SKCropNode *cropNode = [[SKCropNode alloc] init];

SKShapeNode *circleMask = [[SKShapeNode alloc ]init];
CGMutablePathRef circle = CGPathCreateMutable();
CGPathAddArc(circle, NULL, CGRectGetMidX(self.frame), CGRectGetMidY(self.frame), 50, 0, M_PI*2, YES);
circleMask.path = circle;
circleMask.lineWidth = 0;
circleMask.fillColor = [SKColor blueColor];
circleMask.name=@"circleMask";

and further down the code, I set it as the mask for the cropNode:

[cropNode setMaskNode:circleMask];

... but instead of the content showing inside a circle, the mask appears as a square.

Is it possible to use a SKShapeNode as a mask, or do I need to use an image?

Body:
There is a slightly awkward solution to this issue that I believe is slightly less nasty than any of the mooted hacks around this issue. Simply wrap your SKShapeNode in an SKNode. I haven't tested what kind of performance hit this might cause, but given that SKNode is non-drawing, I'm hoping it won't be too significant.

i.e.

let background = SKSpriteNode(imageNamed: "Background")
let maskNode = SKShapeNode(path: MyPath)
let wrapperNode = SKNode()
let cropNode = SKCropNode()

wrapperNode.addChild(maskNode)
cropNode.maskNode = wrapperNode
cropNode.addChild(background)


问:
Python: Regex help
```<code>str = "a\b\c\dsdf\matchthis\erwe.txt"
</code>```

The last folder name.

Match "matchthis"

答:
```<code>>>> str = "a\\b\\c\\dsdf\\matchthis\\erwe.txt"
>>> str.split("\\")[-2]
'matchthis'
</code>```

Title: Python: Regex help

Body:
str = "a\b\c\dsdf\matchthis\erwe.txt"

The last folder name.

Match "matchthis"


问:
How to validate a file name in java
I am working with a coverity issue which i need to validate a file name
    using  regEx in java . In my application support .pdf , .txt , csv etc . My
    file name getting as xxx.txt from user . i want to validate my file name
    with proper extension format and not included any special character other
    than dot ( eg .txt) .

```<code>filePath = properties.getProperty("DOCUMENT.LIBRARY.LOCATION");
String fileName = (String) request.getParameter("read");
</code>```

Only If the file path is completed itsproper validation, the below code should be work .

```<code>filePath += "/" + fileName;
</code>```

答:
Have a look at String.endsWith() method

```<code>if (fileName.endsWith(".pdf")) {
   // do something
}
</code>```

Or use the method String.matches()

```<code>fileName.matches("\\.(pdf|txt|csv)$")
</code>```

Title: How to validate a file name in java

Body:
I am working with a coverity issue which i need to validate a file name
    using  regEx in java . In my application support .pdf , .txt , csv etc . My
    file name getting as xxx.txt from user . i want to validate my file name
    with proper extension format and not included any special character other
    than dot ( eg .txt) .

filePath = properties.getProperty("DOCUMENT.LIBRARY.LOCATION");
String fileName = (String) request.getParameter("read");

Only If the file path is completed itsproper validation, the below code should be work .

filePath += "/" + fileName;

Body:
Have a look at String.endsWith() method

if (fileName.endsWith(".pdf")) {
   // do something
}

Or use the method String.matches()

fileName.matches("\\.(pdf|txt|csv)$")


问:
Cocoa/Mac: JavaScript Core crash on the 38th call
We are developing a Cocoa app for Mac OSX (10.8) which needs to use a JavaScript library (long story why we must use JavaScript).

In a demo application everything seemed to be just fine, but while incorporating the code in our project, we can call the function 37 times without issues and then crashes the 38th time.

To call the JS code we are using Apple's JSWrappers.m (from the JavaScriptCoreHeadStart example).
The line that crashes (with a EXC_BAD_ACCESS) is #149:

```<code>JSObjectCallAsFunction(self.jsContext, jsFunction, NULL, argumentCount, arguments, NULL);
</code>```

As stated above, it crashes on the 38th time -callStringJSFunction:withParameters: is called, no matter what the input is (it crashes with any input string, and the same string works if used in the 37 previous iterations).
The EXC_BAD_ACCESS is not caused by an input variable, as accessing them (such as calling self.jsContext just immediately before that line) works: it is the function call itself that causes the crash.

We have no idea on what it may be causing this issue, and no idea on how to debug more. Does anyone have any hint?
Thanks.

//EDIT

I must correct myself: it doesn't work on the "demo app" too. Even in that case, the code crashes the 38th time we call -callStringJSFunction:withParameters:

//EDIT2

If we re-create the JSWrappers object (and a new JSGlobalContext) every time the function is called, it does not crash anymore. However, this makes the code a lot slower (not surprisingly, as the JS interpreter has to read the script every time - and it's a rather big one).

//EDIT3

Another discovery: building the app in 32 bit makes the code crash. Building in 64 bit, instead, works flawlessly: the JS code is executed without issues any time we wish. This is strange: could this possibly be a bug in the JavaScript Core framework itself?

答:
A bit of an old thread, but somewhat relevant today.

We are still supporting back to iOS 8.2 and found that this issue was cropping up with a number of iOS 8.4 users. Some research shows that is appears to be a bug with iOS versions around this time.

Under synthetic testing, I was calling the same -callWithArguments:@[] function on multiple threads (a new thread in a 100 count for-loop) - this would complete on most test devices, even the 32bit iPod touch, running iOS 9.x. The common denominator was iOS 8.x, even on the iPhone 5S (64bit, 1GB RAM), causing a WTFCrash.

In our production app, the app does call the callWithArguments async and, on occasion, simultaneously on multiple threads. It appears that multiple threads were calling a long-running function at the same time and causing issues. To then stop this, I wrapped the callWithArguments in an

```<code> @synchronized (<#token#>) {
        <#statements#>
    }
</code>```

This seemed to handle this and stopped crashes on all tested iOS versions (8.4, 9.x, 10.3) along with multiple architectures. As these calls were being made on background threads, this had no impact on the UI.

Although this might not be the most graceful approach/ resolution, it seems to have resolved our issue where dozens of users were getting intermittent crashes every day. Having said that, if anyone knows a better way of doing this, please let me know.

tl;dr

Multiple threads calling the same function caused it to bomb out with WTFCrash. Wrapping the call in a @synchronized lock seemed to fix it.

Body:
We are developing a Cocoa app for Mac OSX (10.8) which needs to use a JavaScript library (long story why we must use JavaScript).

In a demo application everything seemed to be just fine, but while incorporating the code in our project, we can call the function 37 times without issues and then crashes the 38th time.

To call the JS code we are using Apple's JSWrappers.m (from the JavaScriptCoreHeadStart example).
The line that crashes (with a EXC_BAD_ACCESS) is #149:

JSObjectCallAsFunction(self.jsContext, jsFunction, NULL, argumentCount, arguments, NULL);

As stated above, it crashes on the 38th time -callStringJSFunction:withParameters: is called, no matter what the input is (it crashes with any input string, and the same string works if used in the 37 previous iterations).
The EXC_BAD_ACCESS is not caused by an input variable, as accessing them (such as calling self.jsContext just immediately before that line) works: it is the function call itself that causes the crash.

We have no idea on what it may be causing this issue, and no idea on how to debug more. Does anyone have any hint?
Thanks.

//EDIT

I must correct myself: it doesn't work on the "demo app" too. Even in that case, the code crashes the 38th time we call -callStringJSFunction:withParameters:

//EDIT2

If we re-create the JSWrappers object (and a new JSGlobalContext) every time the function is called, it does not crash anymore. However, this makes the code a lot slower (not surprisingly, as the JS interpreter has to read the script every time - and it's a rather big one).

//EDIT3

Another discovery: building the app in 32 bit makes the code crash. Building in 64 bit, instead, works flawlessly: the JS code is executed without issues any time we wish. This is strange: could this possibly be a bug in the JavaScript Core framework itself?

Body:
A bit of an old thread, but somewhat relevant today.

We are still supporting back to iOS 8.2 and found that this issue was cropping up with a number of iOS 8.4 users. Some research shows that is appears to be a bug with iOS versions around this time.

Under synthetic testing, I was calling the same -callWithArguments:@[] function on multiple threads (a new thread in a 100 count for-loop) - this would complete on most test devices, even the 32bit iPod touch, running iOS 9.x. The common denominator was iOS 8.x, even on the iPhone 5S (64bit, 1GB RAM), causing a WTFCrash.

In our production app, the app does call the callWithArguments async and, on occasion, simultaneously on multiple threads. It appears that multiple threads were calling a long-running function at the same time and causing issues. To then stop this, I wrapped the callWithArguments in an

 @synchronized (<#token#>) {
        <#statements#>
    }

This seemed to handle this and stopped crashes on all tested iOS versions (8.4, 9.x, 10.3) along with multiple architectures. As these calls were being made on background threads, this had no impact on the UI.

Although this might not be the most graceful approach/ resolution, it seems to have resolved our issue where dozens of users were getting intermittent crashes every day. Having said that, if anyone knows a better way of doing this, please let me know.

tl;dr

Multiple threads calling the same function caused it to bomb out with WTFCrash. Wrapping the call in a @synchronized lock seemed to fix it.


问:
I never know when to make new classes or what to make classes for when I create a new project, and I struggle with organizing my code
Whenever I start a new java project I always run into the same problem and never ever seem to learn: I never know what to make classes of, and what to put where. I have a hard time organizing my code into different classes.

For instance, I am currently writing a program for an experiment. It involves spaceships, some enemy spaceships and some friendly spaceships, a gun to shoot at them, and so on. I thought about creating a Spaceship class, but then wasn't sure if that should really be two classes (one for enemy spaceships and one for friendly spaceships). But then I was thinking that it should be one class of which friendly and enemy spaceships could be instances of spaceships. However, the enemy and friendly spaceships serve different purposes throughout the experiment, so maybe not. I also know that I need to create JLabels of these spaceships, and don't know if these should be variables of instances of the Spaceship class or if they should be something that are created in the main method. And this goes on an on.

Does anyone have any tips for instantly knowing how code should be organized, what classes should be made of, and so on? Because this never seems to get any easier for me no matter how many programs I write.

答:
The answer for your question depends on how well you understand object oriented concepts.
As per your requirement you need to make Spaceship interface or super class.   Make enemy spaceship  and friendly spaceship as child class for Spaceship. Similarly you will need to make separate gun class. Depending upon the functionality you need to create object for each. You can make jLabel classes for you spaceships.

Your main method will be in a class which is Entry to your application. You can have different packages depending upon your classes or layers in your application. You should also aware some design pattern before hand for the solution of common problems arising in application development.