问:
How can I shrink the drawable on a button?
how can I make the drawable on a button smaller? The icon is too big, actually higher than the button. This is the code I am using:

```<code>    <Button
    android:background="@drawable/red_button"
    android:drawableLeft="@drawable/s_vit"
    android:id="@+id/ButtonTest"
    android:gravity="left|center_vertical"
    android:text="S-SERIES CALCULATOR"
    android:textColor="@android:color/white"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_marginLeft="25dp"
    android:layout_marginRight="25dp"
    android:drawablePadding="10dp">
    </Button>
</code>```

The upper is how it should look, the lower how it looks right now.

I tried this but there is no image displayed. :-(

```<code>    Resources res = getResources();
    ScaleDrawable sd = new ScaleDrawable(res.getDrawable(R.drawable.s_vit), 0, 10f, 10f);
    Button btn = (Button) findViewById(R.id.ButtonTest);
    btn.setCompoundDrawables(sd.getDrawable(), null, null, null);
</code>```

答: It is because you did not setLevel. after you setLevel(1), it will be display as u want

Body:
how can I make the drawable on a button smaller? The icon is too big, actually higher than the button. This is the code I am using:

    <Button
    android:background="@drawable/red_button"
    android:drawableLeft="@drawable/s_vit"
    android:id="@+id/ButtonTest"
    android:gravity="left|center_vertical"
    android:text="S-SERIES CALCULATOR"
    android:textColor="@android:color/white"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_marginLeft="25dp"
    android:layout_marginRight="25dp"
    android:drawablePadding="10dp">
    </Button>

The upper is how it should look, the lower how it looks right now.

I tried this but there is no image displayed. :-(

    Resources res = getResources();
    ScaleDrawable sd = new ScaleDrawable(res.getDrawable(R.drawable.s_vit), 0, 10f, 10f);
    Button btn = (Button) findViewById(R.id.ButtonTest);
    btn.setCompoundDrawables(sd.getDrawable(), null, null, null);


来源: stackexchange

问:
Angular 4 - displaying message after an asynchronous call
I have a page where I display a list of posts, and clicking on each of them I am displaying comments for that post. That works fine, what I wanted to add is to display a message if there are no comments for the post that was clicked. I have tried with setting up the template like this:

```<code><li *ngFor="let post of posts" (click)="select(post)" >
      {{ post.title }}
      <ul *ngIf="currentPost == post && commentsVisible">
        <ng-container *ngIf="currentPost.comments.length > 0;else message">
          <li *ngFor="let comment of currentPost.comments" class="document">
            <p>{{ comment.author }}</p>
            <p>{{ comment.text }}</p>
          </li>
        </ng-container>
        <ng-template #message>No comments for {{ post.title }}</ng-template>
      </ul>
  </li>
</code>```

And in the component, I have tried to first set the empty posts array, and an empty currentPost object with a property comments:

```<code>  posts: any[] = [];
  currentPost: any = {};
  currentPost.comments;
</code>```

And then in the method select I am fetching the comments like this:

```<code>this.postService.getComments(post.id)
      .subscribe(
        comments => this.currentPost.comments = comments,
      );
</code>```

But, if I do so, I get an error:

posts.component.html:7 ERROR TypeError: Cannot read property 'length'
  of undefined

How can I avoid that error, and check and display a message after a async call to the service method getComments?

答:
A better solution for this problem is to use the async pipe (more info here).
Add the pipe into the *ngFor statement.
Current situation:

With async pipe:

ContentLicense: CC BY-SA 3.0

Body:
I have a page where I display a list of posts, and clicking on each of them I am displaying comments for that post. That works fine, what I wanted to add is to display a message if there are no comments for the post that was clicked. I have tried with setting up the template like this:

      {{ post.title }}

        <ng-container *ngIf="currentPost.comments.length > 0;else message">

{{ comment.author }}

{{ comment.text }}

        </ng-container>
        <ng-template #message>No comments for {{ post.title }}</ng-template>

And in the component, I have tried to first set the empty posts array, and an empty currentPost object with a property comments:

  posts: any[] = [];
  currentPost: any = {};
  currentPost.comments;

And then in the method select I am fetching the comments like this:

this.postService.getComments(post.id)
      .subscribe(
        comments => this.currentPost.comments = comments,
      );

But, if I do so, I get an error:

posts.component.html:7 ERROR TypeError: Cannot read property 'length'
  of undefined

How can I avoid that error, and check and display a message after a async call to the service method getComments?

Body:
A better solution for this problem is to use the async pipe (more info here).
Add the pipe into the *ngFor statement.
Current situation:
<li *ngFor="let post of posts" (click)="select(post)">

With async pipe:
<li *ngFor="let post of posts | async" (click)="select(post)">


问:
Default value on mappings AWS CloudFormation
What would be a good strategy to have a default value on mappings?

I.E.

I have a parameter called country

Based on that country I reference a DNS using mappings

```<code>"Mappings" : {
   "DNS":{
     "us" : {"dns" : "mypage.us.com", "ttl" : "600"},
     "mx" : {"dns" : "mypage.default.com", "ttl" : "300"},
     "ar" : {"dns" : "mypage.default.com", "ttl" : "300"},
     "br" : {"dns" : "mypage.default.com", "ttl" : "300"}
   }
}
</code>```

If us it's been mapped:

```<code>{ "Fn::FindInMap" : [ "DNS", { "Ref" : "country" }, "dns" ]}
</code>```

I get "mypage.us.com" for the other countries I've created a huge list of countries with a default value mypage.default.com, in the future, this values will be changing and we will be adding more countries, is there a better approach to this?

答:
The only way I was able to do this was to chain Fn::If statements instead of using the map. I tried using a combination of Fn::If and Fn::FindInMap but Fn::FindInMap will always raise an error it if can't find the mapping.

Therefore the only solution for me was to resort to using something like the following (for me it was setting ecs memory based on instance type):

```<code>Conditions:
  IsT2Micro: !Equals [!Ref InstanceType, "t2.micro"]
  IsT2Small: !Equals [!Ref InstanceType, "t2.small"]
  ...

taskdefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ...
      Memory: !If [ IsT2Micro, 900, !If [ IsT2Small, 1900, !Ref "AWS::NoValue"]]
</code>```

Body:
What would be a good strategy to have a default value on mappings?

I.E.

I have a parameter called country

Based on that country I reference a DNS using mappings

"Mappings" : {
   "DNS":{
     "us" : {"dns" : "mypage.us.com", "ttl" : "600"},
     "mx" : {"dns" : "mypage.default.com", "ttl" : "300"},
     "ar" : {"dns" : "mypage.default.com", "ttl" : "300"},
     "br" : {"dns" : "mypage.default.com", "ttl" : "300"}
   }
}

If us it's been mapped:

{ "Fn::FindInMap" : [ "DNS", { "Ref" : "country" }, "dns" ]}

I get "mypage.us.com" for the other countries I've created a huge list of countries with a default value mypage.default.com, in the future, this values will be changing and we will be adding more countries, is there a better approach to this?

Body:
The only way I was able to do this was to chain Fn::If statements instead of using the map. I tried using a combination of Fn::If and Fn::FindInMap but Fn::FindInMap will always raise an error it if can't find the mapping.

Therefore the only solution for me was to resort to using something like the following (for me it was setting ecs memory based on instance type):

Conditions:
  IsT2Micro: !Equals [!Ref InstanceType, "t2.micro"]
  IsT2Small: !Equals [!Ref InstanceType, "t2.small"]
  ...

taskdefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ...
      Memory: !If [ IsT2Micro, 900, !If [ IsT2Small, 1900, !Ref "AWS::NoValue"]]


问:
The Longest Character In UTF-8
What is the character with the most width? So "|" would have less width than "a", any ideas? Maybe a program could do this? Or maybe you just know a really widthy character.</p>

答: In UTF-8 The longest character is '﷽' as of the post of this comment, not sure what you needed it for but hope I helped</p>

Title: The Longest Character In UTF-8


问:
acquire-release pair out of order execution
I'm thinking of whether or not it is possible for atomic variable to load the old value in acquire-release pair.
Let's suppose we have atomic variable x, and we store that variable with release semantics and later load it with acquire semantics is it possible in theory to read the old value?

```<code>std::atomic<int> x = 0;

void thread_1()
{
   x.store(1, std::memory_order_release);
}
void thread_2()
{
   assert(x.load(std::memory_order_acquire) != 0);
}
</code>```

if function thread 1 is finished when thread 2 loads the x (so the new value is stored) is it possible for thread 2 to load old value from x? In other words if actual store to x is done before the load is it possible for assert to fire?

As far as I understood from articles in internet it is possible, but I cannot understand why. Memory fence generated by store to x guaranties to empty store buffer, while acquire memory fence in load from x is guaranteed to invalidate cache line, so it has to read up-to-date value.

added

Does it mean that acquire-release by itself doesn't have any enforced ordering? It's only anything that was done before release will happen before release and everything that is done after acquire will happen after it, so acquire-release pair enforces ordering on the other operations (why??). Did I get it right? Does it mean that in the code bellow assert is guaranteed to do not fire

```<code>std::atomic<int> x = 0;
std::atomic<int> y = 0;

void thread_1()
{
   y.store(1, std::memory_order_relaxed);
   x.store(1, std::memory_order_release);
}
void thread_2()
{
   x.load(std::memory_order_acquire);
   assert(y.load(std::memory_order_relaxed) != 0);
}
</code>```

of course again if the thread 1 was already finished the store. If we replace x.load with while (x.load() == 0) this will 100% work, but I don't know what causes this to work.

And what if I replace the code with code bellow

```<code>std::atomic<int> x = 0;

void thread_1()
{
   x.exchange(1, std::memory_order_acq_rel);
}
void thread_2()
{
   assert(x.exchange(0, std::memory_order_acq_rel) != 0);
}
</code>```

Does it change anything?

Thanks.

答:
You might consider store/load functions with release/acquire memory order as the following pseudo-code:

```<code>template<class T>
struct weak_atomic
{
   void store(T newValue)
   {
      ReleaseBarrier();
      m_value = newValue;
   }

   T load()
   {
      T value = m_value;
      AcquireBarrier();
      return value;
   }

   volatile T m_value;
}
</code>```

You said

Memory fence generated by store to x
  guaranties to empty store buffer

As I understand, the release memory barrier will cause the CPU to flush its store buffer, but it will be done before applying new value to x. So, it seems possible to read old value from x by another CPU.

Anyway, weak atomics is very complex area. Make sure you understand memory barriers before proceeding with lock-free programming.

ADDED

It seems you are still confused with memory barriers. This is a pretty common example of their usage.

```<code>volatile int  x;
volatile bool ok;

void thread_1()
{
   x = 100;
   ok = true;
}

void thread_2()
{
   if (ok)
   {
      assert(x == 100);
   }
}
</code>```

Due to out-of-order execution you may get the following sequence:

```<code>thread 1 sets ok to true
thread 2 checks ok is true and reads some garbage from x
thread 1 sets x to 100 but it is too late
</code>```

Another possible sequence:

```<code>thread 2 reads some garbage from x
thread 2 checks for ok value
</code>```

We may fix that with release and acquire memory barriers.

```<code>volatile int  x;
volatile bool ok;

void thread_1()
{
   x = 100;
   ReleaseBarrier();
   ok = true;
}

void thread_2()
{
   if (ok)
   {
      AcquireBarrier();
      assert(x == 100);
   }
}
</code>```

ReleaseBarrier() guarantees that memory writes can't jump over the barrier.
It means that ok is only set to true when x already contains valid value.

AcquireBarrier() guarantees that memory reads can't jump over the barrier.
It means that the value of x is only read after checking ok state.

This is how release/acquire pair is intended to be used. We can rewrite this example with my weak_atomic.

```<code>volatile int  x;
weak_atomic<bool> ok;

void thread_1()
{
   x = 100;
   ok.store(true);
}

void thread_2()
{
   if (ok.load())
   {
      assert(x == 100);
   }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm thinking of whether or not it is possible for atomic variable to load the old value in acquire-release pair.
Let's suppose we have atomic variable x, and we store that variable with release semantics and later load it with acquire semantics is it possible in theory to read the old value?

std::atomic<int> x = 0;

void thread_1()
{
   x.store(1, std::memory_order_release);
}
void thread_2()
{
   assert(x.load(std::memory_order_acquire) != 0);
}

if function thread 1 is finished when thread 2 loads the x (so the new value is stored) is it possible for thread 2 to load old value from x? In other words if actual store to x is done before the load is it possible for assert to fire?

As far as I understood from articles in internet it is possible, but I cannot understand why. Memory fence generated by store to x guaranties to empty store buffer, while acquire memory fence in load from x is guaranteed to invalidate cache line, so it has to read up-to-date value.

added

Does it mean that acquire-release by itself doesn't have any enforced ordering? It's only anything that was done before release will happen before release and everything that is done after acquire will happen after it, so acquire-release pair enforces ordering on the other operations (why??). Did I get it right? Does it mean that in the code bellow assert is guaranteed to do not fire

std::atomic<int> x = 0;
std::atomic<int> y = 0;

void thread_1()
{
   y.store(1, std::memory_order_relaxed);
   x.store(1, std::memory_order_release);
}
void thread_2()
{
   x.load(std::memory_order_acquire);
   assert(y.load(std::memory_order_relaxed) != 0);
}

of course again if the thread 1 was already finished the store. If we replace x.load with while (x.load() == 0) this will 100% work, but I don't know what causes this to work.

And what if I replace the code with code bellow

std::atomic<int> x = 0;

void thread_1()
{
   x.exchange(1, std::memory_order_acq_rel);
}
void thread_2()
{
   assert(x.exchange(0, std::memory_order_acq_rel) != 0);
}

Does it change anything?

Thanks.

Body:
You might consider store/load functions with release/acquire memory order as the following pseudo-code:

template<class T>
struct weak_atomic
{
   void store(T newValue)
   {
      ReleaseBarrier();
      m_value = newValue;
   }

   T load()
   {
      T value = m_value;
      AcquireBarrier();
      return value;
   }

   volatile T m_value;
}

You said

Memory fence generated by store to x
  guaranties to empty store buffer

As I understand, the release memory barrier will cause the CPU to flush its store buffer, but it will be done before applying new value to x. So, it seems possible to read old value from x by another CPU.

Anyway, weak atomics is very complex area. Make sure you understand memory barriers before proceeding with lock-free programming.

ADDED

It seems you are still confused with memory barriers. This is a pretty common example of their usage.

volatile int  x;
volatile bool ok;

void thread_1()
{
   x = 100;
   ok = true;
}

void thread_2()
{
   if (ok)
   {
      assert(x == 100);
   }
}

Due to out-of-order execution you may get the following sequence:

thread 1 sets ok to true
thread 2 checks ok is true and reads some garbage from x
thread 1 sets x to 100 but it is too late

Another possible sequence:

thread 2 reads some garbage from x
thread 2 checks for ok value

We may fix that with release and acquire memory barriers.

volatile int  x;
volatile bool ok;

void thread_1()
{
   x = 100;
   ReleaseBarrier();
   ok = true;
}

void thread_2()
{
   if (ok)
   {
      AcquireBarrier();
      assert(x == 100);
   }
}

ReleaseBarrier() guarantees that memory writes can't jump over the barrier.
It means that ok is only set to true when x already contains valid value.

AcquireBarrier() guarantees that memory reads can't jump over the barrier.
It means that the value of x is only read after checking ok state.

This is how release/acquire pair is intended to be used. We can rewrite this example with my weak_atomic.

volatile int  x;
weak_atomic<bool> ok;

void thread_1()
{
   x = 100;
   ok.store(true);
}

void thread_2()
{
   if (ok.load())
   {
      assert(x == 100);
   }
}


问:
How to handle print output from yahoo-finance quote reader?
I'm designing a tool that will help me manage risk in my equities portfolio. I've got some code that gathers current price data from yahoo finance for 4 equities, 2x longs and 2x shorts. This is using the yahoo-finance tool.

I can gather the data but I can't work out how to divide the prices by each other to return the value of the spread (stockA/stockB as a relative value trade)

```<code>#always helpful to show the version:
(env) LaurencsonsiMac:~ admin$ python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin

from yahoo_finance import Share
>>> L1 = Share('YHOO')
>>> L2 = Share('GOOG')
>>> S1 = Share('AAPL')
>>> S2 = Share('MSFT')
>>> print L1.get_price()
50.55
>>> print S1.get_price()
154.45
</code>```

A small victory! I can fetch the price :) but
I dont know how to manipulate this output as an object and define Long1 as “whatever is returned by print L1.get_price()”
The final output would be a table like this, with the spread values as a single (super important!) number to two or three (whatever) decimal places.

```<code>Position, Spread
YHOO/AAPL, 0.327 #value of Yahoo stock price/Apple stock price
GOOG/MSF,  4.55
ticker/ticker, 10.14
ticker/ticker, 0.567
</code>```

I attempted to define Long1 and Short1 as the number that L1.get_price() prints:

```<code>>>> Long1 = "L1.get_price()"
>>> Short1 = "S2.get_price()"
</code>```

then hopefully I should get a number by dividing those two:

```<code>>>> Long1/Short1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'str'
</code>```

so i tried to convert these numbers to a float [because it might work why not] but I’m clearly misunderstanding something:

```<code>>>> float(Long1)/float(Short1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: L1.get_price()
</code>```

Alternatively I did manage to get an output using this piece of code using the pandas module: (thank you Brad Solomon for this:)

```<code>import pandas_datareader.data as web

def get_quotes(symbols, type='dict'):
    quotes = web.get_quote_yahoo(symbols)['last']
    if type == 'dict':
        quotes = quotes.to_dict() # otherwise, Series
    return quotes

quotes = get_quotes(symbols=['RAD', 'MSFT']); quotes
Out[16]: {'MSFT': 70.409999999999997, 'RAD': 3.46}
</code>```

But how would you realise MSFT / RAD, get python to "read the string"?

I'm really quite stuck, can anyone hint me how I can get my quoted prices into real objects I can use?

答:
Variable assignment for Long1 and Short1 is wrong: instead of calling methods, you assign string literals with the names of the function. Try to change them to:

```<code>>>> Long1 = L1.get_price()
>>> Short1 = S2.get_price()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm designing a tool that will help me manage risk in my equities portfolio. I've got some code that gathers current price data from yahoo finance for 4 equities, 2x longs and 2x shorts. This is using the yahoo-finance tool.

I can gather the data but I can't work out how to divide the prices by each other to return the value of the spread (stockA/stockB as a relative value trade)

#always helpful to show the version:
(env) LaurencsonsiMac:~ admin$ python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin

from yahoo_finance import Share
>>> L1 = Share('YHOO')
>>> L2 = Share('GOOG')
>>> S1 = Share('AAPL')
>>> S2 = Share('MSFT')
>>> print L1.get_price()
50.55
>>> print S1.get_price()
154.45

A small victory! I can fetch the price :) but
I dont know how to manipulate this output as an object and define Long1 as “whatever is returned by print L1.get_price()”
The final output would be a table like this, with the spread values as a single (super important!) number to two or three (whatever) decimal places.

Position, Spread
YHOO/AAPL, 0.327 #value of Yahoo stock price/Apple stock price
GOOG/MSF,  4.55
ticker/ticker, 10.14
ticker/ticker, 0.567

I attempted to define Long1 and Short1 as the number that L1.get_price() prints:

>>> Long1 = "L1.get_price()"
>>> Short1 = "S2.get_price()"

then hopefully I should get a number by dividing those two:

>>> Long1/Short1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'str'

so i tried to convert these numbers to a float [because it might work why not] but I’m clearly misunderstanding something:

>>> float(Long1)/float(Short1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: L1.get_price()

Alternatively I did manage to get an output using this piece of code using the pandas module: (thank you Brad Solomon for this:)

import pandas_datareader.data as web

def get_quotes(symbols, type='dict'):
    quotes = web.get_quote_yahoo(symbols)['last']
    if type == 'dict':
        quotes = quotes.to_dict() # otherwise, Series
    return quotes

quotes = get_quotes(symbols=['RAD', 'MSFT']); quotes
Out[16]: {'MSFT': 70.409999999999997, 'RAD': 3.46}

But how would you realise MSFT / RAD, get python to "read the string"?

I'm really quite stuck, can anyone hint me how I can get my quoted prices into real objects I can use?

Body:
Variable assignment for Long1 and Short1 is wrong: instead of calling methods, you assign string literals with the names of the function. Try to change them to:

>>> Long1 = L1.get_price()
>>> Short1 = S2.get_price()


问:
Reading and storing static look up data in ASP .Net Core web app
I have a web app (ASP .Net Core 1.1 MVC) which has some basic CRUD operations. The web app consumes a web API for all its operations.

The web app has some pages for editing, with basic textboxes and dropdown lists in them. Some of the dropdown lists contain static information - for example, there might be a lookup table with these values:

Daily

Weekly

Monthly

Yearly

The web API exposes an endpoint to retrieve these values. However, I obviously don't want to call this every time the user navigates to the Edit page. Since this is static data that will never change, I would like to read this lookup data from the API just once when the web app starts up. The thing is I'm not really sure where the best place to do this is. Should I put Main() in Program.cs, or in Startup() in Startup.cs? Or should it be done using DI (somehow... not sure how that would happen). is there some best practise for this scenario?

And then the next question is where should I store this data? Can I just create a static, global variable where I hold all lookup tables? This is data that applies to all users/sessions, so I thought a basic global key/value pair list would be fine? I can read this from my various controllers to populate the dropdown lists in the views?

Thanks... just wanna do this the right way. Any tips would be greatly appreciated.

答:
You could save your data in singleton (application state data). You have to use Dependency Injection to make data available to all users:

Define a service containing the data (for example, a class named MyAppData).

```<code>public class MyAppData
{
// Declare properties/methods/etc.
}
</code>```

Add the service class to ConfigureServices (for example services.AddSingleton<MyAppData>();).

Consume the data service class in each controller:

```<code>public class MyController : Controller
{
   public MyController(MyAppData myService)
   {
    // Do something with the service (read some data from it,
    // store it in a private field/property, etc.)
   }
}
</code>```

You could find more information in the article - Introduction to session and application state in ASP.NET Core (in the Application state data section)

Also, I recommend you to cache your data - Caching.

And finally, you could use localStorage on the frontend for persisting information that newer changes.

PS: You could use application state in a non-core website - https://stackoverflow.com/a/3733549/182344.

Body:
You could save your data in singleton (application state data). You have to use Dependency Injection to make data available to all users:

Define a service containing the data (for example, a class named MyAppData).

public class MyAppData
{
// Declare properties/methods/etc.
}

Add the service class to ConfigureServices (for example services.AddSingleton<MyAppData>();).

Consume the data service class in each controller:

public class MyController : Controller
{
   public MyController(MyAppData myService)
   {
    // Do something with the service (read some data from it,
    // store it in a private field/property, etc.)
   }
}

You could find more information in the article - Introduction to session and application state in ASP.NET Core (in the Application state data section)

Also, I recommend you to cache your data - Caching.

And finally, you could use localStorage on the frontend for persisting information that newer changes.

PS: You could use application state in a non-core website - https://stackoverflow.com/a/3733549/182344.


问:
How to delete pushed commits and revert to old commit?
My situation:
On my branch origin webshop

I need to delete the 2 above commits and revert the whole project back to the 3rd commit.

How do i achieve this?

i Tried:

```<code>git reset --hard 69697a5
</code>```

But this keeps the other 2 commits..

答:
I wouldn't recommend deleting commits that are already pushed to a remote. This can lead to much confusion for other contributors. Therefore I'd recommend you to revert the commits locally and then push your results: git-revert Documentation.

If you need to truly delete the commits you should first do git reset --hard COMMIT has you have already done. To delete the commits on the remote you need to rewrite it's history aswell using git push --force. You can find further documentation here.

Body:
My situation:
On my branch origin webshop

I need to delete the 2 above commits and revert the whole project back to the 3rd commit.

How do i achieve this?

i Tried:

git reset --hard 69697a5

But this keeps the other 2 commits..


问:
How to get hover efect only on part of the element?
I have the below code:

.container {
 padding-top:20px;
}

.container:hover {
 background-color: red;
}

.text {
  padding-top: 20px;
}

.container:before {
content: 'before';
top: 5px;
position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <span class='text'>
    My text
  </span>
</div></code>```

I needed the 'before' as a title so inserted it as a pseudo, moved up and created palce for it by adding padding to the div. Now when I hover over the div the pseudo gets highlighted as well, which I don't want.

AS it's a skin for external app I have very limited possibilities to add elements to dom, which is what I guess should be done. How can I highlight only bottom part of the div without the pseudo? Maybe there's a better way to style the pseudo itself so that it doesn't get hovered over? Pure CSS appreciated.

答:
Why not use descendant selectors? You can nest under :hover as well. And with display: block; no need to use fixed size margins and paddings either.

.container:hover .text {
  background-color: red;
}

.text {
  display: block; /* or just use a div instead */
}

.container:before {
  content: 'before';
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <span class='text'>
    My text
  </span>
</div></code>```

Body:
I have the below code:

.container {
 padding-top:20px;
}

.container:hover {
 background-color: red;
}

.text {
  padding-top: 20px;
}

.container:before {
content: 'before';
top: 5px;
position: absolute;
}

    My text

I needed the 'before' as a title so inserted it as a pseudo, moved up and created palce for it by adding padding to the div. Now when I hover over the div the pseudo gets highlighted as well, which I don't want.

AS it's a skin for external app I have very limited possibilities to add elements to dom, which is what I guess should be done. How can I highlight only bottom part of the div without the pseudo? Maybe there's a better way to style the pseudo itself so that it doesn't get hovered over? Pure CSS appreciated.

Body:
Why not use descendant selectors? You can nest under :hover as well. And with display: block; no need to use fixed size margins and paddings either.

.container:hover .text {
  background-color: red;
}

.text {
  display: block; /* or just use a div instead */
}

.container:before {
  content: 'before';
  display: block;
}

<div class='container'>
  <span class='text'>
    My text
  </span>
</div>


问:
javascript variable scope binding using angularjs
I am using angularjs/javascript code for image Uploading but i got stuck in variable binding , can anyone help me out, here is my code.

```<code>var image_source;
$scope.uploadedFile = function(element) {
  reader.onload = function(event) {
  image_source = event.target.result;
  $scope.$apply(function($scope) {
    $scope.files = element.files;
  });
}
console.log(image_source,event.target.result, element.files[0],  "***not working here***");
</code>```

I'm binding varibale named image_source within function but when i access this outside the function it always return undefined why ?

PS:- i can get this in the typescript using phatarrow operator but how to do in javascript i dont know

答:
If your console.log statement is called before $scope.uploadedFile which is most likely to be the case, the value will not be set, I suggest you try to call the function and put your console.log statement at the end of the function, inside the block.

That's not an angular issue but more like javascript, when you declare an anonymous function it's not called immediately

```<code>let mynumber = 1
let myfunction = () => {
    mynumber = 2
}
console.log(mynumber) // 1
myfunction()
console.log(mynumber) // 2
</code>```

Body:
I am using angularjs/javascript code for image Uploading but i got stuck in variable binding , can anyone help me out, here is my code.

var image_source;
$scope.uploadedFile = function(element) {
  reader.onload = function(event) {
  image_source = event.target.result;
  $scope.$apply(function($scope) {
    $scope.files = element.files;
  });
}
console.log(image_source,event.target.result, element.files[0],  "***not working here***");

I'm binding varibale named image_source within function but when i access this outside the function it always return undefined why ?

PS:- i can get this in the typescript using phatarrow operator but how to do in javascript i dont know

Body:
If your console.log statement is called before $scope.uploadedFile which is most likely to be the case, the value will not be set, I suggest you try to call the function and put your console.log statement at the end of the function, inside the block.

That's not an angular issue but more like javascript, when you declare an anonymous function it's not called immediately

let mynumber = 1
let myfunction = () => {
    mynumber = 2
}
console.log(mynumber) // 1
myfunction()
console.log(mynumber) // 2


问:
Error 404 on delete row codeigniter 2
im deleting a row in coneigniter2  but it takes me to 404 page
(The page you requested was not found.)

this is my code

Controler Post

```<code> class Posts extends CI_Controller{

public function index(){
 $data['title'] = 'Ultimos Post';
  $data['posts'] = $this->Post_model->get_posts();
   $this->load->view('templates/header');
    $this->load->view('posts/index',$data);
     $this->load->view('templates/footer');
 }
   ...

   public function delete($id){
      //apagar post pelo id
         $this->Post_Model->delete_post($id);
          redirect('posts');

   }}
</code>```

Post Model

```<code> class Post_model extends Ci_Model{
  ...

    public function delete_post($id) {

              $this->db->where('id',$id);
                $this->db->delete('posts');

        }}
</code>```

In the View.php

```<code><?php echo form_open('/posts/delete/'.$post['id']);?>
<input type="submit" value="Delete" class="btn btn-danger" name="delete">
</code>```

Routes.php

```<code>$route['posts/create'] = 'posts/create';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = "pages/view";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

答:
Based on your config, posts/delete/2 route to posts/view/delete/2. Change your routes config to following code:

```<code>$route['posts/create'] = 'posts/create';
$route['posts/delete/(:num)'] = 'posts/delete/$1';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = "pages/view";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

Title: Error 404 on delete row codeigniter 2

Body:
im deleting a row in coneigniter2  but it takes me to 404 page
(The page you requested was not found.)

this is my code

Controler Post

 class Posts extends CI_Controller{

public function index(){
 $data['title'] = 'Ultimos Post';
  $data['posts'] = $this->Post_model->get_posts();
   $this->load->view('templates/header');
    $this->load->view('posts/index',$data);
     $this->load->view('templates/footer');
 }
   ...

   public function delete($id){
      //apagar post pelo id
         $this->Post_Model->delete_post($id);
          redirect('posts');

   }}

Post Model

 class Post_model extends Ci_Model{
  ...

    public function delete_post($id) {

              $this->db->where('id',$id);
                $this->db->delete('posts');

        }}

In the View.php

<?php echo form_open('/posts/delete/'.$post['id']);?>
<input type="submit" value="Delete" class="btn btn-danger" name="delete">

Routes.php

$route['posts/create'] = 'posts/create';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = "pages/view";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

Body:
Based on your config, posts/delete/2 route to posts/view/delete/2. Change your routes config to following code:

$route['posts/create'] = 'posts/create';
$route['posts/delete/(:num)'] = 'posts/delete/$1';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = "pages/view";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;


问:
#include <QtWidgets> not working in Qt 5.5 with ros kinetic ubuntu 16.06
I have a ros-project that builds fine under ros-indigo on ubuntu 14.04
now I switched to ros-kinetic and to ubuntu 16.04 and I got the following error when building my code:

Errors     << rviz_satellite:make
  /home/kohaf3/opel_ws/logs/rviz_satellite/build.make.028.log        In
  file included from
  /home/kohaf3/opel_ws/build/rviz_satellite/src/moc_aerialmap_display.cpp:9:0:
  /home/kohaf3/opel_ws/build/rviz_satellite/src/../../../src/rviz_satellite/src/aerialmap_display.h:43:21:
  fatal error: QtWidgets: No such file or directory compilation
  terminated. make[2]: *
  [CMakeFiles/rviz_satellite.dir/src/moc_aerialmap_display.cpp.o] Error
  1 make[2]:  Waiting for unfinished jobs.... In file included from
  /home/kohaf3/opel_ws/src/rviz_satellite/src/aerialmap_display.cpp:45:0:
  /home/kohaf3/opel_ws/src/rviz_satellite/src/aerialmap_display.h:43:21:
  fatal error: QtWidgets: No such file or directory compilation
  terminated. make[2]:
  [CMakeFiles/rviz_satellite.dir/src/aerialmap_display.cpp.o] Error 1
  make[1]: * [CMakeFiles/rviz_satellite.dir/all] Error 2 make: ***
  [all] Error 2

My CMakeLists file is as follows:

```<code>cmake_minimum_required(VERSION 2.8.3)
project(rviz_satellite)

set(DISTRO $ENV{ROS_DISTRO})
message("Distribution: " ${DISTRO})

set(DEFAULT_BUILD_QT5 OFF)
if(${DISTRO} STREQUAL "kinetic")
    set(DEFAULT_BUILD_QT5 ON)
endif()

option(UseQt5 "Build w/ QT version 5" ${DEFAULT_BUILD_QT5})

if (UseQt5)
    find_package(Qt5 COMPONENTS Core Gui Network Concurrent REQUIRED)
        message("qt5 is used")
else()
    find_package(Qt4 COMPONENTS QtCore QtGui QtNetwork REQUIRED)
    include(${QT_USE_FILE})
        message("qt4 is used")
endif()

find_package(OpenCV REQUIRED)
find_package(PkgConfig REQUIRED)

pkg_check_modules(OGRE_OV OGRE OGRE-Overlay)

# Old versions of OGRE (pre 1.9) included OGRE-Overlay in the main package
# (i.e. there was no OGRE-Overlay component).  So if the above
# pkg_check_modules() failed, try looking for just OGRE.
if(NOT OGRE_OV_FOUND)
  pkg_check_modules(OGRE_OV REQUIRED OGRE)
endif()

find_package(catkin REQUIRED COMPONENTS
  nav_msgs
  roscpp
  rviz
  sensor_msgs
  geodesy
  rtkrcv_ros_tool# wichtig für include:#include <rtkrcv_ros_tool/GPS_rtklib.h>
)

#generate_messages(
 # DEPENDENCIES
 # std_msgs
#)

catkin_package(CATKIN_DEPENDS nav_msgs sensor_msgs )#message_runtime)

set(${PROJECT_NAME}_SOURCES
  src/aerialmap_display.cpp
  src/tileloader.cpp
  src/rviz_plot_markers.cpp
)

set(${PROJECT_NAME}_HEADERS
  src/aerialmap_display.h
  src/tileloader.h
)

# invoke MOC and UI/ include Qt headers/ link Qt libraries
if (UseQt5)
    qt5_wrap_cpp(${PROJECT_NAME}_MOCSrcs ${${PROJECT_NAME}_HEADERS})
    include_directories(
        ${Qt5Core_INCLUDE_DIRS}
        ${Qt5Gui_INCLUDE_DIRS}
        ${Qt5Network_INCLUDE_DIRS}
        ${Qt5Concurrent_INCLUDE_DIRS}
                "/usr/include/qt5"
        )
    link_libraries(
        ${Qt5Core_LIBRARIES}
        ${Qt5Gui_LIBRARIES}
        ${Qt5Network_LIBRARIES}
        ${Qt5Concurrent_LIBRARIES}
        )
else()
    qt4_wrap_cpp(${PROJECT_NAME}_MOCSrcs ${${PROJECT_NAME}_HEADERS})
    include_directories(${Qt4_INCLUDE_DIR})
    link_libraries(
        ${QT_LIBRARIES}
        )
endif()

# Other includes
include_directories(
  ${CMAKE_CURRENT_BINARY_DIR}
  ${OpenCV_INCLUDE_DIR}
  ${OGRE_OV_INCLUDE_DIRS}
  ${catkin_INCLUDE_DIRS}
  src
)

# Other libraries
link_libraries(
  ${QT_LIBRARIES}
  ${OpenCV_LIBRARIES}
  ${catkin_LIBRARIES}
)

add_definitions("-Wall -Wunused -std=c++11")

set(PROJECT_SOURCE_FILES
  ${${PROJECT_NAME}_SOURCES}
  ${${PROJECT_NAME}_MOCSrcs}
)

add_library(${PROJECT_NAME}
  ${PROJECT_SOURCE_FILES}
)

install(TARGETS ${PROJECT_NAME}
    RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
    ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
    LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
)

install(FILES plugin_description.xml DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})

# von Markus:
add_executable(rviz_node
    src/rviz_plot_markers.cpp)
add_dependencies(rviz_node ${catkin_EXPORTED_TARGETS})
target_link_libraries(rviz_node
  ${catkin_LIBRARIES}
)
</code>```

qmake --version

```<code>QMake version 3.0
Using Qt version 5.5.1 in /usr/lib/x86_64-linux-gnu
</code>```

pkg-config --modversion QtCore

```<code>4.8.7
</code>```

qtdiag

```<code>Library info:   PrefixPath: /usr   DocumentationPath: /usr/share/qt5/doc
HeadersPath: /usr/include/x86_64-linux-gnu/qt5   LibrariesPath: /usr/lib
/x86_64-linux-gnu   LibraryExecutablesPath: /usr/lib/x86_64-linux-gnu/qt5
/libexec   BinariesPath: /usr/lib/x86_64-linux-gnu/qt5/bin   PluginsPath:
/usr/lib/x86_64-linux-gnu/qt5/plugins   ImportsPath: /usr/lib/x86_64-
linux-gnu/qt5/imports   Qml2ImportsPath: /usr/lib/x86_64-linux-gnu/qt5/qml
ArchDataPath: /usr/lib/x86_64-linux-gnu/qt5   DataPath: /usr/share/qt5
TranslationsPath: /usr/share/qt5/translations   ExamplesPath: /usr/lib
/x86_64-linux-gnu/qt5/examples   TestsPath: /usr/tests
SettingsPath: /etc/xdg
</code>```

I also installed Qt creator ros plugin see here (https://github.com/ros-industrial/ros_qtc_plugin/wiki/1.-How-to-Install-(Users) )

答:
This worked now for me:</p>

```<code>if (UseQt5)
        find_package(Qt5 COMPONENTS Core Gui Network Widgets Concurrent REQUIRED)
        message("qt5 is used")
        # Find Qt5Core and Qt5Widgets
        find_package(Qt5Core REQUIRED)
        find_package(Qt5Widgets REQUIRED)
        # For finding Qt includes
        include_directories(${CMAKE_CURRENT_SOURCE_DIR})
        include_directories(${Qt5Widgets_INCLUDE_DIRS})
        include_directories(${Qt5Core_INCLUDE_DIRS})

else()
        find_package(Qt4 COMPONENTS QtCore QtGui QtNetwork QtWidgets REQUIRED)
    include(${QT_USE_FILE})
        message("qt4 is used")
endif()
</code>```

Body:
I have a ros-project that builds fine under ros-indigo on ubuntu 14.04
now I switched to ros-kinetic and to ubuntu 16.04 and I got the following error when building my code:

Errors     << rviz_satellite:make
  /home/kohaf3/opel_ws/logs/rviz_satellite/build.make.028.log        In
  file included from
  /home/kohaf3/opel_ws/build/rviz_satellite/src/moc_aerialmap_display.cpp:9:0:
  /home/kohaf3/opel_ws/build/rviz_satellite/src/../../../src/rviz_satellite/src/aerialmap_display.h:43:21:
  fatal error: QtWidgets: No such file or directory compilation
  terminated. make[2]: *
  [CMakeFiles/rviz_satellite.dir/src/moc_aerialmap_display.cpp.o] Error
  1 make[2]:  Waiting for unfinished jobs.... In file included from
  /home/kohaf3/opel_ws/src/rviz_satellite/src/aerialmap_display.cpp:45:0:
  /home/kohaf3/opel_ws/src/rviz_satellite/src/aerialmap_display.h:43:21:
  fatal error: QtWidgets: No such file or directory compilation
  terminated. make[2]:
  [CMakeFiles/rviz_satellite.dir/src/aerialmap_display.cpp.o] Error 1
  make[1]: * [CMakeFiles/rviz_satellite.dir/all] Error 2 make: ***
  [all] Error 2

My CMakeLists file is as follows:

cmake_minimum_required(VERSION 2.8.3)
project(rviz_satellite)

set(DISTRO $ENV{ROS_DISTRO})
message("Distribution: " ${DISTRO})

set(DEFAULT_BUILD_QT5 OFF)
if(${DISTRO} STREQUAL "kinetic")
    set(DEFAULT_BUILD_QT5 ON)
endif()

option(UseQt5 "Build w/ QT version 5" ${DEFAULT_BUILD_QT5})

if (UseQt5)
    find_package(Qt5 COMPONENTS Core Gui Network Concurrent REQUIRED)
        message("qt5 is used")
else()
    find_package(Qt4 COMPONENTS QtCore QtGui QtNetwork REQUIRED)
    include(${QT_USE_FILE})
        message("qt4 is used")
endif()

find_package(OpenCV REQUIRED)
find_package(PkgConfig REQUIRED)

pkg_check_modules(OGRE_OV OGRE OGRE-Overlay)

# Old versions of OGRE (pre 1.9) included OGRE-Overlay in the main package
# (i.e. there was no OGRE-Overlay component).  So if the above
# pkg_check_modules() failed, try looking for just OGRE.
if(NOT OGRE_OV_FOUND)
  pkg_check_modules(OGRE_OV REQUIRED OGRE)
endif()

find_package(catkin REQUIRED COMPONENTS
  nav_msgs
  roscpp
  rviz
  sensor_msgs
  geodesy
  rtkrcv_ros_tool# wichtig für include:#include <rtkrcv_ros_tool/GPS_rtklib.h>
)

#generate_messages(
 # DEPENDENCIES
 # std_msgs
#)

catkin_package(CATKIN_DEPENDS nav_msgs sensor_msgs )#message_runtime)

set(${PROJECT_NAME}_SOURCES
  src/aerialmap_display.cpp
  src/tileloader.cpp
  src/rviz_plot_markers.cpp
)

set(${PROJECT_NAME}_HEADERS
  src/aerialmap_display.h
  src/tileloader.h
)

# invoke MOC and UI/ include Qt headers/ link Qt libraries
if (UseQt5)
    qt5_wrap_cpp(${PROJECT_NAME}_MOCSrcs ${${PROJECT_NAME}_HEADERS})
    include_directories(
        ${Qt5Core_INCLUDE_DIRS}
        ${Qt5Gui_INCLUDE_DIRS}
        ${Qt5Network_INCLUDE_DIRS}
        ${Qt5Concurrent_INCLUDE_DIRS}
                "/usr/include/qt5"
        )
    link_libraries(
        ${Qt5Core_LIBRARIES}
        ${Qt5Gui_LIBRARIES}
        ${Qt5Network_LIBRARIES}
        ${Qt5Concurrent_LIBRARIES}
        )
else()
    qt4_wrap_cpp(${PROJECT_NAME}_MOCSrcs ${${PROJECT_NAME}_HEADERS})
    include_directories(${Qt4_INCLUDE_DIR})
    link_libraries(
        ${QT_LIBRARIES}
        )
endif()

# Other includes
include_directories(
  ${CMAKE_CURRENT_BINARY_DIR}
  ${OpenCV_INCLUDE_DIR}
  ${OGRE_OV_INCLUDE_DIRS}
  ${catkin_INCLUDE_DIRS}
  src
)

# Other libraries
link_libraries(
  ${QT_LIBRARIES}
  ${OpenCV_LIBRARIES}
  ${catkin_LIBRARIES}
)

add_definitions("-Wall -Wunused -std=c++11")

set(PROJECT_SOURCE_FILES
  ${${PROJECT_NAME}_SOURCES}
  ${${PROJECT_NAME}_MOCSrcs}
)

add_library(${PROJECT_NAME}
  ${PROJECT_SOURCE_FILES}
)

install(TARGETS ${PROJECT_NAME}
    RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
    ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
    LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
)

install(FILES plugin_description.xml DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})

# von Markus:
add_executable(rviz_node
    src/rviz_plot_markers.cpp)
add_dependencies(rviz_node ${catkin_EXPORTED_TARGETS})
target_link_libraries(rviz_node
  ${catkin_LIBRARIES}
)

qmake --version

QMake version 3.0
Using Qt version 5.5.1 in /usr/lib/x86_64-linux-gnu

pkg-config --modversion QtCore

4.8.7

qtdiag

Library info:   PrefixPath: /usr   DocumentationPath: /usr/share/qt5/doc
HeadersPath: /usr/include/x86_64-linux-gnu/qt5   LibrariesPath: /usr/lib
/x86_64-linux-gnu   LibraryExecutablesPath: /usr/lib/x86_64-linux-gnu/qt5
/libexec   BinariesPath: /usr/lib/x86_64-linux-gnu/qt5/bin   PluginsPath:
/usr/lib/x86_64-linux-gnu/qt5/plugins   ImportsPath: /usr/lib/x86_64-
linux-gnu/qt5/imports   Qml2ImportsPath: /usr/lib/x86_64-linux-gnu/qt5/qml
ArchDataPath: /usr/lib/x86_64-linux-gnu/qt5   DataPath: /usr/share/qt5
TranslationsPath: /usr/share/qt5/translations   ExamplesPath: /usr/lib
/x86_64-linux-gnu/qt5/examples   TestsPath: /usr/tests
SettingsPath: /etc/xdg

I also installed Qt creator ros plugin see here (https://github.com/ros-industrial/ros_qtc_plugin/wiki/1.-How-to-Install-(Users) )

Body:
This worked now for me:

if (UseQt5)
        find_package(Qt5 COMPONENTS Core Gui Network Widgets Concurrent REQUIRED)
        message("qt5 is used")
        # Find Qt5Core and Qt5Widgets
        find_package(Qt5Core REQUIRED)
        find_package(Qt5Widgets REQUIRED)
        # For finding Qt includes
        include_directories(${CMAKE_CURRENT_SOURCE_DIR})
        include_directories(${Qt5Widgets_INCLUDE_DIRS})
        include_directories(${Qt5Core_INCLUDE_DIRS})

else()
        find_package(Qt4 COMPONENTS QtCore QtGui QtNetwork QtWidgets REQUIRED)
    include(${QT_USE_FILE})
        message("qt4 is used")
endif()


问:
How to put json array in json object
This is code which I'm using:

```<code>@Override
protected String doInBackground(String... arg0) {
    String yourJsonStringUrl = "GetCalender_Events";
    JsonParser jParser = new JsonParser();
    json = jParser.getJSONFromUrlArray(yourJsonStringUrl);
    return null;
}

@Override
protected void onPostExecute(String strFromDoInBg) {
    for (int i = 0; i < json.length(); i++) {
        try {
            JSONObject c = json.getJSONObject(i);
            ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"), c.getString("Event_Name"),
                    sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),
                    c.getString("Description")));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}
</code>```

How to put my JSON Array into JSON object? Can anyone please help me, this is my first try with JSON Array.

My array looks like this:

```<code>{
  "ContactList": [
    {
      "Column1": "22-05-2017",
      "Event_Name": "Garba Compition",
      "Description": "School organized garba compition"
    },
    {
      "Column1": "24-05-2017",
      "Event_Name": "Mahendi Compition",
      "Description": "Mahendi compition"
    }
  ]
}
</code>```

答:
```<code>JSONArray jsonarray = new JSONArray();
JSONObject jsonObject = new JSONObject();

try{
    jsonObject.put(jsonarray);
} catch(JSONException e){
    e.printStackTrace();
}
</code>```

<p>You get the values </p>

```<code>JSONArray songobj = json.getJSONArray("ContactList");
Log.d(TAG, "List Length" + songobj.length());
for (int i = 0; i < songobj.length(); i++) {
     JSONObject song = songobj.getJSONObject(i);
     String column=song.getString("Column1");
     String name=song.getString("Event_Name");
     String desc=song.getString("Description");
     ldatosAgenda.add(new DatosAgenda(column,name,desc));
  }
}
</code>```

Title: How to put json array in json object

Body:
This is code which I'm using:

@Override
protected String doInBackground(String... arg0) {
    String yourJsonStringUrl = "GetCalender_Events";
    JsonParser jParser = new JsonParser();
    json = jParser.getJSONFromUrlArray(yourJsonStringUrl);
    return null;
}

@Override
protected void onPostExecute(String strFromDoInBg) {
    for (int i = 0; i < json.length(); i++) {
        try {
            JSONObject c = json.getJSONObject(i);
            ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"), c.getString("Event_Name"),
                    sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),
                    c.getString("Description")));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}

How to put my JSON Array into JSON object? Can anyone please help me, this is my first try with JSON Array.

My array looks like this:

{
  "ContactList": [
    {
      "Column1": "22-05-2017",
      "Event_Name": "Garba Compition",
      "Description": "School organized garba compition"
    },
    {
      "Column1": "24-05-2017",
      "Event_Name": "Mahendi Compition",
      "Description": "Mahendi compition"
    }
  ]
}

Body:
JSONArray jsonarray = new JSONArray();
JSONObject jsonObject = new JSONObject();

try{
    jsonObject.put(jsonarray);
} catch(JSONException e){
    e.printStackTrace();
}

You get the values

JSONArray songobj = json.getJSONArray("ContactList");
Log.d(TAG, "List Length" + songobj.length());
for (int i = 0; i < songobj.length(); i++) {
     JSONObject song = songobj.getJSONObject(i);
     String column=song.getString("Column1");
     String name=song.getString("Event_Name");
     String desc=song.getString("Description");
     ldatosAgenda.add(new DatosAgenda(column,name,desc));
  }
}


问:
Can i generate a maven plugin descriptor (plugin.xml) with gradle?
I have the task of migrating a maven project, which has a java based maven plugin, to gradle. The plugin uses the maven-plugin-plugin and has the goals descriptor and helpmojo.

```<code><build>
    <plugins>
      <plugin>
        <artifactId>maven-plugin-plugin</artifactId>
        <version>3.4</version>
        <configuration>
        </configuration>
        <executions>
          <execution>
            <id>default-descriptor</id>
            <goals>
              <goal>descriptor</goal>
            </goals>
            <phase>process-classes</phase>
          </execution>
          <execution>
            <id>help-descriptor</id>
            <goals>
              <goal>helpmojo</goal>
            </goals>
            <phase>process-classes</phase>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</code>```

Is there any way i can execute these goals in gradle, or do i need to rewrite my java based maven plugin in gradle?

答:
You can create this file with gradle by running this task code on build.gradle. This code generates a pom.xml temporary, runs maven with the temporary pom and generates plguin.xml file. Finally (on doLast) the task copies the file to the META-INF/maven/ directory.</p>

```<code>task pluginDescriptor(type: Exec) {
  commandLine 'mvn', '-e', '-B', 'org.apache.maven.plugins:maven-plugin-plugin:3.2:descriptor'
  doFirst {
    final File pom = project.file('pom.xml')
    install.repositories.mavenInstaller.pom.writeTo(pom)
    assert pom.file, "[$pom.canonicalPath] was not created"

    pom.text = pom.text.
            replace('<groupId>unknown</groupId>', "<groupId>${project.group}</groupId>").
            replace('<artifactId>empty-project</artifactId>', "<artifactId>${project.name}</artifactId>").
            replace('<version>0</version>', """
                                                          |<version>${version}</version>
                                                          |  <packaging>maven-plugin</packaging>
                                                          |  <build>
                                                          |    <directory>\${project.basedir}/build</directory>
                                                          |    <outputDirectory>\${project.build.directory}/classes/main</outputDirectory>
                                                          |  </build>
                                                          |""".stripMargin().trim())
  }
  doLast {
    final pluginDescriptor = new File((File) project.compileGroovy.destinationDir, 'META-INF/maven/plugin.xml')
    assert pluginDescriptor.file, "[$pluginDescriptor.canonicalPath] was not created"
    println "Plugin descriptor file:$pluginDescriptor.canonicalPath is created successfully"
  }
}
</code>```

Body:
I have the task of migrating a maven project, which has a java based maven plugin, to gradle. The plugin uses the maven-plugin-plugin and has the goals descriptor and helpmojo.

<build>
    <plugins>
      <plugin>
        <artifactId>maven-plugin-plugin</artifactId>
        <version>3.4</version>
        <configuration>
        </configuration>
        <executions>
          <execution>
            <id>default-descriptor</id>
            <goals>
              <goal>descriptor</goal>
            </goals>
            <phase>process-classes</phase>
          </execution>
          <execution>
            <id>help-descriptor</id>
            <goals>
              <goal>helpmojo</goal>
            </goals>
            <phase>process-classes</phase>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

Is there any way i can execute these goals in gradle, or do i need to rewrite my java based maven plugin in gradle?

Body:
You can create this file with gradle by running this task code on build.gradle. This code generates a pom.xml temporary, runs maven with the temporary pom and generates plguin.xml file. Finally (on doLast) the task copies the file to the META-INF/maven/ directory.

task pluginDescriptor(type: Exec) {
  commandLine 'mvn', '-e', '-B', 'org.apache.maven.plugins:maven-plugin-plugin:3.2:descriptor'
  doFirst {
    final File pom = project.file('pom.xml')
    install.repositories.mavenInstaller.pom.writeTo(pom)
    assert pom.file, "[$pom.canonicalPath] was not created"

    pom.text = pom.text.
            replace('<groupId>unknown</groupId>', "<groupId>${project.group}</groupId>").
            replace('<artifactId>empty-project</artifactId>', "<artifactId>${project.name}</artifactId>").
            replace('<version>0</version>', """
                                                          |<version>${version}</version>
                                                          |  <packaging>maven-plugin</packaging>
                                                          |  <build>
                                                          |    <directory>\${project.basedir}/build</directory>
                                                          |    <outputDirectory>\${project.build.directory}/classes/main</outputDirectory>
                                                          |  </build>
                                                          |""".stripMargin().trim())
  }
  doLast {
    final pluginDescriptor = new File((File) project.compileGroovy.destinationDir, 'META-INF/maven/plugin.xml')
    assert pluginDescriptor.file, "[$pluginDescriptor.canonicalPath] was not created"
    println "Plugin descriptor file:$pluginDescriptor.canonicalPath is created successfully"
  }
}


问:
Placement of Python counter within class/function
I have the code below. I want to write 40 numbered output files (outfile) with 100 lines each. The while loop is supposed to check when the counter reaches a 100. But my counter = counter + 1 does not do the job. The counter stays at 1.

```<code>class MyStreamListener(tweepy.StreamListener):
    def on_data(self, data):
        for i in range(40): # create max 40 outfiles
            outfile = (projname + "_" + str(i+1) + "_output.json")
            counter = 0
            while counter <= 100:
                try:
                    with open(outfile, 'a') as f:
                        f.write(data)
                        counter = counter + 1
                        print("\rAppending tweet " + str(counter) + " to " + str(outfile), end="")
                        return True
                except BaseException as e:
                    print("Error on_data: " % str(e))
                    return True
            else:
                break
</code>```

答:
I took the liberty to re-write your code a bit.

```<code>class MyStreamListener(tweepy.StreamListener):
    def on_data(self, data):
        for i in range(40):  # create max 40 outfiles
            outfile = (projname + "_" + str(i+1) + "_output.json")
            with open(outfile, 'a') as f:
                for counter in range(100):
                    f.write(data)
                    print("\rAppending tweet " + str(counter) + " to " + str(outfile), end="")
        return True
</code>```

As you might notice there are a few things that are done differently now.

No need for a while if you know how many times you need to execute a loop.

Opening and closing a file every time you want to write a line is very wasteful, so do it once per file

I do not see a point for your try block.. What is it that should be tried because it might fail?

Why the else at the end?

There is a chance I missinterpreted some of your code and removed features that should be there. If that is the case or if you have any questions, please let me know.

Note: Keep in mind that .write() is not like print() and does not append a newline character automatically. So your script will write everything in a single line unless data contains newlines.

And I final thing. data does not change in each iteration. You are writing the same thing 100 times in each file. Is this the desired behavior?

Body:
I have the code below. I want to write 40 numbered output files (outfile) with 100 lines each. The while loop is supposed to check when the counter reaches a 100. But my counter = counter + 1 does not do the job. The counter stays at 1.

class MyStreamListener(tweepy.StreamListener):
    def on_data(self, data):
        for i in range(40): # create max 40 outfiles
            outfile = (projname + "_" + str(i+1) + "_output.json")
            counter = 0
            while counter <= 100:
                try:
                    with open(outfile, 'a') as f:
                        f.write(data)
                        counter = counter + 1
                        print("\rAppending tweet " + str(counter) + " to " + str(outfile), end="")
                        return True
                except BaseException as e:
                    print("Error on_data: " % str(e))
                    return True
            else:
                break

Body:
I took the liberty to re-write your code a bit.

class MyStreamListener(tweepy.StreamListener):
    def on_data(self, data):
        for i in range(40):  # create max 40 outfiles
            outfile = (projname + "_" + str(i+1) + "_output.json")
            with open(outfile, 'a') as f:
                for counter in range(100):
                    f.write(data)
                    print("\rAppending tweet " + str(counter) + " to " + str(outfile), end="")
        return True

As you might notice there are a few things that are done differently now.

No need for a while if you know how many times you need to execute a loop.

Opening and closing a file every time you want to write a line is very wasteful, so do it once per file

I do not see a point for your try block.. What is it that should be tried because it might fail?

Why the else at the end?

There is a chance I missinterpreted some of your code and removed features that should be there. If that is the case or if you have any questions, please let me know.

Note: Keep in mind that .write() is not like print() and does not append a newline character automatically. So your script will write everything in a single line unless data contains newlines.

And I final thing. data does not change in each iteration. You are writing the same thing 100 times in each file. Is this the desired behavior?


问:
Android rxJava2 project structure, file naming, etc
I have an Android project that currently doesn't use View Models or rxJava.  It's a fairly straightforward app that uses the Parse sdk with a parse-server.  It's still early in the project and I've decided to start using VM and rxJava.

My question is mostly about structure, naming etc.  Let's use Login for an example:

I have an interface calledAuthenticationService.java with a login(Authorization auth, ServiceCallback<User> callback) method.

My ParseAuthenticationService.java implements that interface and does all the parse stuff.

The whole app is set up like that, so my User.java is an interface used by MyParseUser.java where all the parse stuff happens.

So there's a login button, LoginActivity grabs the username/password, makes an Authorization object and calls the login function.

Is the change to rxJava as simple as wrapping the login function in an observable and subscribing to it in the activity?

What would that look like?  The login function looks like this:

```<code>@Override
public void login(Authorization authorization, final ServiceCallback<User> callback)
{
    cachedUser = null;
    ParseUser.logInInBackground(authorization.getUsername(), authorization.getPassword(), new LogInCallback()
    {
        @Override
        public void done(ParseUser user, ParseException e)
        {
            if (callback != null)
            {
                callback.onServiceRequestComplete(Response.<User>from((MyParseUser) user, e));
            }
        }
    });
}
</code>```

Can I keep the same Parse-class-using-generic-interface structure?  Or should I restructure/rename my files?

Thanks for any help.  This is all a bit overwhelming.

答:
Using interface separate contract declaration from implementation. Since the Observable pattern is a nice way to represent asynchronous responses, replacing callback with Observables in your interfaces seems a good fit.

You could begin to put Observable version of your callback function alongside. For example, writing an Observable<User> loginObservable(Authorization auth) (or better Single<User> loginSingle(Authorization auth)) that essentially wrap login( ... ) with Observable.create() or Single.create(). You may need a refactoring afterward, but you will do it when you familiar with Rx. For me switching to Rx was a 2 steps process; I evolved my architecture but a lot later.

Since creating Observable like this is a little advanced Rx topic, I would recommend you to look for already existing Rx wrappers for Parse.

Body:
I have an Android project that currently doesn't use View Models or rxJava.  It's a fairly straightforward app that uses the Parse sdk with a parse-server.  It's still early in the project and I've decided to start using VM and rxJava.

My question is mostly about structure, naming etc.  Let's use Login for an example:

I have an interface calledAuthenticationService.java with a login(Authorization auth, ServiceCallback<User> callback) method.

My ParseAuthenticationService.java implements that interface and does all the parse stuff.

The whole app is set up like that, so my User.java is an interface used by MyParseUser.java where all the parse stuff happens.

So there's a login button, LoginActivity grabs the username/password, makes an Authorization object and calls the login function.

Is the change to rxJava as simple as wrapping the login function in an observable and subscribing to it in the activity?

What would that look like?  The login function looks like this:

@Override
public void login(Authorization authorization, final ServiceCallback<User> callback)
{
    cachedUser = null;
    ParseUser.logInInBackground(authorization.getUsername(), authorization.getPassword(), new LogInCallback()
    {
        @Override
        public void done(ParseUser user, ParseException e)
        {
            if (callback != null)
            {
                callback.onServiceRequestComplete(Response.<User>from((MyParseUser) user, e));
            }
        }
    });
}

Can I keep the same Parse-class-using-generic-interface structure?  Or should I restructure/rename my files?

Thanks for any help.  This is all a bit overwhelming.


问:
Trigger after updating the document at couchDB
I am using the couchDB and I just wanted to fire a http request when any updation is performed at the couchDb side.I am updating the document using the java api (in an android application).Thanks in advance any clue will be appreciated.</p>

答:
You might be able to implement that with PouchDB live sync, like below:

```<code>var localDB = new PouchDB('localdb')
var remoteDB = new PouchDB('http://192.168.1.106:5984/remotedb')

localDB.sync(remoteDB, {
    live: true,
    retry: true
}).on('change', function (change) {
    // Something changed
    // trigger appropriate events here
})
</code>```

Body:
You might be able to implement that with PouchDB live sync, like below:

var localDB = new PouchDB('localdb')
var remoteDB = new PouchDB('http://192.168.1.106:5984/remotedb')

localDB.sync(remoteDB, {
    live: true,
    retry: true
}).on('change', function (change) {
    // Something changed
    // trigger appropriate events here
})


问:
expression of non-boolean type
Using this statement:

```<code>select * from qvalues where rowid ,name,compound in (
    select rowid,name,compound from qvalues where rowid in (select rowid from batchinfo where instrument='tf1')
    group by rowid,name,compound
    having COUNT(*)>1
    )
    group by rowid,name,compound
having rid=min(rid)
</code>```

This error occurs:

Msg 4145, Level 15, State 1, Line 3
  An expression of non-boolean type specified in a context where a condition is expected, near ','.
  Msg 156, Level 15, State 1, Line 8
  Incorrect syntax near the keyword 'group'.

What is wrong with this SQL statement? I need to find all the occurrences of those three fields in the table having min(rid).

Update
Using this query, the outer select is not working. What am I doing wrong?

```<code>select * from qvalues where rid not in (
select q.rowid, q.name, q.compound, min(q.rid)
    from qvalues q
        inner join batchinfo b
            on q.rowid = b.rowid
                and b.instrument = 'tf1'
    group by q.rowid, q.name, q.compound
    having count(*) > 1)
</code>```

答:
I think this is equivalent to what you're trying to achieve.</p>

```<code>select min(q.rid)
    from qvalues q
        inner join batchinfo b
            on q.rowid = b.rowid
                and b.instrument = 'tf1'
    group by q.rowid, q.name, q.compound
    having count(*) > 1
</code>```

Title: expression of non-boolean type

Body:
Using this statement:

select * from qvalues where rowid ,name,compound in (
    select rowid,name,compound from qvalues where rowid in (select rowid from batchinfo where instrument='tf1')
    group by rowid,name,compound
    having COUNT(*)>1
    )
    group by rowid,name,compound
having rid=min(rid)

This error occurs:

Msg 4145, Level 15, State 1, Line 3
  An expression of non-boolean type specified in a context where a condition is expected, near ','.
  Msg 156, Level 15, State 1, Line 8
  Incorrect syntax near the keyword 'group'.

What is wrong with this SQL statement? I need to find all the occurrences of those three fields in the table having min(rid).

Update
Using this query, the outer select is not working. What am I doing wrong?

select * from qvalues where rid not in (
select q.rowid, q.name, q.compound, min(q.rid)
    from qvalues q
        inner join batchinfo b
            on q.rowid = b.rowid
                and b.instrument = 'tf1'
    group by q.rowid, q.name, q.compound
    having count(*) > 1)

Body:
I think this is equivalent to what you're trying to achieve.

select min(q.rid)
    from qvalues q
        inner join batchinfo b
            on q.rowid = b.rowid
                and b.instrument = 'tf1'
    group by q.rowid, q.name, q.compound
    having count(*) > 1


问:
Dependency injection and serialization Object in spring
I have an application that is configured with spring security.

Everything is working as well.

The UserDetailService is:

```<code>@Service(value = "userDetail")
public class UserDetailServiceImpl implements UserDetailsService, Serializable {
    private static final long serialVersionUID = 3487495895819392L;

    @Autowired
    private IUserDetailRepository iUserDetailRepository;

    @Autowired
    private IUserRoleRepository iUserRoleRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = iUserDetailRepository.loadUserByUsername(username);
        List<UserRole> roles = iUserRoleRepository.getAllRoleByUserName(username);
        UserDetails u = new UserDetails() {

            @Override
            public boolean isEnabled() {
                // return user.getEnable();
                return true;
            }

            @Override
            public boolean isCredentialsNonExpired() {
                return true;
            }

            @Override
            public boolean isAccountNonLocked() {
                return true;
            }

            @Override
            public boolean isAccountNonExpired() {
                return true;
            }

            @Override
            public String getUsername() {
                // return user.getUsername();
                return "reyhane";
            }

            @Override
            public String getPassword() {
                // return user.getPassword();
                return "reyhane";
            }

            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ADMIN");
                authorities.add(authority);

                return authorities;

            }
        };
        return u;
    }

}
</code>```

After that I was forced to config spring session over this configuration for saving the context of spring security into Redis.

There exists a problem in UserDetailService.

UserDetailService have two autowired filed as shown above are:

```<code>@Autowired
private IUserDetailRepository iUserDetailRepository;

@Autowired
private IUserRoleRepository iUserRoleRepository;
</code>```

This two autowired field are for getting User and User's roles information from DB.

It is interesting here that when I comment this two autowired like this:

```<code>//@Autowired
private IUserDetailRepository iUserDetailRepository;

//@Autowired
private IUserRoleRepository iUserRoleRepository;
</code>```

and fill manually user and user's role.Spring session is working as well but when this two @Autowired exist in the class the below exception is raised:

Caused by:
  org.springframework.core.serializer.support.SerializationFailedException:
  Failed to serialize object using DefaultSerializer; nested exception
  is java.io.NotSerializableException:
  org.springframework.dao.support.PersistenceExceptionTranslationInterceptor
  at
  org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:68)
  ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at
  org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:35)
  ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at
  org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.serialize(JdkSerializationRedisSerializer.java:90)
  ~[spring-data-redis-1.7.2.RELEASE.jar:na] ... 35 common frames omitted
  Caused by: java.io.NotSerializableException:
  org.springframework.dao.support.PersistenceExceptionTranslationInterceptor
  at
  java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
  ~[na:1.8.0_111] at
  java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
  ~[na:1.8.0_111]

Everybody know that what is happen?

I do not understand what is happen.

I do not know there is what key for searching in google

I want to know what is happen between spring session and spring security and how to solve it.

Thanks for your helping

答:
This has actually nothing to do with those dependencies, it is due to the fact that you are using an (non static) inner class. You should either use an embedded static class or simply use the regular User class from Spring Security. (More on inner, (non) static embedded classes are found in this answer.

In short due to the fact of you using an inner classes it requires an instance of the outer class to exist. Now when serializing the UserDetails it will also try to serialize the outer class.

The simplest solution is to rewrite your code and use the Spring Security provided User class (assuming you are using Spring Security 4.2 you can use the UserBuilder).

```<code>@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = iUserDetailRepository.loadUserByUsername(username);
    List<UserRole> roles = iUserRoleRepository.getAllRoleByUserName(username);

    return User.withUsername(user.getUsername())
                        .password(user.getPassword())
                        .disabled(!user.getEnable())
                        .roles(roles.stream().map(<convert-to-SimpleGrantedAuthority>).collect(Collectors.toList()))
                        .build();
}
</code>```

If you are on Spring Security before 4.2 you can simply construct a User object using the constructor.

```<code>return new User(user.getUsername(), user.getPassword(), user.getEnable(), true, true, true, <convert-roles-to-SimpleGrantedAuthoritu>);
</code>```

When return a concrete class it doesn't require an instance of the outer class (as it isn't an inner class) and it will not try to serialize it. It will only serialize the User and nothing else.

Body:
I have an application that is configured with spring security.

Everything is working as well.

The UserDetailService is:

@Service(value = "userDetail")
public class UserDetailServiceImpl implements UserDetailsService, Serializable {
    private static final long serialVersionUID = 3487495895819392L;

    @Autowired
    private IUserDetailRepository iUserDetailRepository;

    @Autowired
    private IUserRoleRepository iUserRoleRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = iUserDetailRepository.loadUserByUsername(username);
        List<UserRole> roles = iUserRoleRepository.getAllRoleByUserName(username);
        UserDetails u = new UserDetails() {

            @Override
            public boolean isEnabled() {
                // return user.getEnable();
                return true;
            }

            @Override
            public boolean isCredentialsNonExpired() {
                return true;
            }

            @Override
            public boolean isAccountNonLocked() {
                return true;
            }

            @Override
            public boolean isAccountNonExpired() {
                return true;
            }

            @Override
            public String getUsername() {
                // return user.getUsername();
                return "reyhane";
            }

            @Override
            public String getPassword() {
                // return user.getPassword();
                return "reyhane";
            }

            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ADMIN");
                authorities.add(authority);

                return authorities;

            }
        };
        return u;
    }

}

