问:
Join two integers into one double
I need to transfer a double value (-47.1235648, for example) using sockets. Since I'll have a lot of platforms, I must convert to network byte order to ensure correct endian of all ends....but this convert doesn't accept double, just integer and short, so I'm 'cutting' my double into two integer to transfer, like this:

```<code>double lat = -47.848945;
int a;
int b;
a = (int)lat;
b = (int)(lat+1);
</code>```

Now, I need to restore this on the other end, but using the minimum computation as possible (I saw some examples using POW, but looks like pow use a lot of resources for this, I'm not sure). Is there any way to join this as simples as possible, like bit manipulating?

答:
It's good that you're considering differences in numeric representation, but your idea for how to deal with this problem just doesn't work reliably.

Let us suppose that every machine involved uses 64-bit IEEE-754 format for its double representation.  (That's already a potential point of failure, but in practice you probably don't have to worry about failures there.)  You seem to postulate that the byte order for machines' doubles will map in a consistent way onto the byte order for their integers, but that is not a safe assumption.  Moreover, even where that assumption holds true, you need exactly the right kind of mapping for your scheme to work, and that is not only not safe to assume, but very plausibly will not be what you actually see.

For the sake of argument, suppose machine A, which features big-endian integers, wants to transfer a double value to machine B, which features little-endian integers.  Suppose further that on B, the byte order for its double representation is the exact reverse of the order on A (which, again, is not safe to assume).  Thus, if on A, the bytes of that double are in the order

```<code>S T U V W X Y Z
</code>```

then we want them to be in order

```<code>Z Y X W V U T S
</code>```

on B.  Your approach is to split the original into a pair (STUV, WXYZ), transfer the pair in a value-preserving manner to get (VUTS, ZYXW), and then put the pair back together to get ... uh oh ...

```<code>V U T S Z Y X W
</code>```

.  Don't imagine fixing that by first swapping the pair.  That doesn't serve your purpose because you must avoid such a swap in the event that the two communicating machines have the same byte order, and you have no way to know from just the 8 bytes whether such a swap is needed.  Thus even if we make simplifying assumptions that we know to be unsafe, your strategy is insufficient for the task.

Alternatives include:

transfer your doubles as strings.

transfer your doubles as integer (significand, scale) pairs.  The frexp() and ldexp() functions can help with encoding and decoding such representations.

transfer an integer-based fixed-point representation of your doubles (the same as the previous option, but with pre-determined scale that is not transferred)

Title: Join two integers into one double

Body:
I need to transfer a double value (-47.1235648, for example) using sockets. Since I'll have a lot of platforms, I must convert to network byte order to ensure correct endian of all ends....but this convert doesn't accept double, just integer and short, so I'm 'cutting' my double into two integer to transfer, like this:

double lat = -47.848945;
int a;
int b;
a = (int)lat;
b = (int)(lat+1);

Now, I need to restore this on the other end, but using the minimum computation as possible (I saw some examples using POW, but looks like pow use a lot of resources for this, I'm not sure). Is there any way to join this as simples as possible, like bit manipulating?

Body:
It's good that you're considering differences in numeric representation, but your idea for how to deal with this problem just doesn't work reliably.

Let us suppose that every machine involved uses 64-bit IEEE-754 format for its double representation.  (That's already a potential point of failure, but in practice you probably don't have to worry about failures there.)  You seem to postulate that the byte order for machines' doubles will map in a consistent way onto the byte order for their integers, but that is not a safe assumption.  Moreover, even where that assumption holds true, you need exactly the right kind of mapping for your scheme to work, and that is not only not safe to assume, but very plausibly will not be what you actually see.

For the sake of argument, suppose machine A, which features big-endian integers, wants to transfer a double value to machine B, which features little-endian integers.  Suppose further that on B, the byte order for its double representation is the exact reverse of the order on A (which, again, is not safe to assume).  Thus, if on A, the bytes of that double are in the order

S T U V W X Y Z

then we want them to be in order

Z Y X W V U T S

on B.  Your approach is to split the original into a pair (STUV, WXYZ), transfer the pair in a value-preserving manner to get (VUTS, ZYXW), and then put the pair back together to get ... uh oh ...

V U T S Z Y X W

.  Don't imagine fixing that by first swapping the pair.  That doesn't serve your purpose because you must avoid such a swap in the event that the two communicating machines have the same byte order, and you have no way to know from just the 8 bytes whether such a swap is needed.  Thus even if we make simplifying assumptions that we know to be unsafe, your strategy is insufficient for the task.

Alternatives include:

transfer your doubles as strings.

transfer your doubles as integer (significand, scale) pairs.  The frexp() and ldexp() functions can help with encoding and decoding such representations.

transfer an integer-based fixed-point representation of your doubles (the same as the previous option, but with pre-determined scale that is not transferred)


来源: stackexchange

问:
Strange button behavior XML selector enabled
I have a button that must be enabled/disabled dynamically. When the switch on the right is checked, the button must be enabled. When the switch is unchecked, the button must be disabled. I've done that using Bindings in MVVMlight.

The default state of the switch is unchecked, so the button must be disabled.

The button has it's own Color State List to be grayed when disabled and blue when enabled.

```<code><?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_enabled="false" android:color="@color/third_light_gray"/>
   <item android:state_enabled="true" android:color="@color/light_blue"/>
</selector>
</code>```

The binding works properly, the button gets enabled/disabled as expected.
However, the default state of the button should be disabled, but it is always enabled by default.

```<code><Button
        android:id="@+id/buttonListProtections"
        ...
        android:enabled="false"
        android:theme="@style/Gohy.Button" />
</code>```

Button style :

```<code>  <style name="Gohy.Button" parent="Widget.AppCompat.Button.Colored">
    <item name="android:textColor">@color/white</item>
    <item name="colorButtonNormal">@drawable/button_color_list</item>
    <item name="android:padding">30dp</item>
    </style>
</code>```

What have I done wrong ?

答:
Change your selector.xml to :

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/light_blue" android:state_enabled="true"/>
<item android:drawable="@color/third_light_gray" android:state_enabled="false"/>
</selector>
</code>```

And modify you style to:

```<code><style name="Gohy.Button" parent="Widget.AppCompat.Button.Colored">
    <item name="android:textColor">@color/colorAccent</item>
    <item name="android:background">@drawable/color_selector</item>
    <item name="android:padding">30dp</item>
</style>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a button that must be enabled/disabled dynamically. When the switch on the right is checked, the button must be enabled. When the switch is unchecked, the button must be disabled. I've done that using Bindings in MVVMlight.

The default state of the switch is unchecked, so the button must be disabled.

The button has it's own Color State List to be grayed when disabled and blue when enabled.

<?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_enabled="false" android:color="@color/third_light_gray"/>
   <item android:state_enabled="true" android:color="@color/light_blue"/>
</selector>

The binding works properly, the button gets enabled/disabled as expected.
However, the default state of the button should be disabled, but it is always enabled by default.

<Button
        android:id="@+id/buttonListProtections"
        ...
        android:enabled="false"
        android:theme="@style/Gohy.Button" />

Button style :

What have I done wrong ?

Body:
Change your selector.xml to :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/light_blue" android:state_enabled="true"/>
<item android:drawable="@color/third_light_gray" android:state_enabled="false"/>
</selector>

And modify you style to:

<style name="Gohy.Button" parent="Widget.AppCompat.Button.Colored">
    <item name="android:textColor">@color/colorAccent</item>
    <item name="android:background">@drawable/color_selector</item>
    <item name="android:padding">30dp</item>
</style>


问:
RestKit, RKEntityMapping trouble with Response Descriptors
Im trying to use RestKit with RKEntityMapping ;(
Help!

```<code>  NSURL *baseURL = [NSURL URLWithString:@"http://api.mymemory.translated.net"];

RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:baseURL];

// Initialize managed object model from bundle
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
// Initialize managed object store
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
objectManager.managedObjectStore = managedObjectStore;

// Complete Core Data stack initialization
[managedObjectStore createPersistentStoreCoordinator];
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"MyArticlesDB.sqlite"];
NSString *seedPath = [[NSBundle mainBundle] pathForResource:@"RKSeedDatabase" ofType:@"sqlite"];
NSError *error;

NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:seedPath withConfiguration:nil options:nil error:&error];
NSAssert(persistentStore, @"Failed to add persistent store with error: %@", error);

// Create the managed object contexts
[managedObjectStore createManagedObjectContexts];

// Configure a managed object cache to ensure we do not create duplicate objects
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];

RKEntityMapping *matchMapping = [RKEntityMapping mappingForEntityForName:@"Match" inManagedObjectStore:managedObjectStore];
[matchMapping addAttributeMappingsFromDictionary:@{@"id"    :@"id",
                                                   @"segment"   :@"segment",
                                                   @"trnaslation"   :@"translation",
                                                   @"quality"       :@"quality",
                                                   @"reference"     :@"reference",
                                                   @"usage-count"   :@"usage_count",
                                                   @"subject"       :@"subject",
                                                   @"created-by"    :@"MateCat",
                                                   @"last-updated-by"   :@"last_updated_by",
                                                   @"create-date"       :@"create_date",
                                                   @"last-update-date"  :@"last_update_date",
                                                   @"tm_properties"     :@"tm_properties",
                                                   @"match"         :@"match"}];

RKEntityMapping *translationMapping = [RKEntityMapping mappingForEntityForName:@"Translation" inManagedObjectStore:managedObjectStore];
[translationMapping addAttributeMappingsFromDictionary:@{@"responseData.translatedText"     :@"translatedText",
                                                         @"responseData.match"              :@"match",
                                                         @"responseDetails"                 :@"responseDetails",
                                                         @"responseStatus"                  :@"responseStatus",
                                                         @"responseId"                      :@"responseId"}];

      RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:translationMapping method:RKRequestMethodGET pathPattern:@"/" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:responseDescriptor];
</code>```

json  here : http://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en%7Cru

error :

Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No response descriptors match the response loaded." UserInfo={NSLocalizedFailureReason=A 200 response was loaded from the URL 'http://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en%7Cru', which failed to match all (0) response descriptors:, NSErrorFailingURLStringKey=http://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en%7Cru, NSErrorFailingURLKey=http://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en%7Cru, NSUnderlyingError=0x1700562f0 {Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No mappable object representations were found at the key paths searched." UserInfo={NSLocalizedDescription=No mappable object representations were found at the key paths searched., NSLocalizedFailureReason=The mapping operation was unable to find any nested object representations at the key paths searched:
  The representation inputted to the mapper was found to contain nested object representations at the following key paths: matches, responderId, responseData, responseDetails, responseStatus
  This likely indicates that you have misconfigured the key paths for your mappings., keyPath=null, DetailedErrors=(
  )}}, keyPath=null, NSLocalizedDescription=No response descriptors match the response loaded.}

答:
I forgot to add relationships. This helped me.</p>

```<code>RKRelationshipMapping *res = [RKRelationshipMapping relationshipMappingFromKeyPath:@"responseData" toKeyPath:@"responseData" withMapping:responseMapping];

 RKRelationshipMapping *matchRelation = [RKRelationshipMapping relationshipMappingFromKeyPath:@"matches" toKeyPath:@"matches" withMapping:matchMapping];

[globalMappig addPropertyMapping:matchRelation];
[globalMappig addPropertyMapping:responseRelation];
</code>```

Body:
Im trying to use RestKit with RKEntityMapping ;(
Help!

  NSURL *baseURL = [NSURL URLWithString:@"http://api.mymemory.translated.net"];

RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:baseURL];

// Initialize managed object model from bundle
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
// Initialize managed object store
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
objectManager.managedObjectStore = managedObjectStore;

// Complete Core Data stack initialization
[managedObjectStore createPersistentStoreCoordinator];
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"MyArticlesDB.sqlite"];
NSString *seedPath = [[NSBundle mainBundle] pathForResource:@"RKSeedDatabase" ofType:@"sqlite"];
NSError *error;

NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:seedPath withConfiguration:nil options:nil error:&error];
NSAssert(persistentStore, @"Failed to add persistent store with error: %@", error);

// Create the managed object contexts
[managedObjectStore createManagedObjectContexts];

// Configure a managed object cache to ensure we do not create duplicate objects
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];

RKEntityMapping *matchMapping = [RKEntityMapping mappingForEntityForName:@"Match" inManagedObjectStore:managedObjectStore];
[matchMapping addAttributeMappingsFromDictionary:@{@"id"    :@"id",
                                                   @"segment"   :@"segment",
                                                   @"trnaslation"   :@"translation",
                                                   @"quality"       :@"quality",
                                                   @"reference"     :@"reference",
                                                   @"usage-count"   :@"usage_count",
                                                   @"subject"       :@"subject",
                                                   @"created-by"    :@"MateCat",
                                                   @"last-updated-by"   :@"last_updated_by",
                                                   @"create-date"       :@"create_date",
                                                   @"last-update-date"  :@"last_update_date",
                                                   @"tm_properties"     :@"tm_properties",
                                                   @"match"         :@"match"}];

RKEntityMapping *translationMapping = [RKEntityMapping mappingForEntityForName:@"Translation" inManagedObjectStore:managedObjectStore];
[translationMapping addAttributeMappingsFromDictionary:@{@"responseData.translatedText"     :@"translatedText",
                                                         @"responseData.match"              :@"match",
                                                         @"responseDetails"                 :@"responseDetails",
                                                         @"responseStatus"                  :@"responseStatus",
                                                         @"responseId"                      :@"responseId"}];

      RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:translationMapping method:RKRequestMethodGET pathPattern:@"/" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:responseDescriptor];

json  here : http://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en%7Cru

error :

Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No response descriptors match the response loaded." UserInfo={NSLocalizedFailureReason=A 200 response was loaded from the URL 'http://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en%7Cru', which failed to match all (0) response descriptors:, NSErrorFailingURLStringKey=http://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en%7Cru, NSErrorFailingURLKey=http://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en%7Cru, NSUnderlyingError=0x1700562f0 {Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No mappable object representations were found at the key paths searched." UserInfo={NSLocalizedDescription=No mappable object representations were found at the key paths searched., NSLocalizedFailureReason=The mapping operation was unable to find any nested object representations at the key paths searched:
  The representation inputted to the mapper was found to contain nested object representations at the following key paths: matches, responderId, responseData, responseDetails, responseStatus
  This likely indicates that you have misconfigured the key paths for your mappings., keyPath=null, DetailedErrors=(
  )}}, keyPath=null, NSLocalizedDescription=No response descriptors match the response loaded.}

Body:
I forgot to add relationships. This helped me.

RKRelationshipMapping *res = [RKRelationshipMapping relationshipMappingFromKeyPath:@"responseData" toKeyPath:@"responseData" withMapping:responseMapping];

 RKRelationshipMapping *matchRelation = [RKRelationshipMapping relationshipMappingFromKeyPath:@"matches" toKeyPath:@"matches" withMapping:matchMapping];

[globalMappig addPropertyMapping:matchRelation];
[globalMappig addPropertyMapping:responseRelation];


问:
Deleting an object declared on the stack
I wanted to know what happens if we delete an object declared on the stack, two times. In order to test this I've written this simple program:

```<code>#include <iostream>
using namespace std;

class A {
public:
    A() {}
    virtual ~A() {
        cout << "test" << endl;
    }
};

int main()
{
    A a;
    a.~A();
}
</code>```

I was actually expecting a segmentation fault, as I'm deleting A once explicitly in the code, and it will be deleted again when it goes out of scope, however suprisingly the program produces the following ouput:

"test"

    "test"

Can anybody explain why this code is working??

答:
As the name says, a is a "variable with automatic lifetime" which means you can't end it's lifetime prematurely yourself. It is bound to the scope it was created in. You're just manually calling the destructor which is just another method that prints something. Then it's called again automatically by the runtime on actual destruction and end of lifetime. You can somewhat control the lifetime of an automatically managed object by defining the scope of it:

```<code>int main()
{
    {
      A a;
    } // 'a' is destroyed here.
} // instead of here.
</code>```

Body:
I wanted to know what happens if we delete an object declared on the stack, two times. In order to test this I've written this simple program:

#include <iostream>
using namespace std;

class A {
public:
    A() {}
    virtual ~A() {
        cout << "test" << endl;
    }
};

int main()
{
    A a;
    a.~A();
}

I was actually expecting a segmentation fault, as I'm deleting A once explicitly in the code, and it will be deleted again when it goes out of scope, however suprisingly the program produces the following ouput:

"test"

    "test"

Can anybody explain why this code is working??

Body:
As the name says, a is a "variable with automatic lifetime" which means you can't end it's lifetime prematurely yourself. It is bound to the scope it was created in. You're just manually calling the destructor which is just another method that prints something. Then it's called again automatically by the runtime on actual destruction and end of lifetime. You can somewhat control the lifetime of an automatically managed object by defining the scope of it:

int main()
{
    {
      A a;
    } // 'a' is destroyed here.
} // instead of here.


问:
REST url @RequestParam encoding cannot be decoded to proper format (Spring MVC)
I'm writing a Rest controller with Spring MVC, currently I have just one endpoint with one parameter requesting:

```<code>@RequestMapping(value = "/city", method = RequestMethod.GET)
@ResponseBody
public List<String> getCities(@RequestParam String name)  {
    ...
}
</code>```

I'm working with Hungarian city names which can have some special characters (á,é,ő,ű,ú...) - they all come from the database.

When I call the rest endpoint with this:

```<code>/serviceoffer/region/city?name=Borsod-Aba%C3%BAj-Zempl%C3%A9n
</code>```

I get this string into the name:

```<code>Borsod-AbaÃºj-ZemplÃ©n
</code>```

but I should get this:

```<code>Borsod-Abaúj-Zemplén
</code>```

I don't know if it's an encoding/decoding issue, but I tried to decode it without any success.

What could be the solution?
Many thanks!

答:
Since you use Tomcat <= 7 and GET requests, you should change the URIEncoding from the default ISO8859-1 to UTF-8. Change your HTTP connector settings in config/server.xml:

```<code><Connector ... URIEncoding="UTF-8" />
</code>```

Body:
I'm writing a Rest controller with Spring MVC, currently I have just one endpoint with one parameter requesting:

@RequestMapping(value = "/city", method = RequestMethod.GET)
@ResponseBody
public List<String> getCities(@RequestParam String name)  {
    ...
}

I'm working with Hungarian city names which can have some special characters (á,é,ő,ű,ú...) - they all come from the database.

When I call the rest endpoint with this:

/serviceoffer/region/city?name=Borsod-Aba%C3%BAj-Zempl%C3%A9n

I get this string into the name:

Borsod-AbaÃºj-ZemplÃ©n

but I should get this:

Borsod-Abaúj-Zemplén

I don't know if it's an encoding/decoding issue, but I tried to decode it without any success.

What could be the solution?
Many thanks!

Body:
Since you use Tomcat <= 7 and GET requests, you should change the URIEncoding from the default ISO8859-1 to UTF-8. Change your HTTP connector settings in config/server.xml:

<Connector ... URIEncoding="UTF-8" />


问:
Javascript - Read value of a JSON property, if that key doesn't exist return null, in a single line
Let me give a python analogy of what I am looking for:

```<code>fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)
</code>```

prints:
    3 None

Now in Javascript, with a similar JS object, we can use hasOwnProperty(key) in a if block

```<code>var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);
</code>```

gives:
    3 null

Is there a better way? Something on the lines of python's get function?

答:
If you want to return it from a function, in a single line, you can use a ternary:</p>

```<code>return fruits_obj.hasOwnProperty("orange") ? fruits_obj['orange'] : null;
</code>```

Body:
Let me give a python analogy of what I am looking for:

fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)

prints:
    3 None

Now in Javascript, with a similar JS object, we can use hasOwnProperty(key) in a if block

var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);

gives:
    3 null

Is there a better way? Something on the lines of python's get function?

