问:
Android 7 intent extras missing
Does anyone know if there are any changes to how Android 7.0 (Nougat) handles intent extras compared to Android 6.0 (Lollipop)?

Long story short: my app works as intended on all versions from 4.1(16) to 6.0(23) but crashes on android 7.0(24)!

The app creates a pending intent with an intent to a custom broadcast receiver which has extras. However, on android 7 none of the extras are present in the intent received by the broadcast receiver.

MainActivity.java

Intent intent = new Intent(context, PollServerReceiver.class);

// TODO:  Remove after DEBUGGING is completed!
intent.putExtra("TESTING1", "testing1");
intent.putExtra("TESTING2", "testing2");
intent.putExtra("TESTING3", "testing3");

 // PendingIntent to be triggered when the alarm goes off.
 final PendingIntent pIntent = PendingIntent.getBroadcast(context,
            PollServerReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Setup alarm to schedule our service runs.
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstRun, freqMilis, pIntent);
```

<p><strong><code>PollServerReceiver.java</code></strong></p>

<pre class="lang-java prettyprint-override"><code>Bundle extras = intent.getExtras();
Log.d(TAG, "onReceive: TESTING1 = " + extras.getString("TESTING1")); // null here

// None of the three "TESTING*" keys are there!
for (String key : extras.keySet()) {
    Object value = extras.get(key);
    Log.d(TAG, String.format("onReceive extra keys: %s %s (%s)", key, value.toString(), value.getClass().getName()));
}
</code>```

Stack trace obviously gives the NullPointerException as the cause of crash.
It would not be so weird if it would crash among all versions, but in this case its the latest android only. Has anyone got any ideas please?

Note: I have tried creating pending intents with different flags including (0, PendingIntent.FLAG_UPDATE_CURRENT, PendingIntent.FLAG_CANCEL_CURRENT) still got the exact same result.

答:
I had a similar problem but I think I found an easy solution. Put your data inside a Bundle and send that Bundle with your intent. In my case I wanted to send a serializable object with my intent.

Setup the alarm:

```<code>AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReciever.class);
Bundle bundle = new Bundle();

//creating an example object
ExampleClass exampleObject = new ExampleClass();

//put the object inside the Bundle
bundle.putSerializable("example", exampleObject);

//put the Bundle inside the intent
intent.putExtra("bundle",bundle);

PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

//setup the alarm
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
</code>```

Receive the alarm:

```<code>public class AlarmReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // get the Bundle
        Bundle bundle = intent.getBundleExtra("bundle");
        // get the object
        ExampleClass exampleObject = (ExampleClass)bundle.getSerializable("example");
    }

}
</code>```

It worked fine for me. Hope it helps :)

Title: Android 7 intent extras missing

Body:
Does anyone know if there are any changes to how Android 7.0 (Nougat) handles intent extras compared to Android 6.0 (Lollipop)?

Long story short: my app works as intended on all versions from 4.1(16) to 6.0(23) but crashes on android 7.0(24)!

The app creates a pending intent with an intent to a custom broadcast receiver which has extras. However, on android 7 none of the extras are present in the intent received by the broadcast receiver.

MainActivity.java

Intent intent = new Intent(context, PollServerReceiver.class);

// TODO:  Remove after DEBUGGING is completed!
intent.putExtra("TESTING1", "testing1");
intent.putExtra("TESTING2", "testing2");
intent.putExtra("TESTING3", "testing3");

 // PendingIntent to be triggered when the alarm goes off.
 final PendingIntent pIntent = PendingIntent.getBroadcast(context,
            PollServerReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Setup alarm to schedule our service runs.
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstRun, freqMilis, pIntent);

PollServerReceiver.java

Bundle extras = intent.getExtras();
Log.d(TAG, "onReceive: TESTING1 = " + extras.getString("TESTING1")); // null here

// None of the three "TESTING*" keys are there!
for (String key : extras.keySet()) {
    Object value = extras.get(key);
    Log.d(TAG, String.format("onReceive extra keys: %s %s (%s)", key, value.toString(), value.getClass().getName()));
}

Stack trace obviously gives the NullPointerException as the cause of crash.
It would not be so weird if it would crash among all versions, but in this case its the latest android only. Has anyone got any ideas please?

Note: I have tried creating pending intents with different flags including (0, PendingIntent.FLAG_UPDATE_CURRENT, PendingIntent.FLAG_CANCEL_CURRENT) still got the exact same result.

Body:
I had a similar problem but I think I found an easy solution. Put your data inside a Bundle and send that Bundle with your intent. In my case I wanted to send a serializable object with my intent.

Setup the alarm:

AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReciever.class);
Bundle bundle = new Bundle();

//creating an example object
ExampleClass exampleObject = new ExampleClass();

//put the object inside the Bundle
bundle.putSerializable("example", exampleObject);

//put the Bundle inside the intent
intent.putExtra("bundle",bundle);

PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

//setup the alarm
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);

Receive the alarm:

public class AlarmReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // get the Bundle
        Bundle bundle = intent.getBundleExtra("bundle");
        // get the object
        ExampleClass exampleObject = (ExampleClass)bundle.getSerializable("example");
    }

}

It worked fine for me. Hope it helps :)


来源: stackexchange

问:
Shuffling an array without built in functions?
Trying to shuffle an array without using built in functions.

```<code>def shuffle2():
    lis = [5,6,7,10,11,12]
    print (lis)
    x = random.randint (0,len (lis)-1)
    y = random.randint (0,len (lis)-1)
    z = lis[x], lis[y] = lis[y], lis[x]#flips the elements around

 shuffle2()
</code>```

So far it switches two elements around once, however I need it to shuffle the whole array rather than just two positions.

output:
      [5, 6, 7, 10, 11, 12]
      [11, 6, 7, 10, 5, 12]

Any ideas?

答:
```<code>import random
def shuffle2():
    i = 1
    lis = [5,6,7,10,11,12]
    print (lis)
    while i < len(lis):
        x = random.randint (0,len (lis)-1)
        y = random.randint (0,len (lis)-1)
        z = lis[x], lis[y] = lis[y], lis[x]
        i = i + 1
        #flips the elements around

    print (lis)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Trying to shuffle an array without using built in functions.

def shuffle2():
    lis = [5,6,7,10,11,12]
    print (lis)
    x = random.randint (0,len (lis)-1)
    y = random.randint (0,len (lis)-1)
    z = lis[x], lis[y] = lis[y], lis[x]#flips the elements around

 shuffle2()

So far it switches two elements around once, however I need it to shuffle the whole array rather than just two positions.

output:
      [5, 6, 7, 10, 11, 12]
      [11, 6, 7, 10, 5, 12]

Any ideas?


问:
"waiting for target device to come online" in Android Studio 2.3
Recently upgraded to Android Studio from 2.2.3 to 2., running on Win10

Emulator stopped working since then. Tried installing other images(25 rev 4)/upgrading for AVD but nothing seems to work. After running gradle and showing "waiting for target device to come online" in task bar nothing happens and program doesn't run.

Kindly help

Adding Screenshot:

And:

答:
For me what was happening was the Virtual device never booted.

What fixed this was:

```<code>cd ~/.android/avd/<Name of virtual device>/
rm *.img
</code>```

Then I restarted the virtual device and it came on line.

Body:
For me what was happening was the Virtual device never booted.

What fixed this was:

cd ~/.android/avd/<Name of virtual device>/
rm *.img

Then I restarted the virtual device and it came on line.


问:
Mock an object which is part of mocked object
when I run the test case I get AnObj mocked. this is used from inside the target classes method. when that method gets invoked the 'anOtherObj' is accessed and that is found to be null. Can some one please point out how to make sure 'anOtherObj' is not null so that I dont get nullpointer there?</p>

```<code>    @Test
    public class TestTargetTest {

    @Mock
    private AnObj anObj;

    @InjectMocks
    private TestTarget testTarget;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testTarget() {

        when(anObj.someMethod()).thenCallRealMethod();

        testTarget.testTarget();

    }

}

@Component
public class TestTarget {

    @Autowired
    private AnObj anObj;

    public void testTarget(){

        anObj.someMethod();
    }
}

@Component
public class AnObj {

    @Autowired
    private AnOtherObj anOtherObj;

    public void someMethod(){
        syso(anOtherObj.toString());
    }
}
</code>```

答: As mentioned by @Valya that point was valid. I shouldn't have mocked that. I needed to autowire 'AnObj'. Thanks a lot for all the help. It made the difference.</p>

Body:
when I run the test case I get AnObj mocked. this is used from inside the target classes method. when that method gets invoked the 'anOtherObj' is accessed and that is found to be null. Can some one please point out how to make sure 'anOtherObj' is not null so that I dont get nullpointer there?

    @Test
    public class TestTargetTest {

    @Mock
    private AnObj anObj;

    @InjectMocks
    private TestTarget testTarget;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testTarget() {

        when(anObj.someMethod()).thenCallRealMethod();

        testTarget.testTarget();

    }

}

@Component
public class TestTarget {

    @Autowired
    private AnObj anObj;

    public void testTarget(){

        anObj.someMethod();
    }
}

@Component
public class AnObj {

    @Autowired
    private AnOtherObj anOtherObj;

    public void someMethod(){
        syso(anOtherObj.toString());
    }
}


问:
add typings for missing method (from a npm package)
I'm using the package @types/cropperjs
unfortunately it is behind the current cropper.js versions and lacks the method scale.
So far I just manually added the missing method to the d.ts file under node_modules (this is obviously a bad idea, so don't do that! it was just a temp. fix)

I tried to merge the definitions from node_modules with my own declaration.

```<code>declare class cropperjs {

  /**
   * Scale the image.
   *
   * @param scaleX The scaling factor to apply on the abscissa of the image.
   * When equal to 1 it does nothing. Default is 1
   * @param scaleY The scaling factor to apply on the ordinate of the image.
   * If not present, its default value is scaleX.
   */
   scale(scaleX: number, scaleY?: number): void;
}