After that I was forced to config spring session over this configuration for saving the context of spring security into Redis.

There exists a problem in UserDetailService.

UserDetailService have two autowired filed as shown above are:

@Autowired
private IUserDetailRepository iUserDetailRepository;

@Autowired
private IUserRoleRepository iUserRoleRepository;

This two autowired field are for getting User and User's roles information from DB.

It is interesting here that when I comment this two autowired like this:

//@Autowired
private IUserDetailRepository iUserDetailRepository;

//@Autowired
private IUserRoleRepository iUserRoleRepository;

and fill manually user and user's role.Spring session is working as well but when this two @Autowired exist in the class the below exception is raised:

Caused by:
  org.springframework.core.serializer.support.SerializationFailedException:
  Failed to serialize object using DefaultSerializer; nested exception
  is java.io.NotSerializableException:
  org.springframework.dao.support.PersistenceExceptionTranslationInterceptor
  at
  org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:68)
  ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at
  org.springframework.core.serializer.support.SerializingConverter.convert(SerializingConverter.java:35)
  ~[spring-core-4.3.2.RELEASE.jar:4.3.2.RELEASE] at
  org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.serialize(JdkSerializationRedisSerializer.java:90)
  ~[spring-data-redis-1.7.2.RELEASE.jar:na] ... 35 common frames omitted
  Caused by: java.io.NotSerializableException:
  org.springframework.dao.support.PersistenceExceptionTranslationInterceptor
  at
  java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
  ~[na:1.8.0_111] at
  java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
  ~[na:1.8.0_111]