Body:
If you want to return it from a function, in a single line, you can use a ternary:

return fruits_obj.hasOwnProperty("orange") ? fruits_obj['orange'] : null;


问:
Send bytes with Jade ACLMessage in Java
I'm trying to send a byte array with the Jade ACL message. Basically I want to do what this guy does: Decryption Error bad padding But I don't want to convert the cipher into a string but send the bytes directly. There's a function named setByteSequence which I could/should use but when I run my code, it throws an error saying that base64 is not supported and refers to the documentation which doesn't say anything about how to use it. Just that it's supported. I'm using the jade.jar from the Jade Website.

Sender:

```<code>public class Alice extends Agent {
private static final long serialVersionUID = 725326296709140752L;

protected void setup() {
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);

AID recipient1 = new AID();
recipient1.setName(String.format("Bob@%s:1099/JADE", Main.IPBob));
recipient1.addAddresses(String.format("http://%s:7778/acc", Main.IPBob));

msg.addReceiver(recipient1);
//  byte[] mBytes = "bla".getBytes(); // this doesn't work
byte[] mBytes = Base64.getEncoder().encode("bla".getBytes()); // neither does this
msg.setByteSequenceContent(mBytes);
send(msg);
     }
}
</code>```

Receiver:

```<code>public class Bob extends Agent {
private static final long serialVersionUID = 2028682217881039710L;

protected void setup() {
    addBehaviour(new CyclicBehaviour(this) {

        private static final long serialVersionUID = 1L;

        public void action() {
            ACLMessage msg = myAgent.receive();

            if (msg != null) {
                System.out.println(String.format("Got Message %s", DatatypeConverter.printBase64Binary(msg.getByteSequenceContent())));
            } else {
                block();
            }
        }
    });
    }
}
</code>```

Main:

```<code>public class Main {
public static final String IPAlice = "...";
public static final String IPBob = "...";

public static void main(String[] args) {
    int port = 1099;
    int mtpPort = 7778;
    String hostIP = "...";
    Profile profile = new ProfileImpl(hostIP, port, null, true);
    profile.setParameter(Profile.MTPS, "jade.mtp.http.MessageTransportProtocol(http://"+hostIP+":"+mtpPort+"/acc)");

    Runtime runtime = Runtime.instance();

    AgentContainer container = runtime.createMainContainer(profile);
    try {
//          AgentController bob = container.createNewAgent("Bob", agent.Bob.class.getName(), null);
//          bob.start();

        AgentController alice = container.createNewAgent("Alice", agent.Alice.class.getName(), null);
        alice.start();

    } catch (StaleProxyException e) {
        e.printStackTrace();
    }
}
}
}
</code>```

The base64 example doesn't show anything either. It just sets an object as the message's content and says that it will be base64-encoded...Might be that I'm missing the obvious but I can't see it. I'm grateful for help.

答:
Here is how you sender Agent should look like.

/////////////////////////////////    SENDER ///////////////////////////////

```<code>                  Path path = Paths.get("Address of file");

                    byte[] data = null;
                    try {
                        data = Files.readAllBytes(path);
                    } catch (IOException ex) {
                        Logger.getLogger(DataAgent.class.getName()).log(Level.SEVERE, null, ex);
                    }

ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.addReceiver(<receiver-aid>);
msg.addReceiver(new AID("Agent-name", AID.ISLOCALNAME));

msg.setByteSequenceContent(data);
msg.addUserDefinedParameter("file-name", filename);
send(msg);
 System.out.println("Message sent");
</code>```

Now  This is how your Receiver Agent Should look like:

////////////////////// RECEIVER //////////////////////

```<code>ACLMessage msg = receive();

System.out.println("Received msg is "+msg.getContent());

String fileName = msg.getUserDefinedParameter("file-name");
File f = new File(fileName);

byte[] fileContent = msg.getByteSequenceContent();

//write to file
</code>```

Title: Send bytes with Jade ACLMessage in Java

Body:
I'm trying to send a byte array with the Jade ACL message. Basically I want to do what this guy does: Decryption Error bad padding But I don't want to convert the cipher into a string but send the bytes directly. There's a function named setByteSequence which I could/should use but when I run my code, it throws an error saying that base64 is not supported and refers to the documentation which doesn't say anything about how to use it. Just that it's supported. I'm using the jade.jar from the Jade Website.

Sender:

public class Alice extends Agent {
private static final long serialVersionUID = 725326296709140752L;

protected void setup() {
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);

AID recipient1 = new AID();
recipient1.setName(String.format("Bob@%s:1099/JADE", Main.IPBob));
recipient1.addAddresses(String.format("http://%s:7778/acc", Main.IPBob));

msg.addReceiver(recipient1);
//  byte[] mBytes = "bla".getBytes(); // this doesn't work
byte[] mBytes = Base64.getEncoder().encode("bla".getBytes()); // neither does this
msg.setByteSequenceContent(mBytes);
send(msg);
     }
}

Receiver:

public class Bob extends Agent {
private static final long serialVersionUID = 2028682217881039710L;

protected void setup() {
    addBehaviour(new CyclicBehaviour(this) {

        private static final long serialVersionUID = 1L;

        public void action() {
            ACLMessage msg = myAgent.receive();

            if (msg != null) {
                System.out.println(String.format("Got Message %s", DatatypeConverter.printBase64Binary(msg.getByteSequenceContent())));
            } else {
                block();
            }
        }
    });
    }
}

Main:

public class Main {
public static final String IPAlice = "...";
public static final String IPBob = "...";

public static void main(String[] args) {
    int port = 1099;
    int mtpPort = 7778;
    String hostIP = "...";
    Profile profile = new ProfileImpl(hostIP, port, null, true);
    profile.setParameter(Profile.MTPS, "jade.mtp.http.MessageTransportProtocol(http://"+hostIP+":"+mtpPort+"/acc)");

    Runtime runtime = Runtime.instance();

    AgentContainer container = runtime.createMainContainer(profile);
    try {
//          AgentController bob = container.createNewAgent("Bob", agent.Bob.class.getName(), null);
//          bob.start();

        AgentController alice = container.createNewAgent("Alice", agent.Alice.class.getName(), null);
        alice.start();

    } catch (StaleProxyException e) {
        e.printStackTrace();
    }
}
}
}

The base64 example doesn't show anything either. It just sets an object as the message's content and says that it will be base64-encoded...Might be that I'm missing the obvious but I can't see it. I'm grateful for help.

Body:
Here is how you sender Agent should look like.

/////////////////////////////////    SENDER ///////////////////////////////

                  Path path = Paths.get("Address of file");

                    byte[] data = null;
                    try {
                        data = Files.readAllBytes(path);
                    } catch (IOException ex) {
                        Logger.getLogger(DataAgent.class.getName()).log(Level.SEVERE, null, ex);
                    }

ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.addReceiver(<receiver-aid>);
msg.addReceiver(new AID("Agent-name", AID.ISLOCALNAME));

msg.setByteSequenceContent(data);
msg.addUserDefinedParameter("file-name", filename);
send(msg);
 System.out.println("Message sent");

Now  This is how your Receiver Agent Should look like:

////////////////////// RECEIVER //////////////////////

ACLMessage msg = receive();

System.out.println("Received msg is "+msg.getContent());

String fileName = msg.getUserDefinedParameter("file-name");
File f = new File(fileName);

byte[] fileContent = msg.getByteSequenceContent();

//write to file


问:
How to copy data from one column to another at the same datatable in c#
I have a datatable filled with information from an excel file. I have more than four columns but to bring an example I'm writing just four of them. I have to write a program in which if the value of the cell in the column C is 0, then I have to copy column B to column A. If the value of the cell in column C is > 0 then i have to copy the column B to A and should add another row in which i have to copy the value of the column C to A.

What i have till now is

```<code>    for (int r = 2; r <= ws.UsedRange.Rows.Count; r++)
    {    if (ws.UsedRange.Cells[r, 3].Text == "0")
            {
                DataRow row = dt.NewRow();

                for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
            {
                string cell = ws.Cells[r, c].Text;
                row[c - 1] = cell;
          }
     }
</code>```

So my questions are:

How can i copy a column to another in the same datatable? Copy B to A.
How can i add another row and copy the value of C to A only for that row?

Here is the full code:

```<code>    public DataTable ReadExcel2(string file)
    {
        ExcelI.Application app = new ExcelI.Application(); //create an excel instance
        ExcelI.Workbook wb = app.Workbooks.Open(file, ReadOnly: true); //open a file
        ExcelI.Worksheet ws = wb.Worksheets[1]; //choose a sheet. The firt one

        var rng = ws.UsedRange;
        //takes the index of the columns that are going to be filtered
        int service = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Service");
        int status = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Status");
        int code = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Code");
        DataTable dt = new DataTable();
        dt.Columns.Add("A", typeof(string));
        for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
        {
            string colName = ws.Cells[1, c].Text;
            int i = 2;
            while (dt.Columns.Contains(colName))
            {
                colName = ws.Cells[1, c].Text + "{" + i.ToString() + "}";
                i++;
            }
            dt.Columns.Add(colName);
        }
        //do a loop to delete the rows that we dont need
        for (int r = 2; r <= ws.UsedRange.Rows.Count; r++)
        {
                if (ws.UsedRange.Cells[r, 3].Text == "0")
                {
                    DataRow row = dt.NewRow();

                    for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
                    {
                        string cell = ws.Cells[r, c].Text;
                        row[c - 1] = cell;
                    }
                    dt.Rows.Add(row);
                    row["A"] = row["C"];
                }
        }

//Close the file
        wb.Close();
        //release the excel objects from use
        Marshal.ReleaseComObject(wb);
        Marshal.ReleaseComObject(ws);
        //take the id of excel process
        int pid = app.PID();
        app.Quit();
        StartProc("taskkill", $"/f /pid {pid}");
        return dt;
    }
</code>```

答:
To add row use dt.Rows.Add(row);, about "copy the column B to A" you mean copy value , just assign  row[0] = row[2];, by the way , your example missing a bracket.