export = cropperjs;
export as namespace Cropper;
</code>```

the typings from the DefinitlyTyped Repo can be found on github (it looks similar but is too big to display here)

Here's how I import cropper in an angular component.

import * as Cropper from 'cropperjs';

Here's my tsconfig.json (parts of it)

```<code> "typeRoots": [
  "node_modules/@types",
  "node_modules/@angular",
  "src/typings"
],
"types": [
  "jasmine",
  "node",
  "karma",
  "webpack",
   "cropperjs"
]
</code>```

I tried it with my custom typings folder an with the tripple slash reference notation.
But I can't figure out how I can successfully merge my and DefinitlyTyped's definitions so I can use cropperjs without having to fiddle around in node_module

P.S.
I already opened an issue with the updated definitions on github (no pull request, because at the time had almost no knowledge of git).

答:
As far as I know, you can't do that in typescript. Typescript has the concept of declaration merging, which is what allows us to extend types other people wrote, and you can merge interface and namespaces, but not classes. Look here.

If the @types/cropperjs would have been written using interfaces, you could have extended that interface using your own declaration.

Here is an ugly hack you can do for now:

```<code>import * as Cropper from 'cropperjs';

interface MyCropper extends Cropper {
  scale(scaleX: number, scaleY?: number): void;
}

function CreateCropper(dom: HTMLImageElement, options: Cropper.CropperOptions): MyCropper {
  return new Cropper(dom, options) as MyCropper;
}
</code>```

casting is always ugly, but at least you hide it in one place, I think it's reasonable...

ContentLicense: CC BY-SA 4.0

Body:
I'm using the package @types/cropperjs
unfortunately it is behind the current cropper.js versions and lacks the method scale.
So far I just manually added the missing method to the d.ts file under node_modules (this is obviously a bad idea, so don't do that! it was just a temp. fix)

I tried to merge the definitions from node_modules with my own declaration.

declare class cropperjs {

  /**
   * Scale the image.
   *
   * @param scaleX The scaling factor to apply on the abscissa of the image.
   * When equal to 1 it does nothing. Default is 1
   * @param scaleY The scaling factor to apply on the ordinate of the image.
   * If not present, its default value is scaleX.
   */
   scale(scaleX: number, scaleY?: number): void;
}

export = cropperjs;
export as namespace Cropper;

the typings from the DefinitlyTyped Repo can be found on github (it looks similar but is too big to display here)

Here's how I import cropper in an angular component.

import * as Cropper from 'cropperjs';

Here's my tsconfig.json (parts of it)

 "typeRoots": [
  "node_modules/@types",
  "node_modules/@angular",
  "src/typings"
],
"types": [
  "jasmine",
  "node",
  "karma",
  "webpack",
   "cropperjs"
]

I tried it with my custom typings folder an with the tripple slash reference notation.
But I can't figure out how I can successfully merge my and DefinitlyTyped's definitions so I can use cropperjs without having to fiddle around in node_module

P.S.
I already opened an issue with the updated definitions on github (no pull request, because at the time had almost no knowledge of git).

Body:
As far as I know, you can't do that in typescript. Typescript has the concept of declaration merging, which is what allows us to extend types other people wrote, and you can merge interface and namespaces, but not classes. Look here.

If the @types/cropperjs would have been written using interfaces, you could have extended that interface using your own declaration.

Here is an ugly hack you can do for now:

import * as Cropper from 'cropperjs';

interface MyCropper extends Cropper {
  scale(scaleX: number, scaleY?: number): void;
}

function CreateCropper(dom: HTMLImageElement, options: Cropper.CropperOptions): MyCropper {
  return new Cropper(dom, options) as MyCropper;
}

casting is always ugly, but at least you hide it in one place, I think it's reasonable...


问:
How to handle business rules in DDD + CQRS + Event Sourcing approach?
I'm trying to figure out how to deal with complex domain model using CQRS/ES approach. Let's imagine we have e.g. Order domain entity, which handles both state and behavior of order. It has a Status property with transition rules for switching between statuses (implementing State pattern or any other kind of state machine). According to DDD principles, this logic should be implemented in Order class (representing the Order model) itself, having methods like approve(), cancel(), ship(), etc.

Looking at different public examples of this kind architecture, it turns out that domain entity and aggregate root is the same, and it handles both the state and behavior and even its own projection from events. Isn't it a violation of SRP?

But my question is more concrete: if I want to process new command (and apply new event), should I reconstitute entity from event stream (i.e. from write model and write db) and call its behavioral methods (which applies events to state) to handle business rules? Or just handle commands and events themselves, without having any write-model entity?

Pseudocode to illustrate:

```<code>class ApproveOrderHandler
{
    private EventStore eventStore

    // ...

    public void handle(ApproveOrder event)
    {
        Order order = this.eventStore.findById(event.getOrderId()); // getting order projection from event store
        order.approve(); // handling business logic
        this.eventStore.save(order.releaseEvents()); // save new events (OrderApproved)
    }
}

class Order extends AbstractAggregate
{
    private Uuid id;

    private DateTime takenAt;

    private OrderStatus status;

    // ...

    public void approve()
    {
        this.status.approve(); // business rules blah blah
        this.Apply(new OrderApproved(this.id)); // applying event
    }

    // ...
}
</code>```

Isn't that overdoing or somewhat?

And what should I do with relationships between entities in event-sourcing? If they exist only in "read model", there is no point in domain entity class.

EDIT: or maybe I should store state snapshot in "read database" and recover entity for operations from it? But it breaks idea of "different models for read & write"...

EDIT2: fixed read/write models mistake

答:
Looking at different public examples of this kind architecture, it turns out that domain entity and aggregate root is the same, and it handles both the state and behavior and even its own projection from events. Isn't it a violation of SRP?

No, it does not. "Responsibility" is a vague term but in this case means "reason to change" and an aggregate root has only one (kind of) reason to change: business requirements change. One example of reason to change that do not affect the Aggregate roots is the infrastructure changes, i.e. you change to event store implementation from MySql to MongoDB.

But my question is more concrete: if I want to process new command (and apply new event), should I reconstitute entity from event stream (i.e. from write model and write db) and call its behavioral methods (which applies events to state) to handle business rules?

Every time a command reaches an Aggregate, that Aggregate instance is reconstructed from its stream of events (that are loaded from the Event store - the write side persistence), by applying one by one, in the order that they were generated; there could be optimizations as snapshoting but they should be avoided until proven necessary.

Or just handle commands and events themselves, without having any write-model entity?

You need to have a write model entity, a.k.a. Aggregate; that model enforces the business rules by refusing commands that are incompatible with previously generated events.

Your pseudocode should look like this:

```<code>class ApproveOrderHandler
{
    private EventStore eventStore

    // ...

    public void handle(ApproveOrder event)
    {
        Order order = this.eventStore.findById(event.getOrderId()); // getting order projection from event store
        order.approve(); // handling business logic
        this.eventStore.save(order.releaseEvents()); // save new events (OrderApproved)
    }
}

class Order extends AbstractAggregate
{
    private Uuid id;

    private DateTime takenAt;

    private OrderStatus status;

    // ...

    public void approve()
    {
        if(!this.canBeApproved){ //here is a business rule enforced!
            throw new Exception('Order cannot be approved');
        }

        if(this.status.isAlreadyApproved()){
             return; //idempotent operation
        }

        // this line of code was moved to its own Apply method

        this.generateAndApplyEvent(new OrderApproved(this.id)); // applying event
    }

    //this method is called in two situations: when the aggregate is reconstructed from the eventstream and when the event is raised for the first time
    public void Apply(OrderApproved event)
    {
        this.status.approve(); // transition change
    }