Everybody know that what is happen?

I do not understand what is happen.

I do not know there is what key for searching in google

I want to know what is happen between spring session and spring security and how to solve it.

Thanks for your helping

Body:
This has actually nothing to do with those dependencies, it is due to the fact that you are using an (non static) inner class. You should either use an embedded static class or simply use the regular User class from Spring Security. (More on inner, (non) static embedded classes are found in this answer.

In short due to the fact of you using an inner classes it requires an instance of the outer class to exist. Now when serializing the UserDetails it will also try to serialize the outer class.

The simplest solution is to rewrite your code and use the Spring Security provided User class (assuming you are using Spring Security 4.2 you can use the UserBuilder).

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = iUserDetailRepository.loadUserByUsername(username);
    List<UserRole> roles = iUserRoleRepository.getAllRoleByUserName(username);

    return User.withUsername(user.getUsername())
                        .password(user.getPassword())
                        .disabled(!user.getEnable())
                        .roles(roles.stream().map(<convert-to-SimpleGrantedAuthority>).collect(Collectors.toList()))
                        .build();
}

If you are on Spring Security before 4.2 you can simply construct a User object using the constructor.

return new User(user.getUsername(), user.getPassword(), user.getEnable(), true, true, true, <convert-roles-to-SimpleGrantedAuthoritu>);