I think you should review your code according to conditions in  your question, and you can do it yourself as well. Just pay attention to condition you wrote in question and conditional operator you checked in the code.

Body:
I have a datatable filled with information from an excel file. I have more than four columns but to bring an example I'm writing just four of them. I have to write a program in which if the value of the cell in the column C is 0, then I have to copy column B to column A. If the value of the cell in column C is > 0 then i have to copy the column B to A and should add another row in which i have to copy the value of the column C to A.

What i have till now is

    for (int r = 2; r <= ws.UsedRange.Rows.Count; r++)
    {    if (ws.UsedRange.Cells[r, 3].Text == "0")
            {
                DataRow row = dt.NewRow();

                for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
            {
                string cell = ws.Cells[r, c].Text;
                row[c - 1] = cell;
          }
     }

So my questions are:

How can i copy a column to another in the same datatable? Copy B to A.
How can i add another row and copy the value of C to A only for that row?

Here is the full code:

    public DataTable ReadExcel2(string file)
    {
        ExcelI.Application app = new ExcelI.Application(); //create an excel instance
        ExcelI.Workbook wb = app.Workbooks.Open(file, ReadOnly: true); //open a file
        ExcelI.Worksheet ws = wb.Worksheets[1]; //choose a sheet. The firt one

        var rng = ws.UsedRange;
        //takes the index of the columns that are going to be filtered
        int service = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Service");
        int status = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Status");
        int code = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Code");
        DataTable dt = new DataTable();
        dt.Columns.Add("A", typeof(string));
        for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
        {
            string colName = ws.Cells[1, c].Text;
            int i = 2;
            while (dt.Columns.Contains(colName))
            {
                colName = ws.Cells[1, c].Text + "{" + i.ToString() + "}";
                i++;
            }
            dt.Columns.Add(colName);
        }
        //do a loop to delete the rows that we dont need
        for (int r = 2; r <= ws.UsedRange.Rows.Count; r++)
        {
                if (ws.UsedRange.Cells[r, 3].Text == "0")
                {
                    DataRow row = dt.NewRow();

                    for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
                    {
                        string cell = ws.Cells[r, c].Text;
                        row[c - 1] = cell;
                    }
                    dt.Rows.Add(row);
                    row["A"] = row["C"];
                }
        }

//Close the file
        wb.Close();
        //release the excel objects from use
        Marshal.ReleaseComObject(wb);
        Marshal.ReleaseComObject(ws);
        //take the id of excel process
        int pid = app.PID();
        app.Quit();
        StartProc("taskkill", $"/f /pid {pid}");
        return dt;
    }


问:
How to get value of "extract" key from a Wikipedia JSON response
I want read the value of "extract" key in a Wikipedia JSON response in Python3. The URL I'm testing with is https://en.wikipedia.org/w/api.php?action=query&titles=San%20Francisco&prop=extracts&format=json.

The response looks like this

```<code>{
  "batchcomplete": "",
  "query": {
    "pages": {
      "49728": {
        "pageid": 49728,
        "ns": 0,
        "title": "San Francisco",
        "extract": "<p><b>San Francisco</b></p>"
      }
    }
  }
}
</code>```

I removed the content as it was a lot.

Now the problem is how do I read the page number programmatically. The page number changes with different searches. I definitely don't want to hard code the page number. What do I put instead of page number

```<code>content = response.query.pages.<page number>.extract
</code>```

Is there any way to extract the key from the pages tag and then proceed to get it's value?

答:
I found that I can solve this problem by using Python's .keys() method. I did this.</p>

```<code>key = list(response['query']['pages'].keys())
print(response['query']['pages'][key[0]]['extract'])
</code>```

Body:
I want read the value of "extract" key in a Wikipedia JSON response in Python3. The URL I'm testing with is https://en.wikipedia.org/w/api.php?action=query&titles=San%20Francisco&prop=extracts&format=json.

The response looks like this

{
  "batchcomplete": "",
  "query": {
    "pages": {
      "49728": {
        "pageid": 49728,
        "ns": 0,
        "title": "San Francisco",
        "extract": "
San Francisco
"
      }
    }
  }
}

I removed the content as it was a lot.

Now the problem is how do I read the page number programmatically. The page number changes with different searches. I definitely don't want to hard code the page number. What do I put instead of page number

content = response.query.pages.<page number>.extract

Is there any way to extract the key from the pages tag and then proceed to get it's value?

Body:
I found that I can solve this problem by using Python's .keys() method. I did this.

key = list(response['query']['pages'].keys())
print(response['query']['pages'][key[0]]['extract'])


问:
How to add dynamicly linked and created pages in wordpress?
Since I had some comments on the formulation of my question, I decided to rewrite it completely. And also, I understand a little bit more about wordpress so it should make more sense now.

So, let's start with what I'm trying to accomplish by using a simple example:

Goal:

Make a search engine for some products and link to them using a database to generate the information.

Result:

```<code>http://my.site.url/wordpress/<plugin-name>  <-- The page with the "search" and "search result
http://my.site.url/wordpress/<plugin-name>/products/<product_name>  <-- When click on a search result
</code>```

Part 1:

I want to make a plugin with the name "plugin-name" Right now, I put my code in

```<code>http://my.site.url/wordpress/wp-content/plugins/<plugin-name>
</code>```

On the activate, I create some tables with some data. Since there is no page yet, I create 1 on the fly using the API call 'wp_insert_post'. I give the name and slug "myPlugin".

So, when I go on the main site, I can see my newly created page "myPlugin". But right now, there is no content attached to it. To do so, from what I understand, I need to create a page in my plug-in directory named "myPlugin.php".

```<code>http://my.site.url/wordpress/wp-content/plugins/<plugin-name>/myPlugin.php
</code>```

So, how do I link the page I created manually and the source file in the plugin directory?

Part 2

When clicking on a link in the search result, I would like to have a page "product.php" and display its information. So, is it possible to create a "temporary url" for the result using sub pages (see result at the beginning)? And if possible, how can we achieve that?

Thanks in advance and I hope it's clearer.

答:
u can find how to create plugin from
http://ditio.net/2007/08/09/how-to-create-wordpress-plugin-from-a-scratch/

in plugin write function for search(as per u r logic) fetch result

create a custom page refer video from www.wordpressmax.com/customize-wordpress/custom-page

in custom pages template in between get_header(); and get_footer(); call search function and display records.

Thats it.

ContentLicense: CC BY-SA 2.5

Body:
Since I had some comments on the formulation of my question, I decided to rewrite it completely. And also, I understand a little bit more about wordpress so it should make more sense now.

So, let's start with what I'm trying to accomplish by using a simple example:

Goal:

Make a search engine for some products and link to them using a database to generate the information.

Result:

http://my.site.url/wordpress/<plugin-name>  <-- The page with the "search" and "search result
http://my.site.url/wordpress/<plugin-name>/products/<product_name>  <-- When click on a search result

Part 1:

I want to make a plugin with the name "plugin-name" Right now, I put my code in

http://my.site.url/wordpress/wp-content/plugins/<plugin-name>

On the activate, I create some tables with some data. Since there is no page yet, I create 1 on the fly using the API call 'wp_insert_post'. I give the name and slug "myPlugin".

So, when I go on the main site, I can see my newly created page "myPlugin". But right now, there is no content attached to it. To do so, from what I understand, I need to create a page in my plug-in directory named "myPlugin.php".

http://my.site.url/wordpress/wp-content/plugins/<plugin-name>/myPlugin.php

So, how do I link the page I created manually and the source file in the plugin directory?

Part 2

When clicking on a link in the search result, I would like to have a page "product.php" and display its information. So, is it possible to create a "temporary url" for the result using sub pages (see result at the beginning)? And if possible, how can we achieve that?

Thanks in advance and I hope it's clearer.


问:
How to render Swig templates with Express 4?
I am not able to use Swig templates with Express for Node.
I get the following error :

```<code>Error: Failed to lookup view "index" in views directory
</code>```

The Swig templates are not being compiled into .html files

My code is below :

```<code>var express = require('express');
var cons = require('consolidate');
var swig = require('swig');
var app = express();

//Set template engine
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views')

// Disable Express's and Swig Cache
app.set('view cache', false);
swig.setDefaults({ cache: false });

app.get('/', function(req, res){
  res.render('index', {'title': 'Design'});
});

app.listen(3000);
</code>```

答:
for latest version of swig we need to include swig package which needed to installed through package manager or package.json file

var express = require('express');

var swig = require('swig');

var app = express();

// Here we need to set up and engine as per latest version of swig
  //for latest version of swig we need to include swig package which                //needed to installed through package manager or package.json file

app.engine('swig', swig.renderFile);

app.set('view engine', 'swig');

app.set('views', path.join(__dirname, 'views'));

app.set('view cache', false);

swig.setDefaults({ cache: false });
  //Here we are setting cache defaults to false.

`

Body:
I am not able to use Swig templates with Express for Node.
I get the following error :

Error: Failed to lookup view "index" in views directory

The Swig templates are not being compiled into .html files

My code is below :

var express = require('express');
var cons = require('consolidate');
var swig = require('swig');
var app = express();

//Set template engine
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views')

// Disable Express's and Swig Cache
app.set('view cache', false);
swig.setDefaults({ cache: false });

app.get('/', function(req, res){
  res.render('index', {'title': 'Design'});
});

app.listen(3000);


问:
json_encode format for array
I can't find the answer to this anywhere online, partly because I wouldn't know how to search for this. The problem is the format of json_encode for the following array:

```<code>array(1) {
  [1441065600]=>
  array(4) {
    ["high"]=>
    float(1)
    ["low"]=>
    float(1)
    ["close"]=>
    float(1.28)
    ["open"]=>
    float(1.35)
  }
}
</code>```

The ouput in json_encode() is:

```<code>{"1441065600":{"high":1,"low":1,"close":1.28,"open":1.35}
</code>```

However I am looking to output as:

```<code>[
 [1441065600,1,1,1.28,1.35]
]
</code>```

Can anyone hint at the right approach to doing this?

Can't find my solution in http://php.net/manual/en/function.json-encode.php as I need to group by timestamp as a key.

答:
@Nick simple try this logic you have to format the array first and then encode that array like below:

```<code><?php
$arr = array(
            "1441065600" => array("high" => (float)1, "low" => (float)1, "close" => (float)1.28, "open" => (float)1.35)

            );
$newArr = array();
foreach ($arr as $key => $value) {
    $newArr[] = $key;
    foreach ($value as $key1 => $value1){
        $newArr[] = $value1;
    }
}
echo json_encode(array($newArr));
</code>```

output:

[[1441065600,1,1,1.28,1.35]]

please check it here https://eval.in/764582 your desired output

Title: json_encode format for array

Body:
I can't find the answer to this anywhere online, partly because I wouldn't know how to search for this. The problem is the format of json_encode for the following array:

array(1) {
  [1441065600]=>
  array(4) {
    ["high"]=>
    float(1)
    ["low"]=>
    float(1)
    ["close"]=>
    float(1.28)
    ["open"]=>
    float(1.35)
  }
}

The ouput in json_encode() is:

{"1441065600":{"high":1,"low":1,"close":1.28,"open":1.35}

However I am looking to output as:

[
 [1441065600,1,1,1.28,1.35]
]

Can anyone hint at the right approach to doing this?

Can't find my solution in http://php.net/manual/en/function.json-encode.php as I need to group by timestamp as a key.

Body:
@Nick simple try this logic you have to format the array first and then encode that array like below:

<?php
$arr = array(
            "1441065600" => array("high" => (float)1, "low" => (float)1, "close" => (float)1.28, "open" => (float)1.35)

            );
$newArr = array();
foreach ($arr as $key => $value) {
    $newArr[] = $key;
    foreach ($value as $key1 => $value1){
        $newArr[] = $value1;
    }
}
echo json_encode(array($newArr));

output:

[[1441065600,1,1,1.28,1.35]]

please check it here https://eval.in/764582 your desired output


问:
How to add class on hover using jquery
I have anchor tag with data-value attribute whenever user clicks on the hyperlink I am storing data-value in local storage I want to add active class to the hyperlink which matches data-value with local storage.

HTML code,

```<code><div class="flItems"><a class="category_filter" data-value="Fitted bed Sheet " href="http://192.168.1.156/eles/bed-linen/fitted-bed-sheet"> Fitted bed Sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Flat bed sheet " href="http://192.168.1.156/eles/bed-linen/flat-bed-sheet"> Flat bed sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Full bed sheets  " href="http://192.168.1.156/eles/bed-linen/full-bed-sheets"> Full bed sheets   </a> </div>
<div class="flItems"><a class="category_filter" data-value="Twin bed sheet " href="http://192.168.1.156/eles/bed-linen/twin-bed-sheet"> Twin bed sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Twinxl bed sheets  " href="http://192.168.1.156/eles/bed-linen/twinxl-bed-sheets"> Twinxl bed sheets   </a> </div>
<div class="flItems"><a class="category_filter" data-value="Queen bed sheet " href="http://192.168.1.156/eles/bed-linen/queen-bed-sheet"> Queen bed sheet  </a> </div>
<div class="flItems"><a class="category_filter" data-value="King bed sheets " href="http://192.168.1.156/eles/bed-linen/king-bed-sheets"> King bed sheets  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Cal king bed sheets " href="http://192.168.1.156/eles/bed-linen/cal-king-bed-sheets"> Cal king bed sheets  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Duvet covers " href="http://192.168.1.156/eles/bed-linen/duvet-covers"> Duvet covers  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Bed skirts " href="http://192.168.1.156/eles/bed-linen/bed-skirts"> Bed skirts  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Standard Pillow cases " href="http://192.168.1.156/eles/bed-linen/standard-pillow-cases"> Standard Pillow cases  </a> </div>
<div class="flItems"><a class="category_filter" data-value="King Pillow cases " href="http://192.168.1.156/eles/bed-linen/king-pillow-cases"> King Pillow cases  </a> </div>
<div class="flItems"><a class="category_filter" data-value="Pillow shells " href="http://192.168.1.156/eles/bed-linen/pillow-shells"> Pillow shells  </a> </div>
</code>```

Jquery Code,

```<code>$(".categories_fltrs").hover(function(){
    //alert("adhfdba");
        var clickedvalue = localStorage.getItem("clickedLink");
        //alert(clickedvalue);
        if(clickedvalue)
        {
            //alert("fgjdf");
            //$("data-value='" + clickedvalue + "']").addClass("active");
             $('a[data-value = '+clickedvalue+'].category_filter').addClass('active');
        }
});
</code>```

答:
something like this might work:

```<code>$(".category_filter").hover(function(){
    //alert("adhfdba");
    var clickedvalue = localStorage.getItem("clickedLink");
    //alert(clickedvalue);
    if(clickedvalue && clickedvalue == $(this).attr("data-value"))
    {
        //alert("fgjdf");
        //$("data-value='" + clickedvalue + "']").addClass("active");
        $(this).addClass("active");
    }
});
</code>```

Just make sure you also remove the active class accordingly

Title: How to add class on hover using jquery

Body:
I have anchor tag with data-value attribute whenever user clicks on the hyperlink I am storing data-value in local storage I want to add active class to the hyperlink which matches data-value with local storage.

HTML code,

 Fitted bed Sheet

 Flat bed sheet

 Full bed sheets

 Twin bed sheet

 Twinxl bed sheets

 Queen bed sheet

 King bed sheets

 Cal king bed sheets

 Duvet covers

 Bed skirts

 Standard Pillow cases

 King Pillow cases

 Pillow shells

Jquery Code,

$(".categories_fltrs").hover(function(){
    //alert("adhfdba");
        var clickedvalue = localStorage.getItem("clickedLink");
        //alert(clickedvalue);
        if(clickedvalue)
        {
            //alert("fgjdf");
            //$("data-value='" + clickedvalue + "']").addClass("active");
             $('a[data-value = '+clickedvalue+'].category_filter').addClass('active');
        }
});

Body:
something like this might work:

$(".category_filter").hover(function(){
    //alert("adhfdba");
    var clickedvalue = localStorage.getItem("clickedLink");
    //alert(clickedvalue);
    if(clickedvalue && clickedvalue == $(this).attr("data-value"))
    {
        //alert("fgjdf");
        //$("data-value='" + clickedvalue + "']").addClass("active");
        $(this).addClass("active");
    }
});

Just make sure you also remove the active class accordingly


问:
C# Regex.Split - Would like to split a string by a char but allow the char to be used between ' and '
I would like to split a string by / but also allow anything between ' and ' to contain my split character. While removing the ' and ' from the split and any blanks.

example /'TEST/:1'/3 is split into

Test/:1

3

I have something close:

```<code>regex.split(test, "/(?=(?:[^']*'[^']*')*[^']*$)"
</code>```

but it still has the ' and blanks in it.

```<code>string[] fields = Regex.Split(Path, "/(?=(?:[^']*'[^']*')*[^']*$)");
</code>```

Sorry I well be more clear its my own pathing format for parsing EDI like file it works like this. /Location:LineNumber/YPosition. All I want to do so is get in a command line /TEST:4/6 = /Location(Test):LineNumber(4)/YPosition(6). but my problem is that the Location is worked out by my code and could be anything up to the first delimiter. It could be a date format 12/03/03 which is common in EDI type files.

I would like to be able to get my command looking like this /'12/03/03':4/6 so that when the Location is split by my regex.split it does not include anything between the (' and ') location.

Any help please?

答:
It is not entirely clear what you're really trying to achieve. If you want to parse a CSV-like file format, better use a CSV parser; if you want to manipulate file paths, then use your standard library's path manipulation functions. Both are better equipped to deal with edge cases than a simple regex.

That said, you could do

```<code>MatchCollection allMatchResults = null;
Regex regexObj = new Regex(
    @" "" [^""]* ""  # either match a (double-)quoted string
    |                # or
    [^/\s]*          # a sequence of characters other than / or whitespace",
    RegexOptions.IgnorePatternWhitespace);
allMatchResults = regexObj.Matches(subjectString);
</code>```

This will not handle escaped quotes within quoted strings, but if those aren't present in your input, it should work.

Note that "Test / 1"/1/2 3/45 will be split into "Test / 1", 1, 2, 3 and 45 because blanks are removed and thereby also serve as separators.

Body:
I would like to split a string by / but also allow anything between ' and ' to contain my split character. While removing the ' and ' from the split and any blanks.

example /'TEST/:1'/3 is split into

Test/:1

3

I have something close:

regex.split(test, "/(?=(?:[^']*'[^']*')*[^']*$)"

but it still has the ' and blanks in it.

string[] fields = Regex.Split(Path, "/(?=(?:[^']*'[^']*')*[^']*$)");

Sorry I well be more clear its my own pathing format for parsing EDI like file it works like this. /Location:LineNumber/YPosition. All I want to do so is get in a command line /TEST:4/6 = /Location(Test):LineNumber(4)/YPosition(6). but my problem is that the Location is worked out by my code and could be anything up to the first delimiter. It could be a date format 12/03/03 which is common in EDI type files.

I would like to be able to get my command looking like this /'12/03/03':4/6 so that when the Location is split by my regex.split it does not include anything between the (' and ') location.

Any help please?

Body:
It is not entirely clear what you're really trying to achieve. If you want to parse a CSV-like file format, better use a CSV parser; if you want to manipulate file paths, then use your standard library's path manipulation functions. Both are better equipped to deal with edge cases than a simple regex.

That said, you could do

MatchCollection allMatchResults = null;
Regex regexObj = new Regex(
    @" "" [^""]* ""  # either match a (double-)quoted string
    |                # or
    [^/\s]*          # a sequence of characters other than / or whitespace",
    RegexOptions.IgnorePatternWhitespace);
allMatchResults = regexObj.Matches(subjectString);

This will not handle escaped quotes within quoted strings, but if those aren't present in your input, it should work.

Note that "Test / 1"/1/2 3/45 will be split into "Test / 1", 1, 2, 3 and 45 because blanks are removed and thereby also serve as separators.


问:
cmake : use ExternalProject_Add and specify the output folder
I'm currently using one CMakeLists.txt file that will execute an external CMakeLists.txt (and dependency).

For this I use the ExternalProject_Add command, but I can't find a way to specify where the ".sln" file will be generated.

Here is the command I use :

```<code>include(ExternalProject)
set(LIBRARY_SOURCE_DIR C:/Library)
ExternalProject_Add(Library
  SOURCE_DIR        "${LIBRARY_SOURCE_DIR}"
  CMAKE_ARGS
      -DCMAKE_BUILD_TARGET_ANDROID:BOOL=ON
      -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}
      -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS}
      -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
      -DCMAKE_CONFIGURATION_TYPES=${CMAKE_CONFIGURATION_TYPES}
      -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}
      -G@CMAKE_GENERATOR@
  BUILD_COMMAND     ""
)
</code>```

So, I looking for a way to directly specify it in this call. Any idea ?

I also tried, but no way:

```<code>  PREFIX            LibraryBuild
  SOURCE_DIR        "${LIBRARY_SOURCE_DIR}"
  BINARY_DIR        "${LIBRARY_SOURCE_DIR}/LibraryBuild"
  INSTALL_DIR       "${LIBRARY_SOURCE_DIR}/LibraryBuild"
  BUILD_COMMAND     "cmake --build ./LibraryBuild"
  CMAKE_ARGS
      -DCMAKE_RUNTIME_OUTPUT_DIRECTORY="./LibraryBuild"
      -DCMAKE_LIBRARY_OUTPUT_DIRECTORY="./LibraryBuild"
      -DCMAKE_EXECUTABLE_OUTPUT_DIRECTORY="./LibraryBuild"
      "./LibraryBuild"
      -DCMAKE_CURRENT_BINARY_DIR="./LibraryBuild"
      -DCMAKE_GENERATOR="Visual Studio 15 2017 Win64"