    // ...
}
</code>```

Isn't that overdoing or somewhat?

No, it's not. Note that I moved the line of code that was changing the order status

And what should I do with relationships between entities in event-sourcing? If they exist only in "read model", there is no point in domain entity class.

Relationships between entities (between aggregate roots) exist in the write model too but the references are only by ID.

EDIT: or maybe I should store state snapshot in "read database" and recover entity for operations from it? But it breaks idea of "different models for read & write"...

Aggregate snapshots, when activated/used, are in general stored along the event stream, in the events commit (an events commit is composed of all events that were generated by a single command execution). From what I've seen in productions, snapshots are stored every n-th commit (for example every 5 commits). So they are stored on the write side. This is because a snapshot have a meaning only in the context of a specific Aggregate version.

Body:
I'm trying to figure out how to deal with complex domain model using CQRS/ES approach. Let's imagine we have e.g. Order domain entity, which handles both state and behavior of order. It has a Status property with transition rules for switching between statuses (implementing State pattern or any other kind of state machine). According to DDD principles, this logic should be implemented in Order class (representing the Order model) itself, having methods like approve(), cancel(), ship(), etc.

Looking at different public examples of this kind architecture, it turns out that domain entity and aggregate root is the same, and it handles both the state and behavior and even its own projection from events. Isn't it a violation of SRP?

But my question is more concrete: if I want to process new command (and apply new event), should I reconstitute entity from event stream (i.e. from write model and write db) and call its behavioral methods (which applies events to state) to handle business rules? Or just handle commands and events themselves, without having any write-model entity?

Pseudocode to illustrate:

class ApproveOrderHandler
{
    private EventStore eventStore

    // ...

    public void handle(ApproveOrder event)
    {
        Order order = this.eventStore.findById(event.getOrderId()); // getting order projection from event store
        order.approve(); // handling business logic
        this.eventStore.save(order.releaseEvents()); // save new events (OrderApproved)
    }
}

class Order extends AbstractAggregate
{
    private Uuid id;

    private DateTime takenAt;

    private OrderStatus status;

    // ...

    public void approve()
    {
        this.status.approve(); // business rules blah blah
        this.Apply(new OrderApproved(this.id)); // applying event
    }

    // ...
}

Isn't that overdoing or somewhat?

And what should I do with relationships between entities in event-sourcing? If they exist only in "read model", there is no point in domain entity class.

EDIT: or maybe I should store state snapshot in "read database" and recover entity for operations from it? But it breaks idea of "different models for read & write"...

EDIT2: fixed read/write models mistake

Body:
Looking at different public examples of this kind architecture, it turns out that domain entity and aggregate root is the same, and it handles both the state and behavior and even its own projection from events. Isn't it a violation of SRP?

No, it does not. "Responsibility" is a vague term but in this case means "reason to change" and an aggregate root has only one (kind of) reason to change: business requirements change. One example of reason to change that do not affect the Aggregate roots is the infrastructure changes, i.e. you change to event store implementation from MySql to MongoDB.

But my question is more concrete: if I want to process new command (and apply new event), should I reconstitute entity from event stream (i.e. from write model and write db) and call its behavioral methods (which applies events to state) to handle business rules?

Every time a command reaches an Aggregate, that Aggregate instance is reconstructed from its stream of events (that are loaded from the Event store - the write side persistence), by applying one by one, in the order that they were generated; there could be optimizations as snapshoting but they should be avoided until proven necessary.

Or just handle commands and events themselves, without having any write-model entity?

You need to have a write model entity, a.k.a. Aggregate; that model enforces the business rules by refusing commands that are incompatible with previously generated events.

Your pseudocode should look like this:

class ApproveOrderHandler
{
    private EventStore eventStore

    // ...

    public void handle(ApproveOrder event)
    {
        Order order = this.eventStore.findById(event.getOrderId()); // getting order projection from event store
        order.approve(); // handling business logic
        this.eventStore.save(order.releaseEvents()); // save new events (OrderApproved)
    }
}

class Order extends AbstractAggregate
{
    private Uuid id;

    private DateTime takenAt;

    private OrderStatus status;

    // ...

    public void approve()
    {
        if(!this.canBeApproved){ //here is a business rule enforced!
            throw new Exception('Order cannot be approved');
        }

        if(this.status.isAlreadyApproved()){
             return; //idempotent operation
        }

        // this line of code was moved to its own Apply method

        this.generateAndApplyEvent(new OrderApproved(this.id)); // applying event
    }

    //this method is called in two situations: when the aggregate is reconstructed from the eventstream and when the event is raised for the first time
    public void Apply(OrderApproved event)
    {
        this.status.approve(); // transition change
    }

    // ...
}

Isn't that overdoing or somewhat?

No, it's not. Note that I moved the line of code that was changing the order status

And what should I do with relationships between entities in event-sourcing? If they exist only in "read model", there is no point in domain entity class.

Relationships between entities (between aggregate roots) exist in the write model too but the references are only by ID.

EDIT: or maybe I should store state snapshot in "read database" and recover entity for operations from it? But it breaks idea of "different models for read & write"...

Aggregate snapshots, when activated/used, are in general stored along the event stream, in the events commit (an events commit is composed of all events that were generated by a single command execution). From what I've seen in productions, snapshots are stored every n-th commit (for example every 5 commits). So they are stored on the write side. This is because a snapshot have a meaning only in the context of a specific Aggregate version.


问:
Change private static final field using Java reflection
I have a class with a private static final field that, unfortunately, I need to change it at run-time.

Using reflection I get this error: java.lang.IllegalAccessException: Can not set static final boolean field

Is there any way to change the value?

```<code>Field hack = WarpTransform2D.class.getDeclaredField("USE_HACK");
hack.setAccessible(true);
hack.set(null, true);
</code>```

答: Along with top ranked answer you may use a bit simpliest approach. Apache commons FieldUtils class already has particular method that can do the stuff. Please, take a look at FieldUtils.removeFinalModifier method. You should specify target field instance and accessibility forcing flag (if you play with non-public fields). More info you can find here.

Body:
I have a class with a private static final field that, unfortunately, I need to change it at run-time.

Using reflection I get this error: java.lang.IllegalAccessException: Can not set static final boolean field

Is there any way to change the value?

Field hack = WarpTransform2D.class.getDeclaredField("USE_HACK");
hack.setAccessible(true);
hack.set(null, true);


问:
Is there a way to specify an alternate scalastyle-config.xml under IntelliJ for test scope?
In build.sbt you can specify an alternate scalastyle config file for test scope using this:

(scalastyleConfig in Test) := baseDirectory.value / "scalastyle-test-config.xml"

This is useful when you want to loosen the checks in Test scope.

Unfortunately, IntelliJ ignores this setting and looks for the file in it's default location.

Is there a way to fix this?

答:
This is currently not possible, the locations are hard-coded. I've created an issue for you:
https://youtrack.jetbrains.com/issue/SCL-12086</p>


问:
Comparing tables in MySQL and adding a yes/no response
Can someone help me tweak my SQL to get the desired result. I have a table of users, a table of cases, and a relationship table for users attached to cases.

Users Table - users

```<code>+----+-------+--------+
| id | first |  last  |
+----+-------+--------+
|  1 | Joe   | Bloggs |
|  2 | John  | Doe    |
|  3 | Jane  | Doe    |
|  4 | Dave  | Smith  |
+----+-------+--------+
</code>```

Case Table - cases

```<code>+----+--------+------+
| id |  Case  | Code |
+----+--------+------+
|  1 | Case 1 | C1   |
|  2 | Case 2 | C2   |
|  3 | Case 3 | C3   |
+----+--------+------+
</code>```

Case Users Table - case_users

```<code>+----+---------+---------+
| id | case_id | user_id |
+----+---------+---------+
|  1 |       1 |       1 |
|  2 |       1 |       2 |
|  3 |       2 |       4 |
|  4 |       3 |       1 |
|  5 |       1 |       4 |
+----+---------+---------+
</code>```

I want to query the database to return me a full list of users and return a yes or no if they are linked to case 1 and then case 2 case 3 etc.

The SQL I've got so far (selecting for Case ID 1) returns all users but is assigning 'no' to everyone:

```<code>SELECT
    users.first,
    users.last,
    CASE WHEN case_users.case_id IS NULL THEN 'N' ELSE 'Y' END AS 'yes/no'
FROM
    users
        LEFT OUTER JOIN case_users ON case_users.case_id = 1
</code>```

My actual result is:

```<code>+-------+--------+--------+
| First |  Last  | Yes/No |
+-------+--------+--------+
| Joe   | Bloggs | Y      |
| John  | Doe    | Y      |
| Jane  | Doe    | Y      |
| Dave  | Smith  | Y      |
+-------+--------+--------+
</code>```

My desired result should be:

```<code>+-------+--------+--------+
| First |  Last  | Yes/No |
+-------+--------+--------+
| Joe   | Bloggs | Y      |
| John  | Doe    | Y      |
| Jane  | Doe    | N      |
| Dave  | Smith  | Y      |
+-------+--------+--------+
</code>```

Can someone help me as I can't get the desired result?

答:
You're missing the join condition from users to case_users:</p>

```<code>SELECT
        users.first,
        users.last,
    CASE WHEN case_users.case_id IS NULL THEN 'N' ELSE 'Y' END AS 'yes/no'
FROM
    users
        LEFT OUTER JOIN case_users ON users.id = case_users.user_id AND case_users.case_id = 1