When return a concrete class it doesn't require an instance of the outer class (as it isn't an inner class) and it will not try to serialize it. It will only serialize the User and nothing else.


问:
onKeyDown event not working on divs in React
I want to use a keyDown event on a div in React. I do:

```<code>  componentWillMount() {
      document.addEventListener("keydown", this.onKeyPressed.bind(this));
  }

  componentWillUnmount() {
      document.removeEventListener("keydown", this.onKeyPressed.bind(this));
  }

  onKeyPressed(e) {
    console.log(e.keyCode);
  }

  render() {
    let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
    return (
      <div
        className="player"
        style={{ position: "absolute" }}
        onKeyDown={this.onKeyPressed} // not working
      >
        <div className="light-circle">
          <div className="image-wrapper">
            <img src={IMG_URL+player.img} />
          </div>
        </div>
      </div>
    )
  }
</code>```

It works fine, but I would like to do it more in React style. I tried

```<code>onKeyDown={this.onKeyPressed}
</code>```

on the component. But it doesn't react. It works on input elements as I recall.

Codepen

How can I do it?

答: You should use tabIndex attribute to be able to listen onKeyDown event on a div in React. Setting tabIndex="0" should fire your handler.

Body:
I want to use a keyDown event on a div in React. I do:

  componentWillMount() {
      document.addEventListener("keydown", this.onKeyPressed.bind(this));
  }

  componentWillUnmount() {
      document.removeEventListener("keydown", this.onKeyPressed.bind(this));
  }

  onKeyPressed(e) {
    console.log(e.keyCode);
  }

  render() {
    let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
    return (

    )
  }