</code>```

答:
Do give it a BINARY_DIR, but do NOT give it a BUILD_COMMAND. Giving it an empty BUILD_COMMAND means "do nothing" for the build step and using "cmake --build ./LibraryBuild" does not work unless cmake is in your PATH, and with a Visual Studio solution, you also need to specify "--config Release" or "--config Debug".

If you leave off BUILD_COMMAND entirely for CMake-driven projects, CMake will produce a correct default build command for the CMAKE_GENERATOR used.

Also, I would strongly encourage you to use different values for BINARY_DIR and INSTALL_DIR. They should not overlap. I would recommend you make the INSTALL_DIR a subdirectory or a sibling directory of BINARY_DIR if it's not a canonical install (i.e. under "/usr" or "C:/Program Files...")

Body:
I'm currently using one CMakeLists.txt file that will execute an external CMakeLists.txt (and dependency).

For this I use the ExternalProject_Add command, but I can't find a way to specify where the ".sln" file will be generated.

Here is the command I use :

include(ExternalProject)
set(LIBRARY_SOURCE_DIR C:/Library)
ExternalProject_Add(Library
  SOURCE_DIR        "${LIBRARY_SOURCE_DIR}"
  CMAKE_ARGS
      -DCMAKE_BUILD_TARGET_ANDROID:BOOL=ON
      -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}
      -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS}
      -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
      -DCMAKE_CONFIGURATION_TYPES=${CMAKE_CONFIGURATION_TYPES}
      -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}
      -G@CMAKE_GENERATOR@
  BUILD_COMMAND     ""
)

So, I looking for a way to directly specify it in this call. Any idea ?

I also tried, but no way:

  PREFIX            LibraryBuild
  SOURCE_DIR        "${LIBRARY_SOURCE_DIR}"
  BINARY_DIR        "${LIBRARY_SOURCE_DIR}/LibraryBuild"
  INSTALL_DIR       "${LIBRARY_SOURCE_DIR}/LibraryBuild"
  BUILD_COMMAND     "cmake --build ./LibraryBuild"
  CMAKE_ARGS
      -DCMAKE_RUNTIME_OUTPUT_DIRECTORY="./LibraryBuild"
      -DCMAKE_LIBRARY_OUTPUT_DIRECTORY="./LibraryBuild"
      -DCMAKE_EXECUTABLE_OUTPUT_DIRECTORY="./LibraryBuild"
      "./LibraryBuild"
      -DCMAKE_CURRENT_BINARY_DIR="./LibraryBuild"
      -DCMAKE_GENERATOR="Visual Studio 15 2017 Win64"


问:
SSH connection tunneling refused
I have a virtual machine located inside a private network.
So firstly, I should come in server.com and then come in my-machine.

I want to make ssh-tunnel from my laptop to my-machine.

```<code>ssh -v -A -nNT -L 40000:127.0.0.1:40000 login@server.com ssh -v -nNT -L 40000:127.0.0.1:40000 my-machine &
</code>```

Now I want to test ssh-tunnel with netcat.

I run at my-machine:

```<code>nc -l 40000
</code>```

At my laptop:

```<code>~ ❯❯❯ nc 127.0.0.1 40000
</code>```

But it gives me:

```<code>debug1: Connection to port 40000 forwarding to 127.0.0.1 port 40000 requested.
debug1: channel 2: new [direct-tcpip]
channel 2: open failed: connect failed: Connection refused
debug1: channel 2: free: direct-tcpip: listening port 40000 for 127.0.0.1 port 40000, connect from 127.0.0.1 port 49692 to 127.0.0.1 port 40000, nchannels 3
</code>```

Why this happen and how to fix it? I expected that anything I type in my laptop console will  appear in my-machine console.

What last string means? Especially 127.0.0.1 port 49692 why this port is used? I never type it.

```<code>debug1: channel 2: free: direct-tcpip: listening port 40000 for 127.0.0.1 port 40000, connect from 127.0.0.1 port 49692 to 127.0.0.1 port 40000, nchannels 3
</code>```

答:
Every TCP connection is point to point needs two pairs of IP addresses and ports. Reading all the message (not just the part you showed):

```<code>connect from 127.0.0.1 port 49692
</code>```

So indeed you are connecting to the port 40000, but you are connecting from port 49692 (randomly assigned for your netcat or some of the forwarded steps).

How to fix this problem?

This double-jump forwarding does not work, because you need the second established before the first one.

Also you are using -N switch for the first command, which is preventing running the second ssh command.

But I would give it a shot with ProxyCommand, which will make you connect to the destination with single command directly from your host:

```<code>ssh -v -nNT -L 40000:127.0.0.1:40000 \
    -oProxyCommand="ssh -W %h:%p login@server.com" my-machine &