</code>```

Body:
Can someone help me tweak my SQL to get the desired result. I have a table of users, a table of cases, and a relationship table for users attached to cases.

Users Table - users

+----+-------+--------+
| id | first |  last  |
+----+-------+--------+
|  1 | Joe   | Bloggs |
|  2 | John  | Doe    |
|  3 | Jane  | Doe    |
|  4 | Dave  | Smith  |
+----+-------+--------+

Case Table - cases

+----+--------+------+
| id |  Case  | Code |
+----+--------+------+
|  1 | Case 1 | C1   |
|  2 | Case 2 | C2   |
|  3 | Case 3 | C3   |
+----+--------+------+

Case Users Table - case_users

+----+---------+---------+
| id | case_id | user_id |
+----+---------+---------+
|  1 |       1 |       1 |
|  2 |       1 |       2 |
|  3 |       2 |       4 |
|  4 |       3 |       1 |
|  5 |       1 |       4 |
+----+---------+---------+

I want to query the database to return me a full list of users and return a yes or no if they are linked to case 1 and then case 2 case 3 etc.

The SQL I've got so far (selecting for Case ID 1) returns all users but is assigning 'no' to everyone:

SELECT
    users.first,
    users.last,
    CASE WHEN case_users.case_id IS NULL THEN 'N' ELSE 'Y' END AS 'yes/no'
FROM
    users
        LEFT OUTER JOIN case_users ON case_users.case_id = 1

My actual result is:

+-------+--------+--------+
| First |  Last  | Yes/No |
+-------+--------+--------+
| Joe   | Bloggs | Y      |
| John  | Doe    | Y      |
| Jane  | Doe    | Y      |
| Dave  | Smith  | Y      |
+-------+--------+--------+

My desired result should be:

+-------+--------+--------+
| First |  Last  | Yes/No |
+-------+--------+--------+
| Joe   | Bloggs | Y      |
| John  | Doe    | Y      |
| Jane  | Doe    | N      |
| Dave  | Smith  | Y      |
+-------+--------+--------+

Can someone help me as I can't get the desired result?

Body:
You're missing the join condition from users to case_users:

SELECT
        users.first,
        users.last,
    CASE WHEN case_users.case_id IS NULL THEN 'N' ELSE 'Y' END AS 'yes/no'
FROM
    users
        LEFT OUTER JOIN case_users ON users.id = case_users.user_id AND case_users.case_id = 1


问:
Upgrading Selenium 2.53 to 3.4.0
What are all the steps I have to follow while upgrading to latest selenium version.

I am using Selenium 2.53 and configured the same in Eclipse. Changing just  selenium jar files will work? or any other process I have to follow?

答:
You can follow following steps:

1] Remove old Selenium jars by selecting from Properties->Java Build Path->Add External JARs

2] Download latest selenium jars from Selenium download

3] Add the latest selenium jar to the referenced lib by going to Properties->Java Build Path->Add External JARs

4] Download latest Geckodriver from here

5] And rest things are same. Just you need to specify the Geckodriver path into your code like this :

```<code>System.setProperty("webdriver.gecko.driver", "D:\\\\Library\\drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
</code>```

Hope it will help you.

Title: Upgrading Selenium 2.53 to 3.4.0

Body:
You can follow following steps:

1] Remove old Selenium jars by selecting from Properties->Java Build Path->Add External JARs

2] Download latest selenium jars from Selenium download

3] Add the latest selenium jar to the referenced lib by going to Properties->Java Build Path->Add External JARs

4] Download latest Geckodriver from here

5] And rest things are same. Just you need to specify the Geckodriver path into your code like this :

System.setProperty("webdriver.gecko.driver", "D:\\\\Library\\drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

Hope it will help you.


问:
Email validation, using if else statements wont allow it to continue checking if there was an error with the first if?
I have:

```<code>if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'<span class="error">ERROR: Missing Name </span><br/>';
    } else if(empty($phone) || empty($email)) {
        echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'<span id="valid">Message has been sent</span><br/>';
    }
}
</code>```

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you

答:
Try this:</p>

```<code>if(isset($_POST['submit'])) {
    $errors = array();

    if (empty($name)) {
        $errors[] = 'Missing Name';
    }
    if(empty($phone) || empty($email)) {
        $errors[] = 'You must insert a phone number or email';
    }
    if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        $errors[] = 'Please Insert a valid Email';
    }

    if (!empty($errors)) {
        for ($i = 0; i < count($errors); $i++) {
            echo sprintf('<span class="error">ERROR: %s</span><br/>', $errors[$i]);
        }
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
                                            "Name: $name
                                             Email: $email
                                             Phone Number: $phone
                                             Comment: $comment", "From: $email" );
        echo'<span id="valid">Message has been sent</span><br/>';
     }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have:

if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'ERROR: Missing Name
';
    } else if(empty($phone) || empty($email)) {
        echo'ERROR: You must insert a phone number or email
';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'ERROR: Please Insert a valid Email
';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'Message has been sent
';
    }
}

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you

Body:
Try this:

if(isset($_POST['submit'])) {
    $errors = array();

    if (empty($name)) {
        $errors[] = 'Missing Name';
    }
    if(empty($phone) || empty($email)) {
        $errors[] = 'You must insert a phone number or email';
    }
    if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        $errors[] = 'Please Insert a valid Email';
    }

    if (!empty($errors)) {
        for ($i = 0; i < count($errors); $i++) {
            echo sprintf('<span class="error">ERROR: %s</span><br/>', $errors[$i]);
        }
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
                                            "Name: $name
                                             Email: $email
                                             Phone Number: $phone
                                             Comment: $comment", "From: $email" );
        echo'<span id="valid">Message has been sent</span><br/>';
     }
}


问:
get serializearray() elements with ajax and node js
I would like to get input elements from my form to node js:

Client Side

```<code>var ss =( $('#addform').serializeArray() );
var url= 'http://localhost:8181/add';
    $.ajax({
        url:url,
        type: 'POST',
        dataType: "json",
        data:{ss:ss},
        success: function(json){
            alert("done");
    },
    error: function(jqXHR, textStatus, err) {
        alert('text status '+textStatus+', err '+err)
    }
});
</code>```

[Object, Object, Object, Object, Object, Object, Object]

Server Side:

```<code>router.route('/adduser')
.post(function(req, res) {
  res.header("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      console.log(req.body);
      console.log(req.body.name);
}
</code>```

Result:

```<code>{ ss:
   [ { name: 'name', value: 'a' },
     { name: 'lastname', value: 'a' },
     { name: 'email', value: 'a' },
     { name: 'password', value: 'a' },
     { name: 'password2', value: 'a' },
     { name: 'country', value: 'a' },
     { name: 'phone', value: 'a' } ] }
</code>```

console.log(req.body.name); returns undefined

How can I get elements of these objects in server side ?

答:
SS variable is an array of objects. So you have to iterate over the object with loops.</p>

```<code>var data = req.body.ss;
    for(var i in data){
          console.log(data[i].name);
    }
</code>```

Body:
I would like to get input elements from my form to node js:

Client Side

var ss =( $('#addform').serializeArray() );
var url= 'http://localhost:8181/add';
    $.ajax({
        url:url,
        type: 'POST',
        dataType: "json",
        data:{ss:ss},
        success: function(json){
            alert("done");
    },
    error: function(jqXHR, textStatus, err) {
        alert('text status '+textStatus+', err '+err)
    }
});

[Object, Object, Object, Object, Object, Object, Object]

Server Side:

router.route('/adduser')
.post(function(req, res) {
  res.header("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      console.log(req.body);
      console.log(req.body.name);
}

Result:

{ ss:
   [ { name: 'name', value: 'a' },
     { name: 'lastname', value: 'a' },
     { name: 'email', value: 'a' },
     { name: 'password', value: 'a' },
     { name: 'password2', value: 'a' },
     { name: 'country', value: 'a' },
     { name: 'phone', value: 'a' } ] }

console.log(req.body.name); returns undefined

How can I get elements of these objects in server side ?

Body:
SS variable is an array of objects. So you have to iterate over the object with loops.

var data = req.body.ss;
    for(var i in data){
          console.log(data[i].name);
    }


问:
Force HTTPS using Redirect in .htaccess
I've recently tried to force HTTPS on my website by using various directives contained in mod_rewrite. However it didn't workout very well and now it's recommented to use the Redirect directive from mod_alias. I've got everything in a subfolder and I wrote:

```<code>Redirect "/folder/" "https://mywebsite.org/folder/"
</code>```

in my .htaccess file, but it keeps giving me the ERR_TOO_MANY_REDIRECTS error.

答:
This code in .htaccess will redirect http://example.com to https://example.com </p>

```<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

Title: Force HTTPS using Redirect in .htaccess

Body:
I've recently tried to force HTTPS on my website by using various directives contained in mod_rewrite. However it didn't workout very well and now it's recommented to use the Redirect directive from mod_alias. I've got everything in a subfolder and I wrote:

Redirect "/folder/" "https://mywebsite.org/folder/"

in my .htaccess file, but it keeps giving me the ERR_TOO_MANY_REDIRECTS error.

Body:
This code in .htaccess will redirect http://example.com to https://example.com

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


问:
Why use apps.get_model() when creating a data migration?
As per the django docs when creating django migrations we should use apps.get_model() rather than importing the models and using them.

Why does a data migration have to use the historical version of a model rather than the latest one?(The historical versions of the model will not be in use anyways right?)

答:
Consider this model:

```<code>class A(models.Model):
    field1 = models.PositiveIntegerField()
    field2 = models.PositiveIntegerField()
</code>```

Your migration history knows about these two fields and any further migration will consider this model state and will make changes to this model state.

Now suppose, you remove field1 and your model becomes:

```<code>class A(models.Model):
    field2 = models.PositiveIntegerField()
</code>```

And in the migration, you try to use field1, django should know that field1 existed. Hence when we use apps.get_model(), it helps django use the previous migrations history and infer about field1. Otherwise you will get an error.

Body:
Consider this model:

class A(models.Model):
    field1 = models.PositiveIntegerField()
    field2 = models.PositiveIntegerField()

Your migration history knows about these two fields and any further migration will consider this model state and will make changes to this model state.

Now suppose, you remove field1 and your model becomes:

class A(models.Model):
    field2 = models.PositiveIntegerField()

And in the migration, you try to use field1, django should know that field1 existed. Hence when we use apps.get_model(), it helps django use the previous migrations history and infer about field1. Otherwise you will get an error.


问:
How can I write a list of objects to firebase?
I am trying to write multiple nodes at one go in Firebase, my data class

```<code>@IgnoreExtraProperties
public class Data{
    public String desc;
    public double id;
    public data(String desc,double id) {
        this.id=id;
        this.desc=desc;
    }
}
</code>```

And I am trying this

```<code>   .....//firebase auth ok

    ArrayList<Data> mydata= new ArrayList<>();
    mydata.add(new Items("data1",1));
    mydata.add(new Items("data2",2));
    mDatabase.child("DATA").setValue(mydata);
</code>```

But this fails as firebase doesn't support Listarray I guess, as I am getting the error

com.google.firebase.database.DatabaseException: No properties to
  serialize found on class android.support.v4.app.LoaderManagerImpl

答:
I think the problem is you are directly setting value at the root level.
Just Try by creating another child inside the root node.</p>

```<code>List<Data> mydata= new ArrayList<>();
mydata.add(new Data("data1",1));
mydata.add(new Data("data2",2));
mDatabase.child("DATA").child("CHILD NAME").setValue(mydata);
</code>```

Body:
I am trying to write multiple nodes at one go in Firebase, my data class

@IgnoreExtraProperties
public class Data{
    public String desc;
    public double id;
    public data(String desc,double id) {
        this.id=id;
        this.desc=desc;
    }
}

And I am trying this

   .....//firebase auth ok

    ArrayList<Data> mydata= new ArrayList<>();
    mydata.add(new Items("data1",1));
    mydata.add(new Items("data2",2));
    mDatabase.child("DATA").setValue(mydata);

But this fails as firebase doesn't support Listarray I guess, as I am getting the error

com.google.firebase.database.DatabaseException: No properties to
  serialize found on class android.support.v4.app.LoaderManagerImpl

Body:
I think the problem is you are directly setting value at the root level.
Just Try by creating another child inside the root node.

List<Data> mydata= new ArrayList<>();
mydata.add(new Data("data1",1));
mydata.add(new Data("data2",2));
mDatabase.child("DATA").child("CHILD NAME").setValue(mydata);


问:
tcp/ip monitor
in eclipse, i have a weblogic server running, and a j2ee application deployed to it.
the application is serving on port 7001.
i want to hook the monitor up to the application, i do not know what ports to use.
i think i know what to put in for the Host Name (localhost:7001), but not sure of what to use for type and Local Port. in the proeferences, what is meant by Local Port.
does it matter if i start the monitor before or after the application is running?
my goal is the watch the traffic as i login, from my local machine via a browser, and surf to other parts of the application.
thanks for any help</p>

答:
The monitor basically acts as a proxy. The local monitoring port is the port you will send requests to the monitor on. It can be any free port (7002, for example).

The host name, port, and type describe what you want the monitor to proxy to. In your case, it would be localhost, 7001, and HTTP.

Then, you would use your browser to access localhost:7002, and the proxied requests and responses would be displayed in the monitor.

Title: tcp/ip monitor

LastEditorDisplayName: phihag

OwnerDisplayName: Jordan Liggitt


问:
How to design a method that contains lots of IF's or Switch statements
How can i make the design of this class more dynamic so i can add new extensions and types as required.

```<code>public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}
</code>```

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

```<code>else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}
</code>```

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

答:
One way might be to build a table (list), where each item contains the extension along with information about what to do with names with that extension.

You can then write a simple loop, that compares against each extension in the table.

If what you do with each extension is complex and can't be defined in a simple table, then you could instead include a delegate. When the loop finds the matching extension, it could call the corresponding delegate to process the name.

Body:
How can i make the design of this class more dynamic so i can add new extensions and types as required.

public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers


问:
I want to print PHP query with parameters
I have the following code

```<code>$name = 'myname';
$mail = 'my@mail.it';
$qwt = "INSERT INTO `agenz` (`name`, `email`) VALUES (?,?)";
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $name, $mail);
$result->execute();
</code>```

I want print the query

```<code>"INSERT INTO `agenz` (`name`, `email`) VALUES ('myname','my@mail.it')"
</code>```

for creating a log.So how to do that?

thanx.

答:
You can use variable directly in the statement like following</p>

```<code>$name="ABC";
$mail="me@someone.com";
$value= "I am $name mail id $mail";
</code>```

Body:
I have the following code

$name = 'myname';
$mail = 'my@mail.it';
$qwt = "INSERT INTO `agenz` (`name`, `email`) VALUES (?,?)";
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $name, $mail);
$result->execute();

I want print the query

"INSERT INTO `agenz` (`name`, `email`) VALUES ('myname','my@mail.it')"

for creating a log.So how to do that?

thanx.

Body:
You can use variable directly in the statement like following

$name="ABC";
$mail="me@someone.com";
$value= "I am $name mail id $mail";


问:
save checked items from CheckedListBox selected Items to .txt file
i'm new to c# and windows form application.
i want to save to save selected items from checkedlistbox to a .txt file if not exist then create, if exist then append.

here's how i bind the data to my checkedlistbox, i'm not sure if this is the right way, or there's another way to add value to checkedboxlist.

```<code>public void bind_clbDepartment()
    {
        DataSet ds = DataBank3.get_department();
        DataTable dt = ds.Tables[0];

        foreach (DataRow drow in dt.Rows)
        {
            clbDepartment.Items.Add(drow["id_dept"] + ":" + drow["name_dept"]);
        }
    }