It works fine, but I would like to do it more in React style. I tried

onKeyDown={this.onKeyPressed}

on the component. But it doesn't react. It works on input elements as I recall.

Codepen

How can I do it?


问:
Array by value multiplication memory leak in c++
I'm having some trouble with multiplying an array (char array in this particular case) by a value.
My code looks like this:

```<code>char* tab1 = copy("11");
char t = '2';
int length = strlen(tab1) + 2;
char*result = populate('0', length);
int p_length = strlen(tab1);
for (int j = p_length - 1; j >= 0; j--) {
    char* tmp = multiply_chars(tab1[j], t);
    v_shove(tmp, j);
    char* tmp2 = add_tables(result, tmp);
    delete[] result;
    result = tmp2;
    delete[] tmp;
}
cout << result << endl;
delete[] result;
delete[] tab1;
</code>```

None of the methods used (that's populate, multiply_chars and add_tables) causes a leak when ran in an infinite loop. I've narrowed the leak to the

```<code>char* tmp2 = add_tables(result, tmp);
delete[] result;
result = tmp2;
</code>```

part, but have no idea why it would happen.
I check for leaks by running snippets in an infinite loop and checking memory usage.
Any help would be appreciated! If need be I'll post the code of the methods used, but decided not to for the sake of brevity here. They all return new cstrings. Also, the t2 variable is there from when I was checking the array by array multiplication, which also leaked - decided to do array by value multiplication first.
(Now, to be completely honest this is one of the methods required for a school project, but it's such a miniscule part of it, that I thought it wouldn't hurt if I asked - the teacher isn't really big on helping with particular code problems)

The functions are:

```<code>char * add_tables(const char * table1, const char * table2)
{
    char* tmp1 = get_string_trailing("0",table1);
    char* tmp2 = get_string_trailing("0", table2);
    int l1 = strlen(tmp1), l2 = strlen(tmp2);
    if (l1 != l2) {
        if (l1 > l2) {
            char* t = resize_string(tmp2, l1 - l2, '0');
            delete[] tmp2;
            tmp2 = t;
        }
        else {
            char* t = resize_string(tmp1, l2 - l1, '0');
            delete[] tmp1;
            tmp1 = t;
        }
}
    int length = strlen(tmp1) + 2;
    char*result = new char[length];
    result[length - 1] = 0;
    int buffer = 0;
    for (int i = length - 2; i > 0; i--) {
        int t = buffer + (tmp1[i-1]-'0') + (tmp2[i-1]-'0');
        result[i] = (t% 10)+'0';
        buffer = (t - (t % 10))/10;
    }
    result[0] = buffer + '0';
    char* t = get_string_trailing("0", result);
    delete[]result;
    result = t;
    delete[]tmp1;
    delete[]tmp2;
    return result;
}
void v_shove(char *&c, int i)
{
    char* tmp = shove(c, i);
    delete[] c;
    c = tmp;
}
char * populate(const char populator, int length)
{
    char* result = new char[length + 1];
    result[length] = 0;
    for (int i = 0; i < length; i++) {
        result[i] = populator;
    }
    return result;
}
char * multiply_chars(const char c1,const char c2)
{
    char*result = new char[3];
    result[2] = 0;
    char tmp1 = c1 - '0', tmp2 = c2 - '0';
    result[1] = (tmp1*tmp2 % 10) + '0';
    result[0] = (tmp1*tmp2 - (tmp1*tmp2 % 10)) / 10 + '0';
    char* r = get_string_trailing("0", result);
    delete[] result;
    result = r;
    return result;
}
int get_length_trailing(const char * ignore,const char * table)
{
    int length = 0;
    int i = 0;
    bool flag = true;
    while (i < strlen(table)) {
        if (flag) {
            for (int j = 0; j < strlen(ignore); j++)
            if (table[i] == ignore[j])goto BREAKPOINT;
        }
        flag = false;
        length++;
    BREAKPOINT:i++;
    }
    return length;
}
char * get_string_trailing(const char * ignore,const char * table)
{
    int result_length = get_length_trailing(ignore, table);
    char* result = new char[result_length + 1];
    int counter = 0;
    int i = 0;
    bool flag = true;
    while (i < strlen(table)) {
        if (flag)
            for (int j = 0; j < strlen(ignore); j++)
                if (table[i] == ignore[j])goto BREAKPOINT;
        flag = false;
        result[counter] = table[i];
        counter++;
    BREAKPOINT:i++;
    }
    result[result_length] = 0;
    if (result_length == 0) return copy("0");
    return result;
}
char * shove(const char * table1, int index)
{
    char*result = "0";
    int length = strlen(table1) + index + 1;
    result = new char[length];
    result[length - 1] = 0;
    if (index > 0) {
        for (int i = 0; i < strlen(table1); i++)
            result[i] = table1[i];
        for (int i = 0; i < index; i++)
            result[strlen(table1) + i] = '0';
    }
    else {
        for (int i = 0; i < strlen(result); i++)
            result[i] = table1[i];
    }
    char* t = get_string_trailing("0", result);
    delete[] result;
    result = t;
    return result;
}
</code>```

答:
There is at least a memory leak in get_string_trailing: if result_length is zero, you return a copy and do not delete result. There are also confusions between "string" (such as "0") and 'char': with double quotes, the terminating string character (\0) is automatically appended to the string, while simple quotes only define a character. So "0" is made of 2 char in memory and can not be stored in a pointer (undefined behavior, overwriting memory).

To summarize: here you are writing C, not learning C++. If you have to deal with C strings (you are writing a low-level pilot in C or your professor still doesn't understand that C and C++ are different languages), at least use the functions of the string.h (in C) / cstring (in C++) header to minimize the chance of memory leak or undefined behavior. If you do not have to use C strings, use std::string and the string manipulation tools of the standard library. Your work will be much easier, and your code much less vulnerable to bugs:

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

int main()
{
  string tab1("11")
  string t("2") // never use the single quotes for a string
  cout << stoi(tab1) * stoi(t) << endl;
  return;
}
</code>```

That's it!

Body:
I'm having some trouble with multiplying an array (char array in this particular case) by a value.
My code looks like this:

char* tab1 = copy("11");
char t = '2';
int length = strlen(tab1) + 2;
char*result = populate('0', length);
int p_length = strlen(tab1);
for (int j = p_length - 1; j >= 0; j--) {
    char* tmp = multiply_chars(tab1[j], t);
    v_shove(tmp, j);
    char* tmp2 = add_tables(result, tmp);
    delete[] result;
    result = tmp2;
    delete[] tmp;
}
cout << result << endl;
delete[] result;
delete[] tab1;

None of the methods used (that's populate, multiply_chars and add_tables) causes a leak when ran in an infinite loop. I've narrowed the leak to the

char* tmp2 = add_tables(result, tmp);
delete[] result;
result = tmp2;

part, but have no idea why it would happen.
I check for leaks by running snippets in an infinite loop and checking memory usage.
Any help would be appreciated! If need be I'll post the code of the methods used, but decided not to for the sake of brevity here. They all return new cstrings. Also, the t2 variable is there from when I was checking the array by array multiplication, which also leaked - decided to do array by value multiplication first.
(Now, to be completely honest this is one of the methods required for a school project, but it's such a miniscule part of it, that I thought it wouldn't hurt if I asked - the teacher isn't really big on helping with particular code problems)

The functions are:

char * add_tables(const char * table1, const char * table2)
{
    char* tmp1 = get_string_trailing("0",table1);
    char* tmp2 = get_string_trailing("0", table2);
    int l1 = strlen(tmp1), l2 = strlen(tmp2);
    if (l1 != l2) {
        if (l1 > l2) {
            char* t = resize_string(tmp2, l1 - l2, '0');
            delete[] tmp2;
            tmp2 = t;
        }
        else {
            char* t = resize_string(tmp1, l2 - l1, '0');
            delete[] tmp1;
            tmp1 = t;
        }
}
    int length = strlen(tmp1) + 2;
    char*result = new char[length];
    result[length - 1] = 0;
    int buffer = 0;
    for (int i = length - 2; i > 0; i--) {
        int t = buffer + (tmp1[i-1]-'0') + (tmp2[i-1]-'0');
        result[i] = (t% 10)+'0';
        buffer = (t - (t % 10))/10;
    }
    result[0] = buffer + '0';
    char* t = get_string_trailing("0", result);
    delete[]result;
    result = t;
    delete[]tmp1;
    delete[]tmp2;
    return result;
}
void v_shove(char *&c, int i)
{
    char* tmp = shove(c, i);
    delete[] c;
    c = tmp;
}
char * populate(const char populator, int length)
{
    char* result = new char[length + 1];
    result[length] = 0;
    for (int i = 0; i < length; i++) {
        result[i] = populator;
    }
    return result;
}
char * multiply_chars(const char c1,const char c2)
{
    char*result = new char[3];
    result[2] = 0;
    char tmp1 = c1 - '0', tmp2 = c2 - '0';
    result[1] = (tmp1*tmp2 % 10) + '0';
    result[0] = (tmp1*tmp2 - (tmp1*tmp2 % 10)) / 10 + '0';
    char* r = get_string_trailing("0", result);
    delete[] result;
    result = r;
    return result;
}
int get_length_trailing(const char * ignore,const char * table)
{
    int length = 0;
    int i = 0;
    bool flag = true;
    while (i < strlen(table)) {
        if (flag) {
            for (int j = 0; j < strlen(ignore); j++)
            if (table[i] == ignore[j])goto BREAKPOINT;
        }
        flag = false;
        length++;
    BREAKPOINT:i++;
    }
    return length;
}
char * get_string_trailing(const char * ignore,const char * table)
{
    int result_length = get_length_trailing(ignore, table);
    char* result = new char[result_length + 1];
    int counter = 0;
    int i = 0;
    bool flag = true;
    while (i < strlen(table)) {
        if (flag)
            for (int j = 0; j < strlen(ignore); j++)
                if (table[i] == ignore[j])goto BREAKPOINT;
        flag = false;
        result[counter] = table[i];
        counter++;
    BREAKPOINT:i++;
    }
    result[result_length] = 0;
    if (result_length == 0) return copy("0");
    return result;
}
char * shove(const char * table1, int index)
{
    char*result = "0";
    int length = strlen(table1) + index + 1;
    result = new char[length];
    result[length - 1] = 0;
    if (index > 0) {
        for (int i = 0; i < strlen(table1); i++)
            result[i] = table1[i];
        for (int i = 0; i < index; i++)
            result[strlen(table1) + i] = '0';
    }
    else {
        for (int i = 0; i < strlen(result); i++)
            result[i] = table1[i];
    }
    char* t = get_string_trailing("0", result);
    delete[] result;
    result = t;
    return result;
}

Body:
There is at least a memory leak in get_string_trailing: if result_length is zero, you return a copy and do not delete result. There are also confusions between "string" (such as "0") and 'char': with double quotes, the terminating string character (\0) is automatically appended to the string, while simple quotes only define a character. So "0" is made of 2 char in memory and can not be stored in a pointer (undefined behavior, overwriting memory).

To summarize: here you are writing C, not learning C++. If you have to deal with C strings (you are writing a low-level pilot in C or your professor still doesn't understand that C and C++ are different languages), at least use the functions of the string.h (in C) / cstring (in C++) header to minimize the chance of memory leak or undefined behavior. If you do not have to use C strings, use std::string and the string manipulation tools of the standard library. Your work will be much easier, and your code much less vulnerable to bugs:

#include <string>
#include <iostream>
using namespace std;

int main()
{
  string tab1("11")
  string t("2") // never use the single quotes for a string
  cout << stoi(tab1) * stoi(t) << endl;
  return;
}

That's it!


问:
Using a loop instead of loads of or statements in javascript
Im trying to get all the dates which a room is booked blocked in the datepicker i got this working with the buildin function isInvalidDate the problem is its static now and i need to add the || date.format('YYYY-MM-DD') == '<?php   echo $items['1'] ?>' for every item in the array.
Can i do this in some kinda loop? the output from the var_dump is: `

array(7) { [0]=> string(10) "2017-06-09" [1]=> string(10) "2017-06-10"
  [2]=> string(10) "2017-06-11" [3]=> string(10) "2017-06-12" [4]=>
  string(10) "2017-06-14" [5]=> string(10) "2017-06-15" [6]=> string(10)
  "2017-06-16" }

`
So every time the script will be used the amount of items in the array could be more or less.

```<code><script type="text/javascript">
$(function() {

  $('input[name="datefilter"]').daterangepicker({
      autoUpdateInput: false,
      linkedCalendars: false,
      selectPastInvalidDate: false,
      isInvalidDate: function(date) {
      if (date.format('YYYY-MM-DD') == '<?php   echo $items['0'] ?>' || date.format('YYYY-MM-DD') == '<?php   echo $items['1'] ?>') {
          return true;
      } else {
          return false;
      }
  },
      locale: {
          cancelLabel: 'Clear'
      }
  });

  $('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) {
      $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
  });

  $('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
      $(this).val('');
  });

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

答:
Use json_encode() to pass full array to a javascript variable and then use javascript array methods

```<code>var inValidDates = <?php echo json_encode($items) ?>;

$('input[name="datefilter"]').daterangepicker({
      ....
      isInvalidDate: function(date) {
         return inValidDates.indexOf(date.format('YYYY-MM-DD')) >-1;
      },
      .....
});
</code>```

Body:
Use json_encode() to pass full array to a javascript variable and then use javascript array methods

var inValidDates = <?php echo json_encode($items) ?>;

$('input[name="datefilter"]').daterangepicker({
      ....
      isInvalidDate: function(date) {
         return inValidDates.indexOf(date.format('YYYY-MM-DD')) >-1;
      },
      .....
});