</code>```

Title: SSH connection tunneling refused

Body:
I have a virtual machine located inside a private network.
So firstly, I should come in server.com and then come in my-machine.

I want to make ssh-tunnel from my laptop to my-machine.

ssh -v -A -nNT -L 40000:127.0.0.1:40000 login@server.com ssh -v -nNT -L 40000:127.0.0.1:40000 my-machine &

Now I want to test ssh-tunnel with netcat.

I run at my-machine:

nc -l 40000

At my laptop:

~ ❯❯❯ nc 127.0.0.1 40000

But it gives me:

debug1: Connection to port 40000 forwarding to 127.0.0.1 port 40000 requested.
debug1: channel 2: new [direct-tcpip]
channel 2: open failed: connect failed: Connection refused
debug1: channel 2: free: direct-tcpip: listening port 40000 for 127.0.0.1 port 40000, connect from 127.0.0.1 port 49692 to 127.0.0.1 port 40000, nchannels 3

Why this happen and how to fix it? I expected that anything I type in my laptop console will  appear in my-machine console.

What last string means? Especially 127.0.0.1 port 49692 why this port is used? I never type it.

debug1: channel 2: free: direct-tcpip: listening port 40000 for 127.0.0.1 port 40000, connect from 127.0.0.1 port 49692 to 127.0.0.1 port 40000, nchannels 3

Body:
Every TCP connection is point to point needs two pairs of IP addresses and ports. Reading all the message (not just the part you showed):

connect from 127.0.0.1 port 49692

So indeed you are connecting to the port 40000, but you are connecting from port 49692 (randomly assigned for your netcat or some of the forwarded steps).

How to fix this problem?

This double-jump forwarding does not work, because you need the second established before the first one.

Also you are using -N switch for the first command, which is preventing running the second ssh command.

But I would give it a shot with ProxyCommand, which will make you connect to the destination with single command directly from your host:

ssh -v -nNT -L 40000:127.0.0.1:40000 \
    -oProxyCommand="ssh -W %h:%p login@server.com" my-machine &


问:
Remove directory which is not empty
In my Node application I need to remove a directory which has some files, but fs.rmdir only works on empty directories. How can I do this?

答:
Another alternative is using the fs-promise module that provides promisified versions of the fs-extra modules

you could then write like this example:

```<code>const { remove, mkdirp, writeFile, readFile } = require('fs-promise')
const { join, dirname } = require('path')

async function createAndRemove() {
  const content = 'Hello World!'
  const root = join(__dirname, 'foo')
  const file = join(root, 'bar', 'baz', 'hello.txt')

  await mkdirp(dirname(file))
  await writeFile(file, content)
  console.log(await readFile(file, 'utf-8'))
  await remove(join(__dirname, 'foo'))
}