private void Save_Click(object sender, EventArgs e)
        {
            //save selected items from clbDepartment to D:\test.txt
            //create if not exist, append if exist
        }
</code>```

答:
You can try the following.

Add this using at the beginning of you class code:

```<code>using System.IO;
</code>```

And add this code where you want to write the selected checkboxes' values to your file:

```<code>string path = "<path to file>";

foreach (ListItem item in clbDepartment.CheckBoxes.Items)
   if (item.Selected)
      File.AppendAllText(path, item.Value);
</code>```

Body:
i'm new to c# and windows form application.
i want to save to save selected items from checkedlistbox to a .txt file if not exist then create, if exist then append.

here's how i bind the data to my checkedlistbox, i'm not sure if this is the right way, or there's another way to add value to checkedboxlist.

public void bind_clbDepartment()
    {
        DataSet ds = DataBank3.get_department();
        DataTable dt = ds.Tables[0];

        foreach (DataRow drow in dt.Rows)
        {
            clbDepartment.Items.Add(drow["id_dept"] + ":" + drow["name_dept"]);
        }
    }

private void Save_Click(object sender, EventArgs e)
        {
            //save selected items from clbDepartment to D:\test.txt
            //create if not exist, append if exist
        }

Body:
You can try the following.

Add this using at the beginning of you class code:

using System.IO;

And add this code where you want to write the selected checkboxes' values to your file:

string path = "<path to file>";

foreach (ListItem item in clbDepartment.CheckBoxes.Items)
   if (item.Selected)
      File.AppendAllText(path, item.Value);


问:
SQL - Combine multiple text records to one
I want to combine multiple text records to one.
I have a table with data like this:

```<code>+----+---------+
| id | comment |
+----+---------+
| 1  | Peter   |
| 2  | is      |
| 3  | stupid  |
+----+---------+
</code>```

I want Peter is stupid as output.

Do you have any idea?

I am sorry for my bad SQl knowledge.

答:
You can use GROUP_CONCAT.</p>

```<code>SELECT comment GROUP_CONCAT(comment SEPARATOR ' ')
FROM table_name
</code>```

Body:
I want to combine multiple text records to one.
I have a table with data like this:

+----+---------+
| id | comment |
+----+---------+
| 1  | Peter   |
| 2  | is      |
| 3  | stupid  |
+----+---------+

I want Peter is stupid as output.

Do you have any idea?

I am sorry for my bad SQl knowledge.

Body:
You can use GROUP_CONCAT.

SELECT comment GROUP_CONCAT(comment SEPARATOR ' ')
FROM table_name


问:
if null replace with 0, otherwise default value in same column
In SparkR shell 1.5.0, Created a sample data set:

```<code>df_test <- createDataFrame(sqlContext, data.frame(mon = c(1,2,3,4,5), year = c(2011,2012,2013,2014,2015)))
df_test1 <- createDataFrame(sqlContext, data.frame(mon1 = c(1,2,3,4,5,6,7,8)))
df_test2 <- join(df_test1, df_test, joinExpr = df_test1$mon1 == df_test$mon, joinType = "left_outer")
</code>```

data set : df_test2

```<code>+----+----+------+
|mon1| mon|  year|
+----+----+------+
| 7.0|null|  null|
| 1.0| 1.0|2011.0|
| 6.0|null|  null|
| 3.0| 3.0|2013.0|
| 5.0| 5.0|2015.0|
| 8.0|null|  null|
| 4.0| 4.0|2014.0|
| 2.0| 2.0|2012.0|
+----+----+------+
</code>```

Question: If there is null how can I replace it with 0 in column df_test2$year or else use a default value?

The output should look like this,

```<code>+----+----+------+
|mon1| mon|  year|
+----+----+------+
| 7.0|null|  0   |
| 1.0| 1.0|2011.0|
| 6.0|null|  0   |
| 3.0| 3.0|2013.0|
| 5.0| 5.0|2015.0|
| 8.0|null|  0   |
| 4.0| 4.0|2014.0|
| 2.0| 2.0|2012.0|
+----+----+------+
</code>```

I have used otherwise/when, but doesn't work

```<code>df_test2$year <- otherwise(when(isNull(df_test2$year), 0 ), df_test2$year)
</code>```

It throw ed error,

```<code>Error in rep(yes, length.out = length(ans)) :
  attempt to replicate an object of type 'environment'
</code>```

答:
```<code>df_test2$year <- ifelse(isNull(df_test2$year), 0, df_test2$year)
</code>```

Pure SparkR code that resolves the problem.

Body:
In SparkR shell 1.5.0, Created a sample data set:

df_test <- createDataFrame(sqlContext, data.frame(mon = c(1,2,3,4,5), year = c(2011,2012,2013,2014,2015)))
df_test1 <- createDataFrame(sqlContext, data.frame(mon1 = c(1,2,3,4,5,6,7,8)))
df_test2 <- join(df_test1, df_test, joinExpr = df_test1$mon1 == df_test$mon, joinType = "left_outer")

data set : df_test2

+----+----+------+
|mon1| mon|  year|
+----+----+------+
| 7.0|null|  null|
| 1.0| 1.0|2011.0|
| 6.0|null|  null|
| 3.0| 3.0|2013.0|
| 5.0| 5.0|2015.0|
| 8.0|null|  null|
| 4.0| 4.0|2014.0|
| 2.0| 2.0|2012.0|
+----+----+------+

Question: If there is null how can I replace it with 0 in column df_test2$year or else use a default value?

The output should look like this,

+----+----+------+
|mon1| mon|  year|
+----+----+------+
| 7.0|null|  0   |
| 1.0| 1.0|2011.0|
| 6.0|null|  0   |
| 3.0| 3.0|2013.0|
| 5.0| 5.0|2015.0|
| 8.0|null|  0   |
| 4.0| 4.0|2014.0|
| 2.0| 2.0|2012.0|
+----+----+------+

I have used otherwise/when, but doesn't work

df_test2$year <- otherwise(when(isNull(df_test2$year), 0 ), df_test2$year)

It throw ed error,

Error in rep(yes, length.out = length(ans)) :
  attempt to replicate an object of type 'environment'

Body:
df_test2$year <- ifelse(isNull(df_test2$year), 0, df_test2$year)

Pure SparkR code that resolves the problem.


问:
Duplicate Symbols for Architecture arm64
When I try running my Xcode Project it fails with an error stating that I have duplicate symbols. I looked online where the find these duplicates but have had no luck:

Any ideas how to fix this?

答:
Below Patch work for me..:)

```<code>Step 1: Go to TARGETS -> Build Settings -> No Common Blocks -> No

Step 2: Go to TARGETS -> Build Settings -> enable testability -> No
</code>```

Setting it back to NO solved the problem!

Body:
Below Patch work for me..:)

Step 1: Go to TARGETS -> Build Settings -> No Common Blocks -> No

Step 2: Go to TARGETS -> Build Settings -> enable testability -> No

Setting it back to NO solved the problem!


问:
How to extract and split a string in multiple parts
I would like to search and split different files in a directory based on some pattern  which may contain different file formats:

```<code>/path/

somefile.txt 2010-01-01
file.txt 2010-01-02
f.txt 2010-01-03
test.txt 2010-01-04
photo.jpg 2010-01-04
script.py  2010-01-05
</code>```

In order to get:

```<code>somefile.txt
file.txt
f.txt
test.txt
</code>```

Here first I would like to catch all files which contains .txt and split them accordingly:

```<code>def catch_txt(path):
    result = [os.path.join(path, f) for f in os.listdir(path) if
re.search(r"\w+\.\w+\txt", f)]
    splitted_result = [files for files in result if
re.split(r"\w+\.\w+\txt", f)]
    # some other stuff
    return splitted_result
</code>```

But only gives a emtpy list.

答:
You can use list comprehension to get the .txt : </p>

```<code>res = [ i.split(" ")[0] for i in os.listdir(path) if '.txt' in i ]
</code>```

Body:
I would like to search and split different files in a directory based on some pattern  which may contain different file formats:

/path/

somefile.txt 2010-01-01
file.txt 2010-01-02
f.txt 2010-01-03
test.txt 2010-01-04
photo.jpg 2010-01-04
script.py  2010-01-05

In order to get:

somefile.txt
file.txt
f.txt
test.txt

Here first I would like to catch all files which contains .txt and split them accordingly:

def catch_txt(path):
    result = [os.path.join(path, f) for f in os.listdir(path) if
re.search(r"\w+\.\w+\txt", f)]
    splitted_result = [files for files in result if
re.split(r"\w+\.\w+\txt", f)]
    # some other stuff
    return splitted_result

But only gives a emtpy list.

Body:
You can use list comprehension to get the .txt :

res = [ i.split(" ")[0] for i in os.listdir(path) if '.txt' in i ]


问:
angular - create a new line on HTML
I have a simple question (I hope this). I have a service that return a string as result. The format is something like this:

"
Test1: the association has been accepted.\nTest2: the association has been accepted.\n"
"

On the client side (I'm using Angular 1.5.x) I put that string into a object (say the variable $scope.alert.message). After that I want to print that string in a modal. My html is:

```<code><script type="text/ng-template" id="infoTemplate.html">
    <div class="modal-header left" ng-class="['div-' + alert.type, closeable ? 'alert-dismissible' : null]">
        <h3 class="modal-title" id="modal-title">Info</h3>
    </div>
    <div class="modal-body" id="modal-body">
        <img class="imm-info" ng-class="['imm-' + alert.type, closeable ? 'alert-dismissible' : null]" />
        <p class="col-sm-10 col-sm-offset-2">{{alert.message}}</p><button class="col-sm-3 col-sm-offset-5 btn " ng-class="['button-' + alert.type, closeable ? 'alert-dismissible' : null]" ng-click="cancel()">OK</button>
    </div>
</script>
</code>```

You can see the '{{alert.message}}'. My problem is that my message "doesn't display" the character '\n'. So it doesn't create more than one line. An example here:

example

答:
Try this in HTML:

```<code>```{{ alert.message }}```
</code>```

Already answered here:

The
 wrapper will print text with \n as text

Title: angular - create a new line on HTML

Body:
I have a simple question (I hope this). I have a service that return a string as result. The format is something like this:

"
Test1: the association has been accepted.\nTest2: the association has been accepted.\n"
"

On the client side (I'm using Angular 1.5.x) I put that string into a object (say the variable $scope.alert.message). After that I want to print that string in a modal. My html is:

You can see the '{{alert.message}}'. My problem is that my message "doesn't display" the character '\n'. So it doesn't create more than one line. An example here:

example

Body:
Try this in HTML:

<pre>{{ alert.message }}</pre>

Already answered here:

The < pre > wrapper will print text with \n as text


问:
Qt: Force size of QDockWidget
I have a QMainWindow with a center widget and a number of dockable widgets. The size of the various widgets get manipulated by the sliders between the dockables. I would like to fix the  center widget's height to it's minimumSize height and not allow it to be made larger by the user. The width should remain relative to the QMainWindow (I only allow top and bottom dockables, so the center widget is stretched to the width of the main window).

The center widget is a QDockWidget, containing a QWidget with a QVBoxLayout (containing more stuff).

I have tried deriving from the QVBoxLayout and overriding maximumSize, but it wasn't respected. Overriding expandingDirections also didn't make any difference.

Any advise on how to achieve this?

答:
Got it, thanks to Johannes Schaub.

I thought the QDockWidget propagates the constraints to its contained widget, which it does not. Setting maximumHeight on the inner Widget does the trick.

Title: Qt: Force size of QDockWidget


问:
repeating background image which is from 'image map' using CSS
I have a image map (sorry for sloppy drawing...)

The number means x-coordinate, y-coordinate, width, height.
For example, 5, 5, 25, 25 means that this image is located at (5, 5) and has width 25px and height 25px.

(the last image's size is wrong. 100, 5, 5, 25 is correct size.

And I want to make

using above image map with width 100px and height 25px.

At this time, I use image map as following.

```<code>#aDiv {
    width: 25px; height 25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}
</code>```

with one tag

```<code><div></div>
</code>```

for background.

But I have no idea that making something like second image using first image (image map).
How can I do this?

The above code is what I have done. I have no idea totally. The last idea I have is

```<code>#one {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}

#two {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-100px -5px;
}

#three {
    display:inline-block;
    width:5px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-50px -5px;
}

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</code>```

But in this way, the total width is just 75 pixel. I need to repeat #two, i.e., repeating the third drawing of image map.

答:
As it is difficult to fully understand what you want, here is 2 versions, so we get some visuals from where to work out a proper solution.

Note, I added a border around each div so one easily see how they split/position the image map

Sample 1: 3 div's using the same map, positioned so it still looks as 1, where the second is twice the width as the rest.

div {
    float: left;                /* temp, to set them side by side  */
    border: 1px solid black;    /* temp. for demo purpose          */
    width: 100px;
    height: 100px;
    background-size: 400px 100px;
    background-repeat: no-repeat;
    background-image: url(https://i.stack.imgur.com/Qsnl6.png);
    background-position: 0 0;
}
div:nth-child(2) {
    width: 200px;
    background-position: -100px 0;
}
div:nth-child(3) {
    background-position: -300px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div>
<div></div>
<div></div></code>```

Sample 2: With 4 div's instead.