createAndRemove().catch(console.error)
</code>```

note: async/await requires a recent nodejs version (7.6+)

Title: Remove directory which is not empty

Body:
Another alternative is using the fs-promise module that provides promisified versions of the fs-extra modules

you could then write like this example:

const { remove, mkdirp, writeFile, readFile } = require('fs-promise')
const { join, dirname } = require('path')

async function createAndRemove() {
  const content = 'Hello World!'
  const root = join(__dirname, 'foo')
  const file = join(root, 'bar', 'baz', 'hello.txt')

  await mkdirp(dirname(file))
  await writeFile(file, content)
  console.log(await readFile(file, 'utf-8'))
  await remove(join(__dirname, 'foo'))
}

createAndRemove().catch(console.error)

note: async/await requires a recent nodejs version (7.6+)


问:
Identical values in an array has to be positioned together
```<code>var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"]
</code>```

i have to arrange it in a way that  identical values has to be placed together

output array should be

```<code>["ddd","aaa","aaa","aaa","eee","fff","fff","bbb","ggg","ccc"]
</code>```

how to write the logic for this one ??

答:
You can create one object to store values and index and then use that object to create new array.

var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"],
 obj = {}, i = 0

array1.forEach(function(e) {
  if(!obj[e]) obj[e] = {index: i++, values: []}
  obj[e].values.push(e)
})

var result = [].concat(...Object.keys(obj).reduce((r, e) => (r[obj[e].index] = obj[e].values, r), []))

console.log(result)```

Body:
var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"]

i have to arrange it in a way that  identical values has to be placed together

output array should be

["ddd","aaa","aaa","aaa","eee","fff","fff","bbb","ggg","ccc"]

how to write the logic for this one ??


问:
how to hide specific div when i click div in vue js
```<code><template>
 <div v-for="(item ,index) in items" v-if="showing">
                <span @click="showing=false">{{item.name}}</span>
 </div>
</template>
    <script>

            export default{
                       showing:true,
                       items: [
                          {'name':'a'},
                          {'name':'b'},
                          {'name':'c'},
                       ],
            }
    </script>
</code>```

how to hide specific div when i click div
** when i do this way it`s all of them was hide**

答:
If you don't want to use an other array to keep hide index (like hide :[]) :

new Vue({
    el: "#app",
      data: function() {
    return {
      items:[ {'name':'a'}, {'name':'b'}, {'name':'c'} ]
    }
  },
  methods: {
    setHide: function(item) {
      this.$set(item, 'hide', true);
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>

<div id="app">
  <div v-for="item in items" :key="item" v-if="!item.hide">
    <span @click="setHide(item)">{{item.name}}</span>
  </div>
</div></code>```

Body:
<template>

                {{item.name}}

</template>

how to hide specific div when i click div
** when i do this way it`s all of them was hide**

Body:
If you don't want to use an other array to keep hide index (like hide :[]) :

new Vue({
    el: "#app",
      data: function() {
    return {
      items:[ {'name':'a'}, {'name':'b'}, {'name':'c'} ]
    }
  },
  methods: {
    setHide: function(item) {
      this.$set(item, 'hide', true);
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>

<div id="app">
  <div v-for="item in items" :key="item" v-if="!item.hide">
    <span @click="setHide(item)">{{item.name}}</span>
  </div>
</div>


问:
call popupwindow from recyclerview
I am trying to call pop up window from my recyclerView adapter, I am getting a android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

here is the code which creates the popupwindow.

```<code> private void initiatePopupWindow() {
        try {
        final View popupView =

LayoutInflater.from(context).inflate(R.layout.times_popup, null);
        final PopupWindow pwindo = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        popupView.post(new Runnable() {
            public void run() {
                pwindo.showAtLocation(popupView, Gravity.CENTER, 0, 0);
            }
        });

        btnClosePopup = (Button) popupView.findViewById(R.id.btn_close_popup);
        btnClosePopup.setOnClickListener(cancel_button_click_listener);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
private View.OnClickListener cancel_button_click_listener = new View.OnClickListener() {
    public void onClick(View v) {
        pwindo.dismiss();

    }
};
</code>```

and here is my RecyclerView class

public class DetailsAdapter extends RecyclerView.Adapter {

```<code>private List<Restaurant> restaurant;
private List<Time> times;
private int rowLayout;
private Context context;
private PopupWindow pwindo;
private Button btnClosePopup;
private CoordinatorLayout rootLayout;
private LinearLayout root;

public class DetailViewholder extends RecyclerView.ViewHolder{
    LinearLayout restaurantLayout;
   // TextView RestaurantTitle;
    TextView address1;
    TextView phone;
    TextView price;
    TextView menu_type;
    TextView rate;
    TextView open;
    RatingBar ratingBar;
    ImageView check;
    TextView offer;
    ImageButton info;

    public DetailViewholder(View v) {
        super(v);

        restaurantLayout = (LinearLayout) v.findViewById(R.id.general_information);
        ratingBar = (RatingBar) v.findViewById(R.id.ratingBar);
        check = (ImageView) v.findViewById(R.id.tick);
        info = (ImageButton) v.findViewById(R.id.info);
        address1 = (TextView) v.findViewById(R.id.address);
        phone = (TextView) v.findViewById(R.id.phone);
        price = (TextView) v.findViewById(R.id.price);
        menu_type = (TextView) v.findViewById(R.id.menu_type);
        rate = (TextView) v.findViewById(R.id.rate);
        open = (TextView) v.findViewById(R.id.hours);
        offer = (TextView) v.findViewById(R.id.offer);
        root =(LinearLayout) v.findViewById(R.id.linear);
        rootLayout = (CoordinatorLayout) v.findViewById(R.id.coordinatorLayout);
        info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //onclick listener for the popup window
                initiatePopupWindow();
            }
        });
    }

    public void callplace(View view){
        String val = phone.getText().toString();
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:"+val));
        context.startActivity(intent);
        Log.v("Calling", "Calling..."+val);
    }

}

public DetailsAdapter(List<Restaurant> restaurant,List<Time> times,int rowLayout,Context context) {
    this.restaurant = restaurant;
    this.times=times;
    this.rowLayout = rowLayout;
    this.context = context;
}

@Override
public DetailsAdapter.DetailViewholder onCreateViewHolder(ViewGroup parent,int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
    return new DetailViewholder(view);

}

@Override
public void onBindViewHolder(DetailViewholder holder, final int position) {
    String Sadd = context.getResources().getString(R.string.addr);
    String Smen = context.getResources().getString(R.string.menu);
    String Spho = context.getResources().getString(R.string.phone);
    String Srat = context.getResources().getString(R.string.rate);
    String Scos = context.getResources().getString(R.string.cost);
    String Shou = context.getResources().getString(R.string.hours);
    String Stil = context.getResources().getString(R.string.till);
    String Soff = context.getResources().getString(R.string.offer);

    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
    try {
        Date StartTime = dateFormat.parse(times.get(position).getStartTime());
        Date FinishTime = dateFormat.parse(times.get(position).getFinishTime());
        Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
        if (CurrentTime.after(FinishTime) || CurrentTime.before(StartTime))
        {
            Log.d(TAG,"Restaurant is currently closed");
            holder.check.setImageResource(R.drawable.ic_check_circle_red_500_18dp);
            holder.check.setVisibility(View.VISIBLE);

        }
        else
        {
            Log.d(TAG,"Its open! yey!");
            holder.check.setVisibility(View.VISIBLE);
            holder.check.setImageResource(R.drawable.ic_check_circle_teal_600_18dp);

        }
    } catch (ParseException e)
    {
        e.printStackTrace();
    }

    holder.ratingBar.setRating(1);
    holder.address1.setText(Sadd+restaurant.get(position).getAddress1().substring(0,20));
    holder.menu_type.setText(Smen+restaurant.get(position).getMenuType());
    holder.phone.setText(Spho+restaurant.get(position).getPhone());
    holder.rate.setText(Srat+restaurant.get(position).getRate());
    holder.price.setText(Scos+restaurant.get(position).getCost() +"€");
    holder.open.setText(Shou + times.get(position).getStartTime().substring(0,5)
            + Stil +times.get(position).getFinishTime().substring(0,5));
    holder.offer.setText(Soff+restaurant.get(position).getOffer());
    Picasso.with(context).load(R.drawable.ic_info_blue_900_18dp)
            .fit()
            .into(holder.info);

}
@Override
public int getItemCount() {
    return restaurant.size();
}
</code>```

答:
Try to show popup in activity, using listener in adapter.

Just implement DetailsAdapter.DetailListener in your activity and show popup there

```<code>public class DetailsAdapter extends RecyclerView.Adapter {

    interface DetailListener {
        void onInfoClicked();
    }

    private DetailListener detailListener;

    public DetailsAdapter(List<Restaurant> restaurant,List<Time> times,int rowLayout,Context context, DetailListener detailListener) {
        this.restaurant = restaurant;
        this.times=times;
        this.rowLayout = rowLayout;
        this.context = context;
        this.detailListener = detailListener;
    }

    ...

    public class DetailViewholder extends RecyclerView.ViewHolder {

    ...

    public DetailViewholder(View v) {
        super(v);

        ...

        info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (detailsListener != null) {
                    detailsListener.onInfoClicked();
                }
            }
        });
    }
}
</code>```

Title: call popupwindow from recyclerview

Body:
I am trying to call pop up window from my recyclerView adapter, I am getting a android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

here is the code which creates the popupwindow.

 private void initiatePopupWindow() {
        try {
        final View popupView =

LayoutInflater.from(context).inflate(R.layout.times_popup, null);
        final PopupWindow pwindo = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        popupView.post(new Runnable() {
            public void run() {
                pwindo.showAtLocation(popupView, Gravity.CENTER, 0, 0);
            }
        });

        btnClosePopup = (Button) popupView.findViewById(R.id.btn_close_popup);
        btnClosePopup.setOnClickListener(cancel_button_click_listener);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
private View.OnClickListener cancel_button_click_listener = new View.OnClickListener() {
    public void onClick(View v) {
        pwindo.dismiss();

    }
};

and here is my RecyclerView class

public class DetailsAdapter extends RecyclerView.Adapter {

private List<Restaurant> restaurant;
private List<Time> times;
private int rowLayout;
private Context context;
private PopupWindow pwindo;
private Button btnClosePopup;
private CoordinatorLayout rootLayout;
private LinearLayout root;

public class DetailViewholder extends RecyclerView.ViewHolder{
    LinearLayout restaurantLayout;
   // TextView RestaurantTitle;
    TextView address1;
    TextView phone;
    TextView price;
    TextView menu_type;
    TextView rate;
    TextView open;
    RatingBar ratingBar;
    ImageView check;
    TextView offer;
    ImageButton info;

    public DetailViewholder(View v) {
        super(v);

        restaurantLayout = (LinearLayout) v.findViewById(R.id.general_information);
        ratingBar = (RatingBar) v.findViewById(R.id.ratingBar);
        check = (ImageView) v.findViewById(R.id.tick);
        info = (ImageButton) v.findViewById(R.id.info);
        address1 = (TextView) v.findViewById(R.id.address);
        phone = (TextView) v.findViewById(R.id.phone);
        price = (TextView) v.findViewById(R.id.price);
        menu_type = (TextView) v.findViewById(R.id.menu_type);
        rate = (TextView) v.findViewById(R.id.rate);
        open = (TextView) v.findViewById(R.id.hours);
        offer = (TextView) v.findViewById(R.id.offer);
        root =(LinearLayout) v.findViewById(R.id.linear);
        rootLayout = (CoordinatorLayout) v.findViewById(R.id.coordinatorLayout);
        info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //onclick listener for the popup window
                initiatePopupWindow();
            }
        });
    }

    public void callplace(View view){
        String val = phone.getText().toString();
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:"+val));
        context.startActivity(intent);
        Log.v("Calling", "Calling..."+val);
    }

}

public DetailsAdapter(List<Restaurant> restaurant,List<Time> times,int rowLayout,Context context) {
    this.restaurant = restaurant;
    this.times=times;
    this.rowLayout = rowLayout;
    this.context = context;
}

@Override
public DetailsAdapter.DetailViewholder onCreateViewHolder(ViewGroup parent,int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
    return new DetailViewholder(view);

}

@Override
public void onBindViewHolder(DetailViewholder holder, final int position) {
    String Sadd = context.getResources().getString(R.string.addr);
    String Smen = context.getResources().getString(R.string.menu);
    String Spho = context.getResources().getString(R.string.phone);
    String Srat = context.getResources().getString(R.string.rate);
    String Scos = context.getResources().getString(R.string.cost);
    String Shou = context.getResources().getString(R.string.hours);
    String Stil = context.getResources().getString(R.string.till);
    String Soff = context.getResources().getString(R.string.offer);

    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
    try {
        Date StartTime = dateFormat.parse(times.get(position).getStartTime());
        Date FinishTime = dateFormat.parse(times.get(position).getFinishTime());
        Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
        if (CurrentTime.after(FinishTime) || CurrentTime.before(StartTime))
        {
            Log.d(TAG,"Restaurant is currently closed");
            holder.check.setImageResource(R.drawable.ic_check_circle_red_500_18dp);
            holder.check.setVisibility(View.VISIBLE);

        }
        else
        {
            Log.d(TAG,"Its open! yey!");
            holder.check.setVisibility(View.VISIBLE);
            holder.check.setImageResource(R.drawable.ic_check_circle_teal_600_18dp);

        }
    } catch (ParseException e)
    {
        e.printStackTrace();
    }

    holder.ratingBar.setRating(1);
    holder.address1.setText(Sadd+restaurant.get(position).getAddress1().substring(0,20));
    holder.menu_type.setText(Smen+restaurant.get(position).getMenuType());
    holder.phone.setText(Spho+restaurant.get(position).getPhone());
    holder.rate.setText(Srat+restaurant.get(position).getRate());
    holder.price.setText(Scos+restaurant.get(position).getCost() +"€");
    holder.open.setText(Shou + times.get(position).getStartTime().substring(0,5)
            + Stil +times.get(position).getFinishTime().substring(0,5));
    holder.offer.setText(Soff+restaurant.get(position).getOffer());
    Picasso.with(context).load(R.drawable.ic_info_blue_900_18dp)
            .fit()
            .into(holder.info);

}
@Override
public int getItemCount() {
    return restaurant.size();
}

Body:
Try to show popup in activity, using listener in adapter.

Just implement DetailsAdapter.DetailListener in your activity and show popup there

public class DetailsAdapter extends RecyclerView.Adapter {

    interface DetailListener {
        void onInfoClicked();
    }

    private DetailListener detailListener;

    public DetailsAdapter(List<Restaurant> restaurant,List<Time> times,int rowLayout,Context context, DetailListener detailListener) {
        this.restaurant = restaurant;
        this.times=times;
        this.rowLayout = rowLayout;
        this.context = context;
        this.detailListener = detailListener;
    }

    ...

    public class DetailViewholder extends RecyclerView.ViewHolder {

    ...

    public DetailViewholder(View v) {
        super(v);

        ...

        info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (detailsListener != null) {
                    detailsListener.onInfoClicked();
                }
            }
        });
    }
}


问:
Install Apache TomCat using Puppet
Has anyone successfully installed Apache Tomcat using Puppet? I am following the instructions on Puppets own tomcat module - https://forge.puppetlabs.com/puppetlabs/tomcat but it does not work!</p>

答:
Yes - After trying many examples with the puppetlabs module I was able to install tomcat, nevertheless i find aco/tomcat module much easier to use (the installation of the services is automated aswell).

If you are not forced to use the supported module I'd go with aco/tomcat instead.

Title: Install Apache TomCat using Puppet


问:
Javascript - How do I find out which condition(s) triggered?
Let's say I have the following statement:

```<code>if (height > 4.25 || length > 6 || weight > 1) {
  //Do Something
}
</code>```

Is there a way to tell which of the conditions was met in order for that statement to be true?

Something more elegant than below, which is obviously redundant:

```<code>if (height > 4.25 || length > 6 || weight > 1) {
  if (height > 4.25){...};
  if (length > 6){...};
  if (weight > 1){...};
}
</code>```

答:
you can always assign the conditional check to a variable.
something like this:

```<code>function dimension(height, length, weight) {
    var param = {};
    if ((param.height = height > 4.25) || (param.length = length > 6) || (param.weight = weight > 1)) {
        console.log(param);
        //if (param.height) dosomething_with_height(height);
        //if (param.length) dosomething_with_length(length);
        //if (param.weight) dosomething_with_weight(weight);
    }
}
</code>```

but you know, since its if-or conditional, when some of condition are meet, then the next condition aren't checked.

so if height condition are meet, then length and weight are undefined.
or if length condition are meet, then the height are false, but the weight are undefined.

Body:
Let's say I have the following statement:

if (height > 4.25 || length > 6 || weight > 1) {
  //Do Something
}

Is there a way to tell which of the conditions was met in order for that statement to be true?

Something more elegant than below, which is obviously redundant:

if (height > 4.25 || length > 6 || weight > 1) {
  if (height > 4.25){...};
  if (length > 6){...};
  if (weight > 1){...};
}

Body:
you can always assign the conditional check to a variable.
something like this:

function dimension(height, length, weight) {
    var param = {};
    if ((param.height = height > 4.25) || (param.length = length > 6) || (param.weight = weight > 1)) {
        console.log(param);
        //if (param.height) dosomething_with_height(height);
        //if (param.length) dosomething_with_length(length);
        //if (param.weight) dosomething_with_weight(weight);
    }
}

but you know, since its if-or conditional, when some of condition are meet, then the next condition aren't checked.

so if height condition are meet, then length and weight are undefined.
or if length condition are meet, then the height are false, but the weight are undefined.


问:
What is the alternative to cursors to retrieve large amounts of data from a database?
Searching through stackoverflow I found a large number of answers condemning the use of cursors in database programming. However I don't really understand what the alternative is.

I'm creating a program which reads a large number of rows (hundreds of thousands) from the database and keeps them in memory, for performance reasons. I can't really run a SELECT * FROM table and process all the results at once, can I?

The best way I have found is to use cursors and retrieve the rows in increments, for example 10 at a time.

Could someone enlighten me? I use PostgreSQL 9 on linux.

Thanks

答: Have a look at LIMIT and OFFSET</p>

Body: Have a look at LIMIT and OFFSET


答: I'd say use $(this) this instead of $('a[data-value = '+clickedvalue+'].category_filter')

Title: How to add class on hover using jquery


问:
RSpec does not find my view helper
I get this error when I run my test

```<code>spec/helpers/bikes_helper_spec.rb:3:in `<top (required)>':
uninitialized constant BikesHelper (NameError)
</code>```

bikes_helper

```<code>require "spec_helper"

describe BikesHelper do

  describe "#km_until_next_service" do
    it 'returns a human readable number' do
      expect(km_until_next_service(1000)).to eq '1000 kilometers'
    end

  end
end
</code>```

app/helpers/bikes_helper.rb

```<code>module BikesHelper

  include ActionView::Helpers::NumberHelper

  def km_until_next_service(km_untill_next)

    if km_untill_next == 0
      return "NOW"
    elsif (km_untill_next < 0)
      return "Overdue by #{number_to_human(km_untill_next, unit: :distance)}"
    elsif (km_untill_next > 0)
      return "In #{number_to_human(km_untill_next, unit: :distance)}"
    end

  end
end
</code>```

Any idea why it does not recognise BikesHelper?

答:
Try to

```<code>require 'rails_helper'
</code>```

instead of

```<code>require 'spec_helper'
</code>```

Title: RSpec does not find my view helper

Body:
I get this error when I run my test

spec/helpers/bikes_helper_spec.rb:3:in `<top (required)>':
uninitialized constant BikesHelper (NameError)

bikes_helper

require "spec_helper"

describe BikesHelper do

  describe "#km_until_next_service" do
    it 'returns a human readable number' do
      expect(km_until_next_service(1000)).to eq '1000 kilometers'
    end

  end
end

app/helpers/bikes_helper.rb

module BikesHelper

  include ActionView::Helpers::NumberHelper

  def km_until_next_service(km_untill_next)

    if km_untill_next == 0
      return "NOW"
    elsif (km_untill_next < 0)
      return "Overdue by #{number_to_human(km_untill_next, unit: :distance)}"
    elsif (km_untill_next > 0)
      return "In #{number_to_human(km_untill_next, unit: :distance)}"
    end

  end
end

Any idea why it does not recognise BikesHelper?

Body:
Try to

require 'rails_helper'

instead of

require 'spec_helper'