div {
    float: left;                /* temp, to set them side by side  */
    border: 1px solid black;    /* temp. for demo purpose          */
    width: 100px;
    height: 100px;
    background-size: 400px 100px;
    background-repeat: no-repeat;
    background-image: url(https://i.stack.imgur.com/Qsnl6.png);
    background-position: 0 0;
}
div:nth-child(2) {
    background-position: -100px 0;
}
div:nth-child(3) {
    background-position: -200px 0;
}
div:nth-child(4) {
    background-position: -300px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div>
<div></div>
<div></div>
<div></div></code>```

Body:
I have a image map (sorry for sloppy drawing...)

The number means x-coordinate, y-coordinate, width, height.
For example, 5, 5, 25, 25 means that this image is located at (5, 5) and has width 25px and height 25px.

(the last image's size is wrong. 100, 5, 5, 25 is correct size.

And I want to make

using above image map with width 100px and height 25px.

At this time, I use image map as following.

#aDiv {
    width: 25px; height 25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}

with one tag

for background.

But I have no idea that making something like second image using first image (image map).
How can I do this?

The above code is what I have done. I have no idea totally. The last idea I have is

#one {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}

#two {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-100px -5px;
}

#three {
    display:inline-block;
    width:5px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-50px -5px;
}

But in this way, the total width is just 75 pixel. I need to repeat #two, i.e., repeating the third drawing of image map.

Body:
As it is difficult to fully understand what you want, here is 2 versions, so we get some visuals from where to work out a proper solution.

Note, I added a border around each div so one easily see how they split/position the image map

Sample 1: 3 div's using the same map, positioned so it still looks as 1, where the second is twice the width as the rest.

div {
    float: left;                /* temp, to set them side by side  */
    border: 1px solid black;    /* temp. for demo purpose          */
    width: 100px;
    height: 100px;
    background-size: 400px 100px;
    background-repeat: no-repeat;
    background-image: url(https://i.stack.imgur.com/Qsnl6.png);
    background-position: 0 0;
}
div:nth-child(2) {
    width: 200px;
    background-position: -100px 0;
}
div:nth-child(3) {
    background-position: -300px 0;
}

<div></div>
<div></div>
<div></div>

Sample 2: With 4 div's instead.

div {
    float: left;                /* temp, to set them side by side  */
    border: 1px solid black;    /* temp. for demo purpose          */
    width: 100px;
    height: 100px;
    background-size: 400px 100px;
    background-repeat: no-repeat;
    background-image: url(https://i.stack.imgur.com/Qsnl6.png);
    background-position: 0 0;
}
div:nth-child(2) {
    background-position: -100px 0;
}
div:nth-child(3) {
    background-position: -200px 0;
}
div:nth-child(4) {
    background-position: -300px 0;
}

<div></div>
<div></div>
<div></div>
<div></div>


问:
WebStorm and jsdoc3, defining allowed parameters doesn't work?
Based on the documentation, the JSDoc implementation in WebStorm seems to be very limited. Is there anyway to extend it? I can't find any plugins.

Specifically, I would like "allowed parameters" to work (as implemented 2014-04-11)

答:
they do work - if the argument doesn't match the value specified in @param annotation, WebStorm shows type mismatch warning:

But parameter hint shows expected parameter type, not value


问:
Upload Error - Cannot upload apk file to Google Play Developer Console?
I have some apps in Google Play for some time but I have not been sending updates for a few months. Now I am trying to send an update but I am getting Upload Error as I upload the apk file. I have tried with another app and also with another computer but the same error occurs. I have been trying to solve this issue for 5 past days but I could not find any related resource or same issue occurring with anybody else. I cannot figure out if the problem is due to the new Google Play Developer Console features or anything else. Any help or suggestion from the community is welcomed. Thank you in advance.

This is how the "Upload new APK to Production" screen looks after I browse-upload the apk.

Upload new APK to Production

Upload failed

UPLOAD ANOTHER APK

答: The problem is solved. It seems to be caused by some cookies etc. I have tried uploading my apk in browser's incognito mode and had success.</p>


问:
C# JSON Custom Result List Name
How can I override C#'s JSON response from <MethodName>Results to the class name?

It always returns the methodname+Results.  Is there a way for me to change it to the classname instead?

Or am I doing something wrong on my code?

Here's my Exchange_Reason class

```<code>[DataContract]
public class Exchange_Reason
{
    [DataMember]
    public string Exchange_Reason_ID { get; set; }

    [DataMember]
    public string Reason { get; set; }

    [DataMember]
    public string Status { get; set; }
}
</code>```

My Service Contract

```<code>[OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "getExchange_Reason_List")]
    List<Exchange_Reason> GetExchange_Reason_List();
</code>```

The implementation

```<code>public List<Exchange_Reason> GetExchange_Reason_List()
{
     List<Exchange_Reason> results = new List<Exchange_Reason>();
     ...
     while (reader.Read())
     {
           results.Add(new Exchange_Reason()
           {
                 Exchange_Reason_ID = reader["Exchange_Reason_ID"].ToString(),
                 Reason = reader["Reason"].ToString(),
                 Status = reader["Status"].ToString()
           });
     }
     return results;
}
</code>```

And the results

```<code>{
    GetExchange_Reason_ListResult: [
        {
            Exchange_Reason_ID: "1000001",
            Reason: "Rotten",
            Status: "Active"
        },
        {
            Exchange_Reason_ID: "1000002",
            Reason: "Expired",
            Status: "Active"
        }
    ]
}
</code>```

I need it to be:

```<code>{
    Exchange_Reasons: [
        {
            Exchange_Reason_ID: "1000001",
            Reason: "Rotten",
            Status: "Active"
        },
        {
            Exchange_Reason_ID: "1000002",
            Reason: "Expired",
            Status: "Active"
        }
    ]
}
</code>```

Thanks in advance.

答:
that because your BodyStyle is wrapped. at first remove BodyStyle from your WebInvoke then wrap your output the way you want. i assume you want this:

```<code> [DataContract]
public class GetExchange_Reason_ListResult
{
    [DataMember]
    public Exchange_Reason[] Exchange_Reasons { get; set; }
}

public class Exchange_Reason
{
    public string Exchange_Reason_ID { get; set; }
    public string Reason { get; set; }
    public string Status { get; set; }
}
</code>```

your method should be like this:

```<code>[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "getExchange_Reason_List")]
GetExchange_Reason_ListResult GetExchange_Reason_List();
</code>```

Title: C# JSON Custom Result List Name

Body:
How can I override C#'s JSON response from <MethodName>Results to the class name?

It always returns the methodname+Results.  Is there a way for me to change it to the classname instead?

Or am I doing something wrong on my code?

Here's my Exchange_Reason class

[DataContract]
public class Exchange_Reason
{
    [DataMember]
    public string Exchange_Reason_ID { get; set; }

    [DataMember]
    public string Reason { get; set; }

    [DataMember]
    public string Status { get; set; }
}

My Service Contract

[OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "getExchange_Reason_List")]
    List<Exchange_Reason> GetExchange_Reason_List();

The implementation

public List<Exchange_Reason> GetExchange_Reason_List()
{
     List<Exchange_Reason> results = new List<Exchange_Reason>();
     ...
     while (reader.Read())
     {
           results.Add(new Exchange_Reason()
           {
                 Exchange_Reason_ID = reader["Exchange_Reason_ID"].ToString(),
                 Reason = reader["Reason"].ToString(),
                 Status = reader["Status"].ToString()
           });
     }
     return results;
}

And the results

{
    GetExchange_Reason_ListResult: [
        {
            Exchange_Reason_ID: "1000001",
            Reason: "Rotten",
            Status: "Active"
        },
        {
            Exchange_Reason_ID: "1000002",
            Reason: "Expired",
            Status: "Active"
        }
    ]
}

I need it to be:

{
    Exchange_Reasons: [
        {
            Exchange_Reason_ID: "1000001",
            Reason: "Rotten",
            Status: "Active"
        },
        {
            Exchange_Reason_ID: "1000002",
            Reason: "Expired",
            Status: "Active"
        }
    ]
}

Thanks in advance.

Body:
that because your BodyStyle is wrapped. at first remove BodyStyle from your WebInvoke then wrap your output the way you want. i assume you want this:

 [DataContract]
public class GetExchange_Reason_ListResult
{
    [DataMember]
    public Exchange_Reason[] Exchange_Reasons { get; set; }
}

public class Exchange_Reason
{
    public string Exchange_Reason_ID { get; set; }
    public string Reason { get; set; }
    public string Status { get; set; }
}

your method should be like this:

[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "getExchange_Reason_List")]
GetExchange_Reason_ListResult GetExchange_Reason_List();


问:
Pass an id on clicking a div to the modal and display data based on the id inside the modal
This is my MySQL code in which a div is generated automatically:

```<code><?php
    $sql = "select id,city, event_date, capacity, eb_deadline, regular_deadline, venue, earlybirdstudentprice, regularstudentprice, lastminutestudentprice, earlybirdstudentcount, regularstudentcount, lastminutestudentcount, earlybirdproprice, regularproprice, lastminuteproprice, earlybirdprocount, regularprocount, lastminuteprocount from tbl_events";

    $query = mysql_query($sql);

    while ($row = mysql_fetch_array($query)) {

        $id = $row['id'];
        $city = $row['city'];
        $event_date = $row['event_date'];

        $date = date('F d', strtotime($event_date));

        $capacity = $row['capacity'];
        $eb_deadline = $row['eb_deadline'];
        $regular_deadline = $row['regular_deadline'];
        $venue = $row['venue'];
        $earlybirdstudentprice = $row['earlybirdstudentprice'];
        $regularstudentprice = $row['regularstudentprice'];
        $lastminutestudentprice = $row['lastminutestudentprice'];
        $earlybirdstudentcount = $row['earlybirdstudentcount'];
        $regularstudentcount = $row['regularstudentcount'];
        $lastminutestudentcount = $row['lastminutestudentcount'];
        $earlybirdproprice = $row['earlybirdproprice'];
        $regularproprice = $row['regularproprice'];
        $lastminuteproprice = $row['lastminuteproprice'];
        $earlybirdprocount = $row['earlybirdprocount'];
        $regularprocount = $row['regularprocount'];
        $lastminuteprocount = $row['lastminuteprocount'];
?>

<div class="col-sm-4">
    <div class="card">
        <a href="#myModal" role="button" data-toggle="modal">
        <img src="img/bang.png" alt="Avatar" style="width:100%"></a>
        <h4><b><?php echo $date; ?>, <?php echo $city; ?></b></h4>
    </div>
</div>

<?php
}
?>
</code>```

Now upon clicking on the div, I want to pass the id of the data displayed in that div to the modal and fetch data based on it to display it inside the modal. My modal code is:

```<code><div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog" align="center">

    <!-- Modal content-->
    <div class="modal-content" align="center">
      <div class="modal-header" align="center">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <!-- <h2 class="modal-title">You're buying Tickets for</h2><br> -->
        <h1 class="modal-title"><br>3D Printing Workshop</h1><br>
        <h4 class="modal-title">July 14, Mumbai</h4>
        <h5 class="modal-title">9.30 AM - 4.30 PM</h5><br>
        <h5 class="modal-title">iKeva, Lower Ground 2, Art Guild House, Phoenix Market City, Mumbai 123456</h5>
      </div>
      <div class="modal-body" align="center">

                <div class="container">
    <div class="tabs">
        <div class="col-sm-1"></div>
        <div class="col-sm-8 col-xs-12">
            <div class="title">
                <h2>1. Choose Attendee Type</h2><br>
                <h5><em>Tickets are strictly available on a First Come First Serve Basis only. <br> Students have to provide valid Student ID cards during Check-in</em></h5><br>
            </div>
            <br>
            <ul class="nav nav-tabs nav-justified">
              <li class="active" ><a data-toggle="tab" href="#professionals">Professionals</a></li>
              <li><a data-toggle="tab" href="#students">Students</a></li>
            </ul>
            <br>
            <form>
                <div class="tab-content">
                  <div id="professionals" class="tab-pane fade in active">
                    <table class="table">
                        <tbody>
                            <tr>
                                <td>Early Bird Ticket</td>
                                <td>Ends on Mar 17</td>
                                <td>5 Left</td>
                                <td><select class="form-control" id="tickets">
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>
                                </td>
                                <td>x</td>
                                <td>Rs. 1499/-</td>
                            </tr>
                            <tr>
                                <td>Regular Ticket</td>
                                <td>Ends on Mar 20</td>
                                <td></td>
                                <td><select class="form-control" id="tickets1" disabled>
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>
                                </td>
                                <td>x</td>
                                <td>Rs. 1999/-</td>
                            </tr>
                            <tr>
                                <td>Last Minute Ticket</td>
                                <td>Ends on Mar 24</td>
                                <td></td>
                                <td><select class="form-control" id="tickets2" disabled>
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>
                                </td>
                                <td>x</td>
                                <td>Rs. 2999/-</td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td colspan="4"><hr style="width: 100%; margin-top: 0; margin-bottom: 0"></td>
                            </tr>
                            <tr>
                                <td><input type="text" style="font-size: 12px;" placeholder="Discount Coupon"><button class="btn btn-link">Apply</button></td>
                                <td></td>
                                <td colspan="3"><em>(incl of all taxes)</em></td>
                                <td>Rs. 1998/-</td>
                            </tr>
                        </tbody>
                    </table>
                  </div>
                  <div id="students" class="tab-pane fade">
                    <table class="table">
                        <tbody>
                            <tr>
                                <td>Early Bird Ticket</td>
                                <td>Ends on Mar 17</td>
                                <td>5 Left</td>
                                <td><select class="form-control" id="tickets3">
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>
                                </td>
                                <td>x</td>
                                <td>Rs. 1499/-</td>
                            </tr>
                            <tr>
                                <td>Regular Ticket</td>
                                <td>Ends on Mar 20</td>
                                <td></td>
                                <td><select class="form-control" id="tickets4" disabled>
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>
                                </td>
                                <td>x</td>
                                <td>Rs. 1999/-</td>
                            </tr>
                            <tr>
                                <td>Last Minute Ticket</td>
                                <td>Ends on Mar 24</td>
                                <td></td>
                                <td><select class="form-control" id="tickets5" disabled>
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>
                                </td>
                                <td>x</td>
                                <td>Rs. 2999/-</td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td colspan="4"><hr style="width: 100%; margin-top: 0; margin-bottom: 0"></td>
                            </tr>
                            <tr>
                                <td><input type="text" style="font-size: 12px; text-align: center;" placeholder="Discount Coupon"><button class="btn btn-link">Apply</button></td>
                                <td></td>
                                <td colspan="3"><em>(incl of all taxes)</em></td>
                                <td>Rs. 1998/-</td>
                            </tr>

                        </tbody>
                    </table>
                  </div>
                </div>
                <br>

                    <div class="title">
                        <h2>2. Attendee Details</h2><br>
                        <h5><em>Please enter details of individual Attendee(s). <br> In case of multiple attendees, Billing details should be same as the first Attendee.</em></h5><br>
                    </div>
                    <br>
                    <table class="table" id="attendees">

                        <tbody>
                            <tr>
                            <td><input type="text" class="form-control" name="" placeholder="Name"></td>
                            <td><input type="text" class="form-control" name="" placeholder="Email"></td>
                            <td><input type="text" class="form-control" name="" placeholder="Mobile No."></td>
                            </tr>
                        </tbody>

                    </table>

            </form>
        </div>
    </div>

</div>

        </div>
    </div>
</div>
</div>
</code>```

答:
Wihout the need for all of your code, you can do this quite easily.

```<code><div>
  <div id="hello" style="background-color:red; color :white;text-align:center; padding: 10px;">
  <span id="this">blah blah</span>
  <span id="something">More info</span>
  </div>
</div>
  <hr>
  <div id="modal">
    <div id="here1">Nothing</div>
    <div id="here2">Nohing2</div>
  </div>
</code>```

And use this jQuery to grab the values and populate your modal:

```<code>$('div#hello').click(function(){
  var first= $('#this').html();
  var second= $('#something').html();
  $('#here1').html(first);
  $('#here2').html(second);
});
</code>```

See i in action here: http://jsbin.com/rulaqabane/edit?html,js,output

Fetching your data after that is a separate issue!

Update:

```<code>$('div#hello').click(function(){
      var id= $('#id').html();
      $.get('/my/api/resource', {id: id}, function(data){
            $('#target').html(data.whatever);
      });
    });
</code>```

Body:
This is my MySQL code in which a div is generated automatically:

<?php
    $sql = "select id,city, event_date, capacity, eb_deadline, regular_deadline, venue, earlybirdstudentprice, regularstudentprice, lastminutestudentprice, earlybirdstudentcount, regularstudentcount, lastminutestudentcount, earlybirdproprice, regularproprice, lastminuteproprice, earlybirdprocount, regularprocount, lastminuteprocount from tbl_events";

    $query = mysql_query($sql);

    while ($row = mysql_fetch_array($query)) {

        $id = $row['id'];
        $city = $row['city'];
        $event_date = $row['event_date'];

        $date = date('F d', strtotime($event_date));

        $capacity = $row['capacity'];
        $eb_deadline = $row['eb_deadline'];
        $regular_deadline = $row['regular_deadline'];
        $venue = $row['venue'];
        $earlybirdstudentprice = $row['earlybirdstudentprice'];
        $regularstudentprice = $row['regularstudentprice'];
        $lastminutestudentprice = $row['lastminutestudentprice'];
        $earlybirdstudentcount = $row['earlybirdstudentcount'];
        $regularstudentcount = $row['regularstudentcount'];
        $lastminutestudentcount = $row['lastminutestudentcount'];
        $earlybirdproprice = $row['earlybirdproprice'];
        $regularproprice = $row['regularproprice'];
        $lastminuteproprice = $row['lastminuteproprice'];
        $earlybirdprocount = $row['earlybirdprocount'];
        $regularprocount = $row['regularprocount'];
        $lastminuteprocount = $row['lastminuteprocount'];
?>

<?php echo $date; ?>, <?php echo $city; ?>

<?php
}
?>

Now upon clicking on the div, I want to pass the id of the data displayed in that div to the modal and fetch data based on it to display it inside the modal. My modal code is:

        <button type="button" class="close" data-dismiss="modal">×</button>

3D Printing Workshop

July 14, Mumbai

9.30 AM - 4.30 PM

iKeva, Lower Ground 2, Art Guild House, Phoenix Market City, Mumbai 123456

1. Choose Attendee Type

Tickets are strictly available on a First Come First Serve Basis only.
 Students have to provide valid Student ID cards during Check-in

Professionals

Students

            <form>

                                Early Bird Ticket
                                Ends on Mar 17
                                5 Left
                                <select class="form-control" id="tickets">
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>

                                x
                                Rs. 1499/-

                                Regular Ticket
                                Ends on Mar 20

                                <select class="form-control" id="tickets1" disabled>
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>

                                x
                                Rs. 1999/-

                                Last Minute Ticket
                                Ends on Mar 24

                                <select class="form-control" id="tickets2" disabled>
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>

                                x
                                Rs. 2999/-

                                <input type="text" style="font-size: 12px;" placeholder="Discount Coupon"><button class="btn btn-link">Apply</button>

                                (incl of all taxes)
                                Rs. 1998/-

                                Early Bird Ticket
                                Ends on Mar 17
                                5 Left
                                <select class="form-control" id="tickets3">
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>

                                x
                                Rs. 1499/-

                                Regular Ticket
                                Ends on Mar 20

                                <select class="form-control" id="tickets4" disabled>
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>

                                x
                                Rs. 1999/-

                                Last Minute Ticket
                                Ends on Mar 24

                                <select class="form-control" id="tickets5" disabled>
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                        <option value="5">5</option>
                                    </select>

                                x
                                Rs. 2999/-

                                <input type="text" style="font-size: 12px; text-align: center;" placeholder="Discount Coupon"><button class="btn btn-link">Apply</button>

                                (incl of all taxes)
                                Rs. 1998/-

2. Attendee Details

Please enter details of individual Attendee(s).
 In case of multiple attendees, Billing details should be same as the first Attendee.

                            <input type="text" class="form-control" name="" placeholder="Name">
                            <input type="text" class="form-control" name="" placeholder="Email">
                            <input type="text" class="form-control" name="" placeholder="Mobile No.">

            </form>

Body:
Wihout the need for all of your code, you can do this quite easily.

<div>
  <div id="hello" style="background-color:red; color :white;text-align:center; padding: 10px;">
  <span id="this">blah blah</span>
  <span id="something">More info</span>
  </div>
</div>
  <hr>
  <div id="modal">
    <div id="here1">Nothing</div>
    <div id="here2">Nohing2</div>
  </div>

And use this jQuery to grab the values and populate your modal:

$('div#hello').click(function(){
  var first= $('#this').html();
  var second= $('#something').html();
  $('#here1').html(first);
  $('#here2').html(second);
});

See i in action here: http://jsbin.com/rulaqabane/edit?html,js,output

Fetching your data after that is a separate issue!

Update:

$('div#hello').click(function(){
      var id= $('#id').html();
      $.get('/my/api/resource', {id: id}, function(data){
            $('#target').html(data.whatever);
      });
    });