问:
Django App Log level info not getting write into file
I have added below setting in Django for Info level log.

```<code>logger = logging.getLogger(__name__)
logging.basicConfig(LOGGING=settings.LOGGING)

LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
    'verbose': {
        'format': '%(asctime)s %(levelname)s %(message)s',
    },
},
'handlers': {
    'file': {
        'class': 'logging.handlers.TimedRotatingFileHandler',
        'formatter': 'verbose',
        'level': logging.INFO,
        'filename': '/logs/django/api.log',
        'interval': 1,
        'when': 'midnight',
        'encoding': 'utf8'
    },
},
'loggers': {
    'django': {
        'handlers': ['file'],
        'level': logging.INFO,
        'propagate': True,
    },
},
}
</code>```

If I change this level to Debug then it works properly but when I change it to INFO Level then the log will not be written into the file. Can somebody help?

答:
Try the following settings:

```<code>LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': 'test.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount': 5,
            'formatter':'standard',
        },
        'request_handler': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': 'django_request.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount': 5,
            'formatter':'standard',
        },
    },
    'loggers': {
        '': {
            'handlers': ['default'],
            'level': 'DEBUG',
            'propagate': True
        },
        'django.request': {
            'handlers': ['request_handler'],
            'level': 'DEBUG',
            'propagate': False
        },
    }
}
</code>```

In your code:

```<code>import logging

logger = logging.getLogger(__name__)

logger.info("My name is Info")
</code>```

Sample output:

```<code>2017-05-25 04:56:38,912 [INFO] api.views: API - initiate_scan view, new object created. Uid: cf3822b261790186297d30e4f5b448b2
</code>```

Body:
I have added below setting in Django for Info level log.

logger = logging.getLogger(__name__)
logging.basicConfig(LOGGING=settings.LOGGING)

LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
    'verbose': {
        'format': '%(asctime)s %(levelname)s %(message)s',
    },
},
'handlers': {
    'file': {
        'class': 'logging.handlers.TimedRotatingFileHandler',
        'formatter': 'verbose',
        'level': logging.INFO,
        'filename': '/logs/django/api.log',
        'interval': 1,
        'when': 'midnight',
        'encoding': 'utf8'
    },
},
'loggers': {
    'django': {
        'handlers': ['file'],
        'level': logging.INFO,
        'propagate': True,
    },
},
}

If I change this level to Debug then it works properly but when I change it to INFO Level then the log will not be written into the file. Can somebody help?

Body:
Try the following settings:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': 'test.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount': 5,
            'formatter':'standard',
        },
        'request_handler': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': 'django_request.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount': 5,
            'formatter':'standard',
        },
    },
    'loggers': {
        '': {
            'handlers': ['default'],
            'level': 'DEBUG',
            'propagate': True
        },
        'django.request': {
            'handlers': ['request_handler'],
            'level': 'DEBUG',
            'propagate': False
        },
    }
}

In your code:

import logging

logger = logging.getLogger(__name__)

logger.info("My name is Info")

Sample output:

2017-05-25 04:56:38,912 [INFO] api.views: API - initiate_scan view, new object created. Uid: cf3822b261790186297d30e4f5b448b2


来源: stackexchange

问:
Changing picture inside img on hover with css
I need to change  source URL on hover.

I have tried this but won't work :

This is my Css:

```<code>.nav > li > div {
    position: absolute;
    display: block;
    width: 100%;
    top: 38px;
    left: 0;
    opacity: 0;
    visibility: hidden;
    overflow: hidden;
    background: #ffffff;
    border-top-color: #5f7ec7;
    border-top-style: solid;
    border-top-width: 1px;
    border-bottom-color: #5f7ec7;
    border-bottom-style: solid;
    border-bottom-width: 1px;
    -webkit-transition: all .3s ease .15s;
    -moz-transition: all .3s ease .15s;
    -o-transition: all .3s ease .15s;
    -ms-transition: all .3s ease .15s;
    transition: all .3s ease .15s;
}
.nav > li:hover > div {
    opacity: 1;
    visibility: visible;
    overflow: visible;
}
</code>```

And This is my html:

```<code><ul class="nav" style="width: 100%">
    <li>
        Something
        <a title="D" itemprop="url" href="/Default.aspx"><span itemprop="name">Something</span><img src="/images/Top-Menu-Layer/arrow_122b87.gif" style="vertical-align:middle; padding-left:5px; height:4px; width:7px" /></a>
       </li>
</ul>
</code>```

I would like to change the content of the img tag inside the html via the css. How can I do it ? Any advice ?

答:
Use  content:url("imageURL"); Note[ This method only works in  chrome not in Firefox or IE ].

.image{
  width:100px;
  height:100px;
}

.image:hover{
    content:url("http://via.placeholder.com/350x150");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="image"/></code>```

The best method is to use javascript or if you want a complete css solution use background-image instead of img tag and change background-image on hover

ContentLicense: CC BY-SA 3.0

Body:
I need to change  source URL on hover.

I have tried this but won't work :

This is my Css:

.nav > li > div {
    position: absolute;
    display: block;
    width: 100%;
    top: 38px;
    left: 0;
    opacity: 0;
    visibility: hidden;
    overflow: hidden;
    background: #ffffff;
    border-top-color: #5f7ec7;
    border-top-style: solid;
    border-top-width: 1px;
    border-bottom-color: #5f7ec7;
    border-bottom-style: solid;
    border-bottom-width: 1px;
    -webkit-transition: all .3s ease .15s;
    -moz-transition: all .3s ease .15s;
    -o-transition: all .3s ease .15s;
    -ms-transition: all .3s ease .15s;
    transition: all .3s ease .15s;
}
.nav > li:hover > div {
    opacity: 1;
    visibility: visible;
    overflow: visible;
}

And This is my html:

        Something
        Something

I would like to change the content of the img tag inside the html via the css. How can I do it ? Any advice ?

Body:
Use  content:url("imageURL"); Note[ This method only works in  chrome not in Firefox or IE ].

.image{
  width:100px;
  height:100px;
}

.image:hover{
    content:url("http://via.placeholder.com/350x150");
}

<img class="image"/>

The best method is to use javascript or if you want a complete css solution use background-image instead of img tag and change background-image on hover


问:
How to unit test (in C#) that a button is clicked?
I have a user control that has button whose click event handler contains the core logic. I want to test this button click handler.
This handler function calls a public function of another user control (which resides in separate C# project) which ultimately calls public function of a reference assembly.
Can anyone please tell me - how will be the unit test for such a handler?</p>

答:
In unit testing, we test the Unit - in this case, the user control. And nothing more. But we shouldn't allow the user control to access outside world, we should use mocking techniques.
In example, if your UserControlA calls UserControlB, create an interface for UserControlB and replace it with a mock UserControlB :

```<code>   class UserControlA {
       UserControlBInterface BReference;
       public void setBReference(UserControlBInterface reference) { this.BReference = reference };
       void OnClick (...) { BReference.callAMethod(); }
   }
   class MockupForB : UserControlBInterface {
       boolean called=false;
       public void callAMethod() { this.called = true; }

   }
   class TesterA : UnitTest {
       public void testOnClick()
       {   UserControlA a  = new UserControlA();  MockupForB mockup = new MockupForB(); a.setBReference(mockup);
           a.Button1.PerformClick(...); //following Aaronontheweb's advice
           assertTrue(mockup.called,"the method callAMethod not being called by UserControlA");
       }
   }
</code>```

And to ensure UserControlB indeed calls a reference library, this belongs to unit test for UserControlB.

Body:
In unit testing, we test the Unit - in this case, the user control. And nothing more. But we shouldn't allow the user control to access outside world, we should use mocking techniques.
In example, if your UserControlA calls UserControlB, create an interface for UserControlB and replace it with a mock UserControlB :

   class UserControlA {
       UserControlBInterface BReference;
       public void setBReference(UserControlBInterface reference) { this.BReference = reference };
       void OnClick (...) { BReference.callAMethod(); }
   }
   class MockupForB : UserControlBInterface {
       boolean called=false;
       public void callAMethod() { this.called = true; }

   }
   class TesterA : UnitTest {
       public void testOnClick()
       {   UserControlA a  = new UserControlA();  MockupForB mockup = new MockupForB(); a.setBReference(mockup);
           a.Button1.PerformClick(...); //following Aaronontheweb's advice
           assertTrue(mockup.called,"the method callAMethod not being called by UserControlA");
       }
   }

And to ensure UserControlB indeed calls a reference library, this belongs to unit test for UserControlB.

ContentLicense: CC BY-SA 2.5


问:
Tree Hierarchy in Oracle
I just came across this question from 'HackerRank'.
The BST table contains two columns, N and P. N stands for Node, P stands for Parent:

```<code> N  P
-- --
 1  2
 3  2
 6  8
 9  8
 2  5
 8  5
 5  null
</code>```

Sample Output should be:

1 leaf
2 inner
3 leaf
5 root
6 leaf
8 inner
9 leaf
```

<p>What I have tried is : </p>

```select     N,
           case
               when level = 3 then 'leaf'
               when level = 2 then 'inner'
               else 'root'
           end
from       BST
start with P is NULL
connect by P = prior N
order by   N;
```

Although it gives the correct result, I  am not happy with the code as it hardcodes the name (whether it should be leaf, inner or root). Also this code will fail when there are multiple hierarchies in the tree.

Can someone please suggest any other elegant way of writing the same code so that it does not fail for multiple hierarchy?

答:
Please user Like below (For MS SQL Hierarchy)

;WITH Hierarchy(ChildId,  Generation,  ParentId)
   AS
   (
       SELECT  Id, 0 AS Generation, ParentId
              FROM Table_Name AS FirtGeneration
              WHERE ParentId IS NULL

       UNION ALL
        SELECT NextGeneration.Id, Parent.Generation + 1, Parent.ChildId
              FROM Table_Name AS NextGeneration
              INNER JOIN Hierarchy AS Parent ON NextGeneration.ParentId = Parent.ChildId

   )

SELECT *FROM Hierarchy  ORDER BY Generation;

Title: Tree Hierarchy in Oracle

Body:
I just came across this question from 'HackerRank'.
The BST table contains two columns, N and P. N stands for Node, P stands for Parent:

 N  P
-- --
 1  2
 3  2
 6  8
 9  8
 2  5
 8  5
 5  null

Sample Output should be:

1 leaf
2 inner
3 leaf
5 root
6 leaf
8 inner
9 leaf

What I have tried is :

select     N,
           case
               when level = 3 then 'leaf'
               when level = 2 then 'inner'
               else 'root'
           end
from       BST
start with P is NULL
connect by P = prior N
order by   N;

Although it gives the correct result, I  am not happy with the code as it hardcodes the name (whether it should be leaf, inner or root). Also this code will fail when there are multiple hierarchies in the tree.

Can someone please suggest any other elegant way of writing the same code so that it does not fail for multiple hierarchy?


问:
Can't pass converted array from query using whereIn
I can't pass the first query collection converting it to array. Here is my controller

```<code>$memberfilters = MemberProfile::join('membership_histories', 'membership_histories.profile_id', '=','member_profiles.id')
        ->select('member_profiles.id','member_profiles.last_name','member_profiles.first_name','member_profiles.middle_name','member_profiles.name_ext','member_profiles.birthday','member_profiles.encoded_by')
        ->addSelect(DB::raw('membership_histories.profile_id, membership_histories.log_reason, max(membership_histories.effective_date) as date, membership_histories.membership_type, membership_histories.country_name, membership_histories.sub_region_name'))
        ->orderBy('member_profiles.last_name','ASC')
        ->where('membership_histories.country_name', 'Philippines')
        ->groupBy('membership_histories.profile_id')
        ->orderBy('date', 'desc')
        ->get();

    $members = MemberProfile::join('membership_histories', 'membership_histories.profile_id', '=','member_profiles.id')
        ->whereIn('member_profiles.id', $memberfilters->toArray())
        ->get();
</code>```

I will be applying more where method on the second query $members, that's why I had to pass it to there using whereIn. With this logic, I get no results '0' in my blade view

@Alexey Mezenin
When I use ->whereIn('member_profiles.id', $memberfilters->pluck('id')), I get this error

ErrorException in ComputeAge.php line 13:
  Trying to get property of non-object

This is my ComputeAge.php

```<code>namespace App\Library;
use App\MemberProfile;
use DateTime;

class ComputeAge
{
// Compute age based on given birthday.
public static function show($id)
{
    $from = new DateTime(MemberProfile::find($id)->birthday);
    $to   = new DateTime('today');
    $age = $from->diff($to)->y;

    return $age;
}
}
</code>```

答:
You can solve your first issue with pluck() like Alexey answered. For your age computing issue. You can make use of carbon to do this.

```<code><?php

namespace App\Library;

use Carbon\Carbon;
use App\MemberProfile;

class ComputeAge
{
    public static function show($id)
    {
        $user = MemberProfile::findOrFail($id);
        $age = $user->birthday->diffInYears(Carbon::now(), false);
        return $age;
    }
}
</code>```

If your birthday field isn't an instance of carbon then do this.

```<code>$age = Carbon::parse($user->birthday)->diffInYears(Carbon::now(), false);
</code>```

If you don't need negative values for birthday values in the future then you can just call diffInYears().

Body:
I can't pass the first query collection converting it to array. Here is my controller

$memberfilters = MemberProfile::join('membership_histories', 'membership_histories.profile_id', '=','member_profiles.id')
        ->select('member_profiles.id','member_profiles.last_name','member_profiles.first_name','member_profiles.middle_name','member_profiles.name_ext','member_profiles.birthday','member_profiles.encoded_by')
        ->addSelect(DB::raw('membership_histories.profile_id, membership_histories.log_reason, max(membership_histories.effective_date) as date, membership_histories.membership_type, membership_histories.country_name, membership_histories.sub_region_name'))
        ->orderBy('member_profiles.last_name','ASC')
        ->where('membership_histories.country_name', 'Philippines')
        ->groupBy('membership_histories.profile_id')
        ->orderBy('date', 'desc')
        ->get();

    $members = MemberProfile::join('membership_histories', 'membership_histories.profile_id', '=','member_profiles.id')
        ->whereIn('member_profiles.id', $memberfilters->toArray())
        ->get();

I will be applying more where method on the second query $members, that's why I had to pass it to there using whereIn. With this logic, I get no results '0' in my blade view

@Alexey Mezenin
When I use ->whereIn('member_profiles.id', $memberfilters->pluck('id')), I get this error

ErrorException in ComputeAge.php line 13:
  Trying to get property of non-object

This is my ComputeAge.php

namespace App\Library;
use App\MemberProfile;
use DateTime;

class ComputeAge
{
// Compute age based on given birthday.
public static function show($id)
{
    $from = new DateTime(MemberProfile::find($id)->birthday);
    $to   = new DateTime('today');
    $age = $from->diff($to)->y;

    return $age;
}
}

Body:
You can solve your first issue with pluck() like Alexey answered. For your age computing issue. You can make use of carbon to do this.

<?php

namespace App\Library;

use Carbon\Carbon;
use App\MemberProfile;

class ComputeAge
{
    public static function show($id)
    {
        $user = MemberProfile::findOrFail($id);
        $age = $user->birthday->diffInYears(Carbon::now(), false);
        return $age;
    }
}

If your birthday field isn't an instance of carbon then do this.

$age = Carbon::parse($user->birthday)->diffInYears(Carbon::now(), false);

If you don't need negative values for birthday values in the future then you can just call diffInYears().


问:
Optimizing postgres contains (LIKE) query in django for CHAR field
So I've got a query for a search endpoint in my Django (postgres) backend like so:

```<code>widgets = Widgets.objects.\
    filter(user=request.user).\
    filter(title__icontains="marketing director").\
    distinct('url')[:250]
</code>```

title is a CHAR field (models.CharField(max_length=255, blank=True) in django).

contains here of course amounts to a '%LIKE%' query in Postgres. I want specifically this (ie: NOT an infix 'LIKE%' search).

I'd like to speed up that query.

It seems like most optimizations for postgres text search are only for TEXT fields - is there any way to speed up exact string searches on a CHAR column?

I could use Postgres trigram indices, but I don't actually need the fuzzy/mispelling-type search. Though I'd happily use it if it's actually just faster for some reason.

Or would I be better off converting those columns to TEXT, taking the storage increase hit, and better indexing them somehow?

答:
The only way so use an index with a LIKE pattern that starts with % (is not anchored at the beginning) is to use a trigram index.

It does not matter if you define the attributes as character or text, since they will be converted to text anyway.

Do your data contain a lot of trailing blanks? Other than that, I cannot see how text could waste storage space.

Body:
So I've got a query for a search endpoint in my Django (postgres) backend like so:

widgets = Widgets.objects.\
    filter(user=request.user).\
    filter(title__icontains="marketing director").\
    distinct('url')[:250]

title is a CHAR field (models.CharField(max_length=255, blank=True) in django).

contains here of course amounts to a '%LIKE%' query in Postgres. I want specifically this (ie: NOT an infix 'LIKE%' search).

I'd like to speed up that query.

It seems like most optimizations for postgres text search are only for TEXT fields - is there any way to speed up exact string searches on a CHAR column?

I could use Postgres trigram indices, but I don't actually need the fuzzy/mispelling-type search. Though I'd happily use it if it's actually just faster for some reason.

Or would I be better off converting those columns to TEXT, taking the storage increase hit, and better indexing them somehow?


问:
AttributeError: 'module' object has no attribute 'to_numeric' in Pandas
The following code is throwing AttributeError on a server where the version of Pandas is 0.16.2 whereas it runs fine on my machine where version is 0.20.

```<code>df = pandas.read_csv('filename', header = None, error_bad_lines = False, warn_bad_lines =True,quoting=csv.QUOTE_NONE)

df = df.drop(df[pandas.to_numeric(df[599], errors='coerce').isnull()].index)
</code>```

The error message is the following:

```<code>Traceback (most recent call last):
  File "train_model.py", line 11, in <module>
    df = df.drop(df[pandas.to_numeric(df[599], errors='coerce').isnull()].index)
AttributeError: 'module' object has no attribute 'to_numeric'
</code>```

Is there a way to avoid this error in 0.16.2 version? The update to the server is not possible.

答:
If you notice in the pandas documentation of what's new in version 0.17,
you shall notice

pd.to_numeric is a new function to coerce strings to numbers (possibly with coercion) (GH11133)

Hence, pandas 0.16 does not have the function pd.to_numeric . However you can use this function to achieve the same purpose.

```<code>df = df.drop(df[df[599].astype(float).isnull()].index)
</code>```

Body:
The following code is throwing AttributeError on a server where the version of Pandas is 0.16.2 whereas it runs fine on my machine where version is 0.20.

df = pandas.read_csv('filename', header = None, error_bad_lines = False, warn_bad_lines =True,quoting=csv.QUOTE_NONE)

df = df.drop(df[pandas.to_numeric(df[599], errors='coerce').isnull()].index)

The error message is the following:

Traceback (most recent call last):
  File "train_model.py", line 11, in <module>
    df = df.drop(df[pandas.to_numeric(df[599], errors='coerce').isnull()].index)
AttributeError: 'module' object has no attribute 'to_numeric'

Is there a way to avoid this error in 0.16.2 version? The update to the server is not possible.

Body:
If you notice in the pandas documentation of what's new in version 0.17,
you shall notice

pd.to_numeric is a new function to coerce strings to numbers (possibly with coercion) (GH11133)

Hence, pandas 0.16 does not have the function pd.to_numeric . However you can use this function to achieve the same purpose.

df = df.drop(df[df[599].astype(float).isnull()].index)


问:
How to pass a (byte[] lpData) with integer value to RegSetValueExW P/Invoke
I have this P/Invoke RegSetValueExW that sets the value to the registry key. in C#

```<code>[DllImport("coredll.dll", EntryPoint = "RegSetValueExW")]
public static extern int RegSetValueExW(uint hKey, string lpValueName,
            uint lpReserved,
            uint lpType,
            byte[] lpData,
            uint lpcbData);
</code>```

I'm having a problem with the 4th param byte[] lpdata. I need to pass a DWORD with a value of 5 (int) in it. Everything is OK if I pass a string (REG_SZ), just need to convert using the GetBytes function.

If I call GetBytes("5") it converts it to ascii value
of 53 so it writes 53 on the registry value instead of 5

答: Use REG_DWORD instead of REG_SZ and then use BitConverter.GetBytes(Int32) to convert the int to a byte[].</p>

OwnerDisplayName: Roy Astro

Body:
I have this P/Invoke RegSetValueExW that sets the value to the registry key. in C#

[DllImport("coredll.dll", EntryPoint = "RegSetValueExW")]
public static extern int RegSetValueExW(uint hKey, string lpValueName,
            uint lpReserved,
            uint lpType,
            byte[] lpData,
            uint lpcbData);

I'm having a problem with the 4th param byte[] lpdata. I need to pass a DWORD with a value of 5 (int) in it. Everything is OK if I pass a string (REG_SZ), just need to convert using the GetBytes function.

If I call GetBytes("5") it converts it to ascii value
of 53 so it writes 53 on the registry value instead of 5

OwnerDisplayName: Stu Mackellar

LastEditorDisplayName: Stu Mackellar


问:
Is the native AAC decoder available when using Android NDK?
I'm looking for a way to decode AAC natively to PCM on Android. The decoder source code is at https://android.googlesource.com/platform/external/opencore/+/master/codecs_v2/audio/aac/dec, but I'm not familiar with NDK at all.

1) There's no way of doing this directly using the Android SDK, but can this be done via the NDK?

2) I would especially be interested in a simple way of accessing the decoder from SDK, with a short "bridge" through the NDK.  Is this feasible?

3) Would such a solution work all Android versions (1.5-2.2)?

4) I guess I could use http://code.google.com/p/aacplayer-android/ instead, but it looks like this implementation is fairly CPU intensive.  Does anyone have experiences with this?

答: One thing you may look into is the FFMpeg stuff, it is GPL and TuneIn radio posted their mods here: http://radiotime.com/mobile/android#/support/open-source</p>


问:
Spring-cloud Zuul retry when instance is down
Using Spring-cloud Angel.SR6:

Here is the configuration of my Spring-boot app with @EnableZuulProxy:

```<code>server.port=8765

ribbon.ConnectTimeout=500
ribbon.ReadTimeout=5000
ribbon.MaxAutoRetries=1
ribbon.MaxAutoRetriesNextServer=1
ribbon.OkToRetryOnAllOperations=true

zuul.routes.service-id.retryable=true
</code>```

I have 2 instances of service-id running on random ports.  These instances, as well as the Zuul instance, successfully register with Eureka, and I can access RESTful endpoints on the 2 service-id instances by accessing http://localhost:8765/service-id/.... and find that they are balanced in a round-robin manner.

I would like to kill one of the service-id instances and, when that defunct instance is next in line for forwarding, have Zuul attempt to contact it, fail, and retry with the other instance.

Is this possible, or am I misreading the documentation?  When I try the above config, the request 'destined' for the defunct instance fails with a 500 Forwarding error.  From the Zuul stacktrace:

```<code>com.netflix.zuul.exception.ZuulException: Forwarding error
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:140)

....

Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: service-idRibbonCommand timed-out and no fallback available
</code>```

The subsequent request succeeds as expected.  This behavior continues until the defunct instance is removed from Zuul's registry.

EDIT: Updated to Brixton.M5.  No change in behavior.  Here's the Hystrix exception in more detail:

```<code>Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: service-id timed-out and no fallback available.
    at com.netflix.hystrix.AbstractCommand$16.call(AbstractCommand.java:806) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$16.call(AbstractCommand.java:790) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:99) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at com.netflix.hystrix.AbstractCommand$DeprecatedOnFallbackHookApplication$1.onError(AbstractCommand.java:1521) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$FallbackHookApplication$1.onError(AbstractCommand.java:1411) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:314) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:306) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable.unsafeSubscribe(Observable.java:7710) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:100) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:958) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:978) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:100) ~[hystrix-core-1.4.23.jar:1.4.23]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_66]
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_66]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_66]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_66]
    ... 1 common frames omitted

Caused by: java.util.concurrent.TimeoutException: null
    at com.netflix.hystrix.AbstractCommand$9.call(AbstractCommand.java:601) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$9.call(AbstractCommand.java:581) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:99) ~[rxjava-1.0.14.jar:1.0.14]
    ... 15 common frames omitted
</code>```

答:
Ribbon uses the registered serviced in eureka, so it is up to eureka to update service status and let caller knows the available servers.

In my understanding, when one server is down, there are 2 ways to know:

1. wait for eureka server to update service status. But this update will take some time, 30 seconds as default.

2. try to call and mark it as down, (maybe will confirm with eureka server later)

So, in you question, you said after the first request failed, subsequent request succeeds. I think it is right behavior.

Body:
Using Spring-cloud Angel.SR6:

Here is the configuration of my Spring-boot app with @EnableZuulProxy:

server.port=8765

ribbon.ConnectTimeout=500
ribbon.ReadTimeout=5000
ribbon.MaxAutoRetries=1
ribbon.MaxAutoRetriesNextServer=1
ribbon.OkToRetryOnAllOperations=true

zuul.routes.service-id.retryable=true

I have 2 instances of service-id running on random ports.  These instances, as well as the Zuul instance, successfully register with Eureka, and I can access RESTful endpoints on the 2 service-id instances by accessing http://localhost:8765/service-id/.... and find that they are balanced in a round-robin manner.

I would like to kill one of the service-id instances and, when that defunct instance is next in line for forwarding, have Zuul attempt to contact it, fail, and retry with the other instance.

Is this possible, or am I misreading the documentation?  When I try the above config, the request 'destined' for the defunct instance fails with a 500 Forwarding error.  From the Zuul stacktrace:

com.netflix.zuul.exception.ZuulException: Forwarding error
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:140)

....

Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: service-idRibbonCommand timed-out and no fallback available

The subsequent request succeeds as expected.  This behavior continues until the defunct instance is removed from Zuul's registry.

EDIT: Updated to Brixton.M5.  No change in behavior.  Here's the Hystrix exception in more detail:

Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: service-id timed-out and no fallback available.
    at com.netflix.hystrix.AbstractCommand$16.call(AbstractCommand.java:806) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$16.call(AbstractCommand.java:790) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:99) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at com.netflix.hystrix.AbstractCommand$DeprecatedOnFallbackHookApplication$1.onError(AbstractCommand.java:1521) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$FallbackHookApplication$1.onError(AbstractCommand.java:1411) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:314) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:306) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable.unsafeSubscribe(Observable.java:7710) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:100) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:958) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:978) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:100) ~[hystrix-core-1.4.23.jar:1.4.23]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_66]
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_66]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_66]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_66]
    ... 1 common frames omitted

Caused by: java.util.concurrent.TimeoutException: null
    at com.netflix.hystrix.AbstractCommand$9.call(AbstractCommand.java:601) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$9.call(AbstractCommand.java:581) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:99) ~[rxjava-1.0.14.jar:1.0.14]
    ... 15 common frames omitted


问:
Native Linking errors in xamarin
I am try to compile my xamarin project today and suddenly i am getting these errors:

error MT5210: Native linking failed, undefined symbol:
  _mono_handle_global_vregs. Please verify that all the necessary frameworks have been referenced and native libraries are properly
  linked in.

  error MT5210: Native linking failed, undefined symbol:
  _mono_inst_name. Please verify that all the necessary frameworks have been referenced and native libraries are properly linked in.

  error
  MT5210: Native linking failed, undefined symbol: _mono_local_deadce.
  Please verify that all the necessary frameworks have been referenced
  and native libraries are properly linked in.

  error MT5210: Native
  linking failed, undefined symbol: _mono_print_code. Please verify that
  all the necessary frameworks have been referenced and native libraries
  are properly linked in.

  error MT5210: Native linking failed, undefined
  symbol: _mono_type_to_regmove. Please verify that all the necessary
  frameworks have been referenced and native libraries are properly
  linked in.

  error MT5210: Native linking failed, undefined symbol:
  _type_to_eval_stack_type. Please verify that all the necessary frameworks have been referenced and native libraries are properly
  linked in.

  error MT5202: Native linking failed. Please review the
  build log.

Can any one point me in any direction why these could be happening?

I have a Firebase iOS sdk added to the solution as binding project

答: How i solved this: I had to uninstall Google Cloud Messaging and replaced it with Firebase Cloud Messaging and all works fine now.</p>

Title: Native Linking errors in xamarin


问:
Java/JMS - Processing number of messages with handling failure scenarios
I have a requirement where I have to process number of messages. These messages will be inserted into a DB table by another process. All I have to do is to check for new messages in DB and send it to corresponding customer either email or http, depending on their configuration. The number of messages could be several thousands at any given time and the number of customers are around 1000.

I am planning to design this the way producer consumer works. Like producer thread polls DB for new messages and puts them into Queue and worker threads read these messages and processes.

At first it looked like JMS is the right solution for this requirement. But am seeking if any better alternatively like ExecutorService, using Threadpool suitable for this requirement given the following scenarios.

if one message delivery fails, I will have to retry it several times at least for 24 hours.

if one message delivery fails for a customer, all chances that other message delivery will also fail. So, I should try to send the first message before I process next message for that customer.

That means if I have one queue for all messages for all customers, then if one message fails, others will not be processed.

Can someone give me suggestion on how best I can handle this?

Thanks in advance.

答:
Retry logic is relatively easy to implement with generic JMS: no transactions, assign message a retry attribute, increment it with each retry, pause in listener when retrying, quit after limit is exhausted.

Queue per customer is the simplest configuration. Dynamic queues may help you with customers: create a queue and a listener for each customer dynamically.

Actually polling database reliably may present more challenge for you.


问:
Highlight filtered element in row angularjs
I have a table that filteres out operator and asset using simple inline ng-repeat angular filter.
However in some rows there are more than one operator (ie., second row) which I'm displaying inside scroll.When filtered by operator the rows are getting filtered but not able to display in the row(have to scroll to see the filtered result) the exact operator that is selected .

Example: When selected operator Jill ,I want to see Jill as its inside the row hidden under scroll.

Plunker link

HTML Snippet:

```<code> <tr ng-repeat="item in items | filter:truckName| filter:operatorName">
                  <td>
                    <div ng-class="{'set-height':item.assetOperator.length>'1'}" ng-if="item.assetOperator.length>0">
                     <span ng-repeat="operator in item.assetOperator">
                     {{operator.name}},
                     </span>
                     </div>
                  </td>
                  <td>{{item.assetName}}</td>
               </tr>
</code>```

答:
Try use filter service for this.write filter as following :
I doesn't write this filter.

and for hide other elements use filter in second ng-repeat loop.

```<code>app.filter('highlight', function() {
return function(text, selectedWord) {
  if(selectedWord) {
    var pattern = new RegExp(selectedWord, "g");
    return text.replace(pattern, '<span class="highlighted">' + selectedWord + '</span>');
  }
  else {
    return text;
   }
 };
});
</code>```

Demo

Body:
I have a table that filteres out operator and asset using simple inline ng-repeat angular filter.
However in some rows there are more than one operator (ie., second row) which I'm displaying inside scroll.When filtered by operator the rows are getting filtered but not able to display in the row(have to scroll to see the filtered result) the exact operator that is selected .

Example: When selected operator Jill ,I want to see Jill as its inside the row hidden under scroll.

Plunker link

HTML Snippet:

'1'}" ng-if="item.assetOperator.length>0">

                     {{operator.name}},

                  {{item.assetName}}

Body:
Try use filter service for this.write filter as following :
I doesn't write this filter.

and for hide other elements use filter in second ng-repeat loop.

app.filter('highlight', function() {
return function(text, selectedWord) {
  if(selectedWord) {
    var pattern = new RegExp(selectedWord, "g");
    return text.replace(pattern, '<span class="highlighted">' + selectedWord + '</span>');
  }
  else {
    return text;
   }
 };
});

Demo


问:
I would like to know about backup policy in any RTOS
I am studying RTOS and its backup policy.

Is there any RTOS which has backup policy like save data from SRAM to non-volatile memory before power failure?

It does not have to be an RTOS. any OS is ok :)

Does anybody have an documentation about it?

Best,
Mirae

答: This is not really the responsibility of the RTOS but something which needs to be designed in to the system if required, whether or not using a RTOS. Issues can occur if a power failure occurs during writing to the non-volatile memory. There are numerous methods of managing this, such as having the non-volatile memory mirrored and checked with a CRC, so that if there is a power failure only one copy is corrupted.</p>


问:
RatingBar is getting semi-transparent
I'm using RecyclerView with RatingBar in each row. Now, sometimes part of RatingBars are drawn incorrectly. After leaving a screen and going back it's all back to normal. I have no idea why this is happening, I even removed any styles from RatingBar so it should have default appearance.

This is how it looks:

Tested on Nexus 6P (Android 7.1.1).
Also tested on Samsung Galaxy J3 (2016) (Android 5.1.1) and there's no problem here.

I've also added

```<code>holder.rbRating.requestLayout();
</code>```

in onBindViewHolder(). It reduces the problem a bit, but it's still present. When I scroll a "bad" row out of a screen when it's reused it looks fine.

Here's row layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="@dimen/main_margin_top"
    android:paddingBottom="@dimen/main_margin_top"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/tvRatingTitle"
        android:text="Czystość wody"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RatingBar
        android:id="@+id/rbRating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:isIndicator="true"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/tvRatingTitle"
        android:numStars="5"
        android:rating="2.5"
        android:stepSize="0.1" />

    <CheckBox
        android:id="@+id/chkMissing"
        android:text="Zaznacz jeśli nie ma"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/rbRating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
</code>```

I've also tried switching to android.support.v7.widget.AppCompatRatingBar, but it doesn't make any difference.

EDIT:

@Muhib Pirani solution seems to be working, but I have 2 small issues:

1) on Nexus 6P the first layer of star is offsetted by few pixels (zoom in to see):

2) On Samsung Galaxy J3 (2016) it looks like this:

I'm fine with borders, but I'd like them to be green (not gray, the background should be gray) in the empty stars as well.

答:
I also faced the same problem. I had to programmatically set colors to RatingBar like this and it worked:

```<code>LayerDrawable layerDrawable = (LayerDrawable) ratingBar.getProgressDrawable();
layerDrawable.getDrawable(2).setColorFilter(ContextCompat.getColor(context, R.color.colorPrimaryDark), PorterDuff.Mode.SRC_ATOP);
layerDrawable.getDrawable(1).setColorFilter(ContextCompat.getColor(context, R.color.colorPrimaryDark), PorterDuff.Mode.SRC_ATOP);
layerDrawable.getDrawable(0).setColorFilter(ContextCompat.getColor(context, R.color.editTextBor), PorterDuff.Mode.SRC_ATOP);//when not selected color.
</code>```

Keep layerDrawable.getDrawable(2) and layerDrawable.getDrawable(1) same color.

Title: RatingBar is getting semi-transparent

Body:
I'm using RecyclerView with RatingBar in each row. Now, sometimes part of RatingBars are drawn incorrectly. After leaving a screen and going back it's all back to normal. I have no idea why this is happening, I even removed any styles from RatingBar so it should have default appearance.

This is how it looks:

Tested on Nexus 6P (Android 7.1.1).
Also tested on Samsung Galaxy J3 (2016) (Android 5.1.1) and there's no problem here.

I've also added

holder.rbRating.requestLayout();

in onBindViewHolder(). It reduces the problem a bit, but it's still present. When I scroll a "bad" row out of a screen when it's reused it looks fine.

Here's row layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="@dimen/main_margin_top"
    android:paddingBottom="@dimen/main_margin_top"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/tvRatingTitle"
        android:text="Czystość wody"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RatingBar
        android:id="@+id/rbRating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:isIndicator="true"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/tvRatingTitle"
        android:numStars="5"
        android:rating="2.5"
        android:stepSize="0.1" />

    <CheckBox
        android:id="@+id/chkMissing"
        android:text="Zaznacz jeśli nie ma"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/rbRating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

I've also tried switching to android.support.v7.widget.AppCompatRatingBar, but it doesn't make any difference.

EDIT:

@Muhib Pirani solution seems to be working, but I have 2 small issues:

1) on Nexus 6P the first layer of star is offsetted by few pixels (zoom in to see):

2) On Samsung Galaxy J3 (2016) it looks like this:

I'm fine with borders, but I'd like them to be green (not gray, the background should be gray) in the empty stars as well.

Body:
I also faced the same problem. I had to programmatically set colors to RatingBar like this and it worked:

LayerDrawable layerDrawable = (LayerDrawable) ratingBar.getProgressDrawable();
layerDrawable.getDrawable(2).setColorFilter(ContextCompat.getColor(context, R.color.colorPrimaryDark), PorterDuff.Mode.SRC_ATOP);
layerDrawable.getDrawable(1).setColorFilter(ContextCompat.getColor(context, R.color.colorPrimaryDark), PorterDuff.Mode.SRC_ATOP);
layerDrawable.getDrawable(0).setColorFilter(ContextCompat.getColor(context, R.color.editTextBor), PorterDuff.Mode.SRC_ATOP);//when not selected color.

Keep layerDrawable.getDrawable(2) and layerDrawable.getDrawable(1) same color.


问:
React Native Android app white screen won't start
I get the following error log when I run my Android app: http://pastebin.com/1jHEfdQ3 The app sometimes crashes in the simulator but most of the time it just displays a white screen. I can console.log one or two things until the app won't respond. R-R to refresh doesn't work. None of the dev tools work. I'm stumped with what to do at this point.

I'm running react native 0.38.0

EDIT:

I've tried cleaning my gradle and deleting and reinstalling my node modules.

One thing to note is that I am using React Native Navigation which means I had to modify MainApplication and MainActivity to the following:

MainActivity:

```<code>package com.prayerrequest;

import com.facebook.react.ReactActivity;
import com.reactnativenavigation.NavigationApplication;
import com.airbnb.android.react.maps.MapsPackage;
import com.cmcewen.blurview.BlurViewPackage;
import io.realm.react.RealmReactPackage;
import com.reactnativenavigation.controllers.SplashActivity;

public class MainActivity extends SplashActivity {

}
</code>```

MainApplication:

```<code>package com.prayerrequest;

import com.facebook.react.ReactPackage;

import com.cmcewen.blurview.BlurViewPackage;
import io.realm.react.RealmReactPackage;
import com.airbnb.android.react.maps.MapsPackage;

import com.reactnativenavigation.NavigationApplication;

import java.util.Arrays;
import java.util.List;

  public class MainApplication extends NavigationApplication {
    @Override
     public boolean isDebug() {
         // Make sure you are using BuildConfig from your own application
         return BuildConfig.DEBUG;
     }

     @Override
     public List<ReactPackage> createAdditionalReactPackages() {
        return Arrays.<ReactPackage>asList(
          new RealmReactPackage(),
          new BlurViewPackage(),
          new MapsPackage()
        );
     }
  }
</code>```

I've crossposted on React Native's issues page here

答:
I had a similar problem. I would get this white screen when trying to get it to run on device.

The problem was when I would do adb devices or react-native run-android I would get "ADB is Not Recognized as an internal or external command".

So my fix was to add the path to adb.exe's parent directory to my Environment Variables and then restart my command prompts.I then ran react-native run-android and on startup no more red screen showing the completely useless error message Error calling AppRegistry.runApplication! :)

So I found ADB was located in my folder:

C:\Users\dell\AppData\Local\Android\sdk\platform-tools\adb.exe
I am on a Windows 10 system. dell is my user name of the computer.

So I went to System Environment Variables then found "Path" then clicked "Edit", then clicked "New" and added in "C:\Users\dell\AppData\Local\Android\sdk\platform-tools".

Body:
I get the following error log when I run my Android app: http://pastebin.com/1jHEfdQ3 The app sometimes crashes in the simulator but most of the time it just displays a white screen. I can console.log one or two things until the app won't respond. R-R to refresh doesn't work. None of the dev tools work. I'm stumped with what to do at this point.

I'm running react native 0.38.0

EDIT:

I've tried cleaning my gradle and deleting and reinstalling my node modules.

One thing to note is that I am using React Native Navigation which means I had to modify MainApplication and MainActivity to the following:

MainActivity:

package com.prayerrequest;

import com.facebook.react.ReactActivity;
import com.reactnativenavigation.NavigationApplication;
import com.airbnb.android.react.maps.MapsPackage;
import com.cmcewen.blurview.BlurViewPackage;
import io.realm.react.RealmReactPackage;
import com.reactnativenavigation.controllers.SplashActivity;

public class MainActivity extends SplashActivity {

}

MainApplication:

package com.prayerrequest;

import com.facebook.react.ReactPackage;

import com.cmcewen.blurview.BlurViewPackage;
import io.realm.react.RealmReactPackage;
import com.airbnb.android.react.maps.MapsPackage;

import com.reactnativenavigation.NavigationApplication;

import java.util.Arrays;
import java.util.List;

  public class MainApplication extends NavigationApplication {
    @Override
     public boolean isDebug() {
         // Make sure you are using BuildConfig from your own application
         return BuildConfig.DEBUG;
     }

     @Override
     public List<ReactPackage> createAdditionalReactPackages() {
        return Arrays.<ReactPackage>asList(
          new RealmReactPackage(),
          new BlurViewPackage(),
          new MapsPackage()
        );
     }
  }

I've crossposted on React Native's issues page here


问:
Android GET and POST Request
Can anyone point me to a good implementation of a way to send GET and POST Requests. They are alot of ways to do these, and i am looking for the best implementation. Secondly is there a generic way to send both these methods rather then using two different ways. After all the GET method merely has the params in the Query Strings, whereas the POST method uses the headers for the Params.

Thanks.

答:
```<code>private RequestListener listener;
private int requestId;
private HashMap<String, String> reqParams;
private File file;
private String fileName;
private RequestMethod reqMethod;
private String url;
private Context context;
private boolean isProgressVisible = false;
private MyProgressDialog progressDialog;

public NetworkClient(Context context, int requestId, RequestListener listener,
                     String url, HashMap<String, String> reqParams, RequestMethod reqMethod,
                     boolean isProgressVisible) {

    this.listener = listener;
    this.requestId = requestId;
    this.reqParams = reqParams;
    this.reqMethod = reqMethod;
    this.url = url;
    this.context = context;
    this.isProgressVisible = isProgressVisible;
}

public NetworkClient(Context context, int requestId, RequestListener listener,
                     String url, HashMap<String, String> reqParams, File file, String fileName, RequestMethod reqMethod,
                     boolean isProgressVisible) {

    this.listener = listener;
    this.requestId = requestId;
    this.reqParams = reqParams;
    this.file = file;
    this.fileName = fileName;
    this.reqMethod = reqMethod;
    this.url = url;
    this.context = context;
    this.isProgressVisible = isProgressVisible;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    if (isProgressVisible) {
        showProgressDialog();
    }
}

@Override
protected String doInBackground(Void... params) {

    try {

        if (Utils.isInternetAvailable(context)) {

            OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
            clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
            clientBuilder.writeTimeout(10, TimeUnit.SECONDS);
            clientBuilder.readTimeout(20, TimeUnit.SECONDS);
            OkHttpClient client = clientBuilder.build();

            if (reqMethod == RequestMethod.GET) {

                Request.Builder reqBuilder = new Request.Builder();
                reqBuilder.url(url);
                Request request = reqBuilder.build();
                Response response = client.newCall(request).execute();
                String message = response.message();
                String res = response.body().string();

                JSONObject jObj = new JSONObject();
                jObj.put("statusCode", 1);
                jObj.put("response", message);
                return jObj.toString();

            } else if (reqMethod == RequestMethod.POST) {

                FormBody.Builder formBuilder = new FormBody.Builder();

                RequestBody body = formBuilder.build();

                Request.Builder reqBuilder = new Request.Builder();
                reqBuilder.url(url);
                reqBuilder.post(body);
                Request request = reqBuilder.build();
                Response response = client.newCall(request).execute();

                String res = response.body().string();

                JSONObject jObj = new JSONObject();
                jObj.put("statusCode", 1);
                jObj.put("response", res);
                return jObj.toString();

            } else if (reqMethod == RequestMethod.MULTIPART) {

                MediaType MEDIA_TYPE = fileName.endsWith("png") ?
                        MediaType.parse("image/png") : MediaType.parse("image/jpeg");

                MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
                multipartBuilder.setType(MultipartBody.FORM);

                multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(MEDIA_TYPE, file));

                RequestBody body = multipartBuilder.build();

                Request.Builder reqBuilder = new Request.Builder();
                reqBuilder.url(url);
                reqBuilder.post(body);
                Request request = reqBuilder.build();
                Response response = client.newCall(request).execute();
                String res = response.body().string();

                JSONObject jObj = new JSONObject();
                jObj.put("statusCode", 1);
                jObj.put("response", res);
                return jObj.toString();
            }

        } else {

            JSONObject jObj = new JSONObject();
            jObj.put("statusCode", 0);
            jObj.put("response", context.getString(R.string.no_internet));
            return jObj.toString();
        }
    } catch (final Exception e) {
        e.printStackTrace();
        JSONObject jObj = new JSONObject();
        try {
            jObj.put("statusCode", 0);
            jObj.put("response", e.toString());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return jObj.toString();
    }

    return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    try {
        JSONObject jObj = new JSONObject(result);
        if (jObj.getInt("statusCode") == 1) {
            listener.onSuccess(requestId, jObj.getString("response"));
        } else {
            listener.onError(requestId, jObj.getString("response"));
        }
    } catch (Exception e) {
        listener.onError(requestId, result);
    } finally {
        dismissProgressDialog();
    }
}

private void showProgressDialog() {
    progressDialog = new MyProgressDialog(context);
}

private void dismissProgressDialog() {
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.dismiss();
        progressDialog = null;
    }
}

private static NetworkManager instance = null;
private Set<RequestListener> arrRequestListeners = null;
private int requestId;
public boolean isProgressVisible = false;

private NetworkManager() {
    arrRequestListeners = new HashSet<>();
    arrRequestListeners = Collections.synchronizedSet(arrRequestListeners);
}

public static NetworkManager getInstance() {
    if (instance == null)
        instance = new NetworkManager();
    return instance;
}

public synchronized int addRequest(final HashMap<String, String> params, Context context, RequestMethod reqMethod, String apiMethod) {

    try {

        String url = Constants.WEBSERVICE_URL + apiMethod;
        requestId = UniqueNumberUtils.getInstance().getUniqueId();

        NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, reqMethod, isProgressVisible);
        networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } catch (Exception e) {
        onError(requestId, e.toString() + e.getMessage());
    }

    return requestId;
}

public synchronized int addMultipartRequest(final HashMap<String,String> params, File file, String fileName, Context context, RequestMethod reqMethod, String apiMethod) {

    try {

        String url = Constants.WEBSERVICE_URL + apiMethod;
        requestId = UniqueNumberUtils.getInstance().getUniqueId();

        NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, file, fileName, reqMethod, isProgressVisible);
        networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } catch (Exception e) {
        onError(requestId, e.toString() + e.getMessage());
    }

    return requestId;
}

public void isProgressBarVisible(boolean isProgressVisible) {
    this.isProgressVisible = isProgressVisible;
}

public void setListener(RequestListener listener) {
    try {
        if (listener != null && !arrRequestListeners.contains(listener)) {
            arrRequestListeners.add(listener);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onSuccess(int id, String response) {

    if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
        for (RequestListener listener : arrRequestListeners) {
            if (listener != null)
                listener.onSuccess(id, response);
        }
    }
}

@Override
public void onError(int id, String message) {
    try {
        if (Looper.myLooper() == null) {
            Looper.prepare();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
        for (final RequestListener listener : arrRequestListeners) {
            if (listener != null) {
                listener.onError(id, message);
            }
        }
    }
}

public void removeListener(RequestListener listener) {
    try {
        arrRequestListeners.remove(listener);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Create RequestListner intreface

```<code>public void onSuccess(int id, String response);

public void onError(int id, String message);
</code>```

Get Unique Number

```<code>private static UniqueNumberUtils INSTANCE = new UniqueNumberUtils();

private AtomicInteger seq;

private UniqueNumberUtils() {
    seq = new AtomicInteger(0);
}

public int getUniqueId() {
    return seq.incrementAndGet();
}

public static UniqueNumberUtils getInstance() {
    return INSTANCE;
}
</code>```

Title: Android GET and POST Request

Body:
private RequestListener listener;
private int requestId;
private HashMap<String, String> reqParams;
private File file;
private String fileName;
private RequestMethod reqMethod;
private String url;
private Context context;
private boolean isProgressVisible = false;
private MyProgressDialog progressDialog;

public NetworkClient(Context context, int requestId, RequestListener listener,
                     String url, HashMap<String, String> reqParams, RequestMethod reqMethod,
                     boolean isProgressVisible) {

    this.listener = listener;
    this.requestId = requestId;
    this.reqParams = reqParams;
    this.reqMethod = reqMethod;
    this.url = url;
    this.context = context;
    this.isProgressVisible = isProgressVisible;
}

public NetworkClient(Context context, int requestId, RequestListener listener,
                     String url, HashMap<String, String> reqParams, File file, String fileName, RequestMethod reqMethod,
                     boolean isProgressVisible) {

    this.listener = listener;
    this.requestId = requestId;
    this.reqParams = reqParams;
    this.file = file;
    this.fileName = fileName;
    this.reqMethod = reqMethod;
    this.url = url;
    this.context = context;
    this.isProgressVisible = isProgressVisible;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    if (isProgressVisible) {
        showProgressDialog();
    }
}

@Override
protected String doInBackground(Void... params) {

    try {

        if (Utils.isInternetAvailable(context)) {

            OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
            clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
            clientBuilder.writeTimeout(10, TimeUnit.SECONDS);
            clientBuilder.readTimeout(20, TimeUnit.SECONDS);
            OkHttpClient client = clientBuilder.build();

            if (reqMethod == RequestMethod.GET) {

                Request.Builder reqBuilder = new Request.Builder();
                reqBuilder.url(url);
                Request request = reqBuilder.build();
                Response response = client.newCall(request).execute();
                String message = response.message();
                String res = response.body().string();

                JSONObject jObj = new JSONObject();
                jObj.put("statusCode", 1);
                jObj.put("response", message);
                return jObj.toString();

            } else if (reqMethod == RequestMethod.POST) {

                FormBody.Builder formBuilder = new FormBody.Builder();

                RequestBody body = formBuilder.build();

                Request.Builder reqBuilder = new Request.Builder();
                reqBuilder.url(url);
                reqBuilder.post(body);
                Request request = reqBuilder.build();
                Response response = client.newCall(request).execute();

                String res = response.body().string();

                JSONObject jObj = new JSONObject();
                jObj.put("statusCode", 1);
                jObj.put("response", res);
                return jObj.toString();

            } else if (reqMethod == RequestMethod.MULTIPART) {

                MediaType MEDIA_TYPE = fileName.endsWith("png") ?
                        MediaType.parse("image/png") : MediaType.parse("image/jpeg");

                MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
                multipartBuilder.setType(MultipartBody.FORM);

                multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(MEDIA_TYPE, file));

                RequestBody body = multipartBuilder.build();

                Request.Builder reqBuilder = new Request.Builder();
                reqBuilder.url(url);
                reqBuilder.post(body);
                Request request = reqBuilder.build();
                Response response = client.newCall(request).execute();
                String res = response.body().string();

                JSONObject jObj = new JSONObject();
                jObj.put("statusCode", 1);
                jObj.put("response", res);
                return jObj.toString();
            }

        } else {

            JSONObject jObj = new JSONObject();
            jObj.put("statusCode", 0);
            jObj.put("response", context.getString(R.string.no_internet));
            return jObj.toString();
        }
    } catch (final Exception e) {
        e.printStackTrace();
        JSONObject jObj = new JSONObject();
        try {
            jObj.put("statusCode", 0);
            jObj.put("response", e.toString());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return jObj.toString();
    }

    return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    try {
        JSONObject jObj = new JSONObject(result);
        if (jObj.getInt("statusCode") == 1) {
            listener.onSuccess(requestId, jObj.getString("response"));
        } else {
            listener.onError(requestId, jObj.getString("response"));
        }
    } catch (Exception e) {
        listener.onError(requestId, result);
    } finally {
        dismissProgressDialog();
    }
}

private void showProgressDialog() {
    progressDialog = new MyProgressDialog(context);
}

private void dismissProgressDialog() {
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.dismiss();
        progressDialog = null;
    }
}

private static NetworkManager instance = null;
private Set<RequestListener> arrRequestListeners = null;
private int requestId;
public boolean isProgressVisible = false;

private NetworkManager() {
    arrRequestListeners = new HashSet<>();
    arrRequestListeners = Collections.synchronizedSet(arrRequestListeners);
}

public static NetworkManager getInstance() {
    if (instance == null)
        instance = new NetworkManager();
    return instance;
}

public synchronized int addRequest(final HashMap<String, String> params, Context context, RequestMethod reqMethod, String apiMethod) {

    try {

        String url = Constants.WEBSERVICE_URL + apiMethod;
        requestId = UniqueNumberUtils.getInstance().getUniqueId();

        NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, reqMethod, isProgressVisible);
        networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } catch (Exception e) {
        onError(requestId, e.toString() + e.getMessage());
    }

    return requestId;
}

public synchronized int addMultipartRequest(final HashMap<String,String> params, File file, String fileName, Context context, RequestMethod reqMethod, String apiMethod) {

    try {

        String url = Constants.WEBSERVICE_URL + apiMethod;
        requestId = UniqueNumberUtils.getInstance().getUniqueId();

        NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, file, fileName, reqMethod, isProgressVisible);
        networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } catch (Exception e) {
        onError(requestId, e.toString() + e.getMessage());
    }

    return requestId;
}

public void isProgressBarVisible(boolean isProgressVisible) {
    this.isProgressVisible = isProgressVisible;
}

public void setListener(RequestListener listener) {
    try {
        if (listener != null && !arrRequestListeners.contains(listener)) {
            arrRequestListeners.add(listener);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onSuccess(int id, String response) {

    if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
        for (RequestListener listener : arrRequestListeners) {
            if (listener != null)
                listener.onSuccess(id, response);
        }
    }
}

@Override
public void onError(int id, String message) {
    try {
        if (Looper.myLooper() == null) {
            Looper.prepare();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
        for (final RequestListener listener : arrRequestListeners) {
            if (listener != null) {
                listener.onError(id, message);
            }
        }
    }
}

public void removeListener(RequestListener listener) {
    try {
        arrRequestListeners.remove(listener);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Create RequestListner intreface

public void onSuccess(int id, String response);

public void onError(int id, String message);

Get Unique Number

private static UniqueNumberUtils INSTANCE = new UniqueNumberUtils();

private AtomicInteger seq;

private UniqueNumberUtils() {
    seq = new AtomicInteger(0);
}

public int getUniqueId() {
    return seq.incrementAndGet();
}

public static UniqueNumberUtils getInstance() {
    return INSTANCE;
}


问:
Need a way around this JSON Null exception
I fire a query and the result comes in JSON.I set it using setters.here is my Dataclass:

```<code>private String userstory;
private String task;
private int actual;
private int estimate;
private String ref;
private String uid;
private String tid;
--setters--
</code>```

Here is my main class:

```<code>for(JsonElement result : taskresponse.getResults())
    {
        JsonObject results = result.getAsJsonObject();
        MyData myData = new MyData(results.get("WorkProduct").getAsJsonObject().get("Name").getAsString(),results.get("Name").getAsString(),
        (int) Double.parseDouble(results.get("Actuals").getAsString()),
        (int) Double.parseDouble(results.get("Estimate").getAsString()),
        results.get("_ref").getAsString(),
        results.get("WorkProduct").getAsJsonObject().get("FormattedID").getAsString(),results.get("FormattedID").getAsString());
        data_list.add(myData);
    }
</code>```

When I get value int in fields "Actuals" and "Estimate" it is working well. But sometimes I get values null as the result from query. Thus I get JSONNULLEXCEPTION.
How should i handle this exception.I ultimately want the fields to be set 0 when query returns null.
Thanks

答:
This is the very bad style to pass values in Constructor or Methods. You should always set value first in a local variable and then pass it.

Check below solution

```<code>for(JsonElement result : taskresponse.getResults())
{
    JsonObject results = result.getAsJsonObject();

    private int tempActual = results.has("Actuals") ? results.get("Actuals") != null ? results.getInt("Actuals") : 0: 0;
    private int tempEstimate = results.has("Estimate") ? results.get("Estimate") != null ? results.getInt("Estimate") : 0: 0;;

    //You can use all variables like this

    MyData myData = new MyData(results.get("WorkProduct").getAsJsonObject().get("Name").getAsString(),results.get("Name").getAsString(),tempActual,tempEstimate,
    results.get("_ref").getAsString(),
    results.get("WorkProduct").getAsJsonObject().get("FormattedID").getAsString(),results.get("FormattedID").getAsString());
    data_list.add(myData);
}
</code>```

Body:
I fire a query and the result comes in JSON.I set it using setters.here is my Dataclass:

private String userstory;
private String task;
private int actual;
private int estimate;
private String ref;
private String uid;
private String tid;
--setters--

Here is my main class:

for(JsonElement result : taskresponse.getResults())
    {
        JsonObject results = result.getAsJsonObject();
        MyData myData = new MyData(results.get("WorkProduct").getAsJsonObject().get("Name").getAsString(),results.get("Name").getAsString(),
        (int) Double.parseDouble(results.get("Actuals").getAsString()),
        (int) Double.parseDouble(results.get("Estimate").getAsString()),
        results.get("_ref").getAsString(),
        results.get("WorkProduct").getAsJsonObject().get("FormattedID").getAsString(),results.get("FormattedID").getAsString());
        data_list.add(myData);
    }

When I get value int in fields "Actuals" and "Estimate" it is working well. But sometimes I get values null as the result from query. Thus I get JSONNULLEXCEPTION.
How should i handle this exception.I ultimately want the fields to be set 0 when query returns null.
Thanks

Body:
This is the very bad style to pass values in Constructor or Methods. You should always set value first in a local variable and then pass it.

Check below solution

for(JsonElement result : taskresponse.getResults())
{
    JsonObject results = result.getAsJsonObject();

    private int tempActual = results.has("Actuals") ? results.get("Actuals") != null ? results.getInt("Actuals") : 0: 0;
    private int tempEstimate = results.has("Estimate") ? results.get("Estimate") != null ? results.getInt("Estimate") : 0: 0;;

    //You can use all variables like this

    MyData myData = new MyData(results.get("WorkProduct").getAsJsonObject().get("Name").getAsString(),results.get("Name").getAsString(),tempActual,tempEstimate,
    results.get("_ref").getAsString(),
    results.get("WorkProduct").getAsJsonObject().get("FormattedID").getAsString(),results.get("FormattedID").getAsString());
    data_list.add(myData);
}


问:
Uncaught Error: Call to undefined function
It was working but now it stops working why? it soppiest to write into a file and save it. it was working yesterday but today it stops and I can't figure out why a search the internet but still nothing I can't .</p>
```<code><!DOCTYPE html>
<html>
<head>
    <title>Contact us</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="aboutus.html">About US</a></li>
                <li><a href="contactus.php">Contact Us</a></li>
                <li><a href="property.php">Propertys</a></li>
            </ul>

        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>

<h1>Contact us</h1>

<form  method="post" action="contactus.php" >

    <label>Email</label>
    <input type="text" name="email" required>
    <br>
    <label>Mobile number</label>
    <input type="number" name="number" required>
    <br>
    <textarea name="comments" required></textarea>

    <button name="submit" type="submit"> submit</button>

</form>

<?php
if(isset($_POST['submit'])){
    $number = $_POST["number"];
    $email = $_POST["email"];

    $trueemail;

    $massage = $_POST["comments"];

    if(isset($number)){

    if (strlen($number) == 8) {
        $truenumber = true;
    } else {
        echo "Input your mobile number";
    }
}

if(isset($email)){
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<br>";
        echo "Enter a valid email";
    } else {
        $trueemail = true;
    }
}

if($trueemail == true && $truenumber == true){
    writeToFile($email,$number,$massage);

    function writeToFile($trueemail,$truenumber,$massage) {

        $myfile = fopen("contectus.txt", "w") or die("Unable to open file!");
        fwrite($myfile, $trueemail . PHP_EOL);
        fwrite($myfile, $truenumber . PHP_EOL);
        fwrite($myfile, $massage . PHP_EOL);
        fclose($myfile);
    }
}
}
?>
</body>
</html>
</code>```

答:
Try below code:

put submit event starting of the page.

you cann't call function without defining before calling.

```<code><?php

function writeToFile($trueemail, $truenumber, $massage)
{

  $myfile = fopen("contectus.txt", "w") or die("Unable to open file!");
  fwrite($myfile, $trueemail . PHP_EOL);
  fwrite($myfile, $truenumber . PHP_EOL);
  fwrite($myfile, $massage . PHP_EOL);
  fclose($myfile);
}

if (isset($_POST['submit'])) {
  $number = $_POST["number"];
  $email = $_POST["email"];

  $trueemail;

  $massage = $_POST["comments"];

  if (isset($number)) {

    if (strlen($number) == 8) {

      $truenumber = true;
    } else {

      echo "Input your mobile number";

    }
  }

  if (isset($email)) {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      echo "<br>";
      echo "Enter a valid email";
    } else {
      $trueemail = true;
    }
  }

  if ($trueemail == true && $truenumber == true) {
    writeToFile($email, $number, $massage);
  }
} ?>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It was working but now it stops working why? it soppiest to write into a file and save it. it was working yesterday but today it stops and I can't figure out why a search the internet but still nothing I can't .

<!DOCTYPE html>

    <title>Contact us</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>

About US

Contact Us

Propertys

Contact us

<form  method="post" action="contactus.php" >

    Email
    <input type="text" name="email" required>

    Mobile number
    <input type="number" name="number" required>

    <textarea name="comments" required></textarea>

    <button name="submit" type="submit"> submit</button>

</form>

<?php
if(isset($_POST['submit'])){
    $number = $_POST["number"];
    $email = $_POST["email"];

    $trueemail;

    $massage = $_POST["comments"];

    if(isset($number)){

    if (strlen($number) == 8) {
        $truenumber = true;
    } else {
        echo "Input your mobile number";
    }
}

if(isset($email)){
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "
";
        echo "Enter a valid email";
    } else {
        $trueemail = true;
    }
}

if($trueemail == true && $truenumber == true){
    writeToFile($email,$number,$massage);

    function writeToFile($trueemail,$truenumber,$massage) {

        $myfile = fopen("contectus.txt", "w") or die("Unable to open file!");
        fwrite($myfile, $trueemail . PHP_EOL);
        fwrite($myfile, $truenumber . PHP_EOL);
        fwrite($myfile, $massage . PHP_EOL);
        fclose($myfile);
    }
}
}
?>

Body:
Try below code:

put submit event starting of the page.

you cann't call function without defining before calling.

<?php

function writeToFile($trueemail, $truenumber, $massage)
{

  $myfile = fopen("contectus.txt", "w") or die("Unable to open file!");
  fwrite($myfile, $trueemail . PHP_EOL);
  fwrite($myfile, $truenumber . PHP_EOL);
  fwrite($myfile, $massage . PHP_EOL);
  fclose($myfile);
}

if (isset($_POST['submit'])) {
  $number = $_POST["number"];
  $email = $_POST["email"];

  $trueemail;

  $massage = $_POST["comments"];

  if (isset($number)) {

    if (strlen($number) == 8) {

      $truenumber = true;
    } else {

      echo "Input your mobile number";

    }
  }

  if (isset($email)) {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      echo "<br>";
      echo "Enter a valid email";
    } else {
      $trueemail = true;
    }
  }

  if ($trueemail == true && $truenumber == true) {
    writeToFile($email, $number, $massage);
  }
} ?>


问:
why the image doesn't open?
I have use a Q_PROPERTY to set source of an Image in my qml file. the qml file is in a resource but the source path is out of resource so I set the prepend equal to file://. when it tries to open the Image, this error occurs but the path is true:

qrc:/MainWindow.qml:34:9: QML Image: Cannot open: file:///home/me/Pictures/05.Jun.2017_00:23:57:149.jpg
  how can I fix it?

答:
Show code with your resource file structure OR you can debug it first by using following code. First try to add it manually in your QML if its working then you can check for accessing it from Q_Property. Don't use "file://"

```<code>Image {
    anchors.fill: parent
    source: "qrc:/Images/Images/hello.png"
}
</code>```

Title: why the image doesn't open?

Body:
Show code with your resource file structure OR you can debug it first by using following code. First try to add it manually in your QML if its working then you can check for accessing it from Q_Property. Don't use "file://"

Image {
    anchors.fill: parent
    source: "qrc:/Images/Images/hello.png"
}


问:
Java FX Scene builder didn't recognize css custom color constants(or variables)
If the Defined css is plain, scene builder renders the controls with the defined styles...

but if css custom color constants are used, scene builder renders the controls in white...

When I run the application, the style is applied properly(this is done by javaFX libraries) for the scene

note: linking the css file in the scene builder with preview > Scene StyleSheets > add a StyleSheet is implied and that's why the basic stylesheet(without the css color constants) was working.

My Question is:

How do I make it(Scene builder) understand the CSS(color constants) styles

CSS:

```<code>.root {
   -color1: #1BA1E2;
   -color2: #F8F8F8;

   -primary-color: -color1;
   -secondary-color: -color2;
}

.windowbox {
    -fx-border-radius: 50 0 50 0;
    -fx-background-radius: 50 0 50 0;
    -fx-background-color: -primary-color;
}

.lbl {
    -fx-background-color: derive(-primary-color, -10%);
    -fx-text-fill: -secondary-color;
}
</code>```

the above css works perfectly during execution (in the runtime) but scene builder is oblivious to the styles

答:
In Scene Builder, select Preview, then Scene Style Sheets, then Add a Style Sheet, as described here. Then select your .css file. To get more info, use the CSS Analyzer functionality.

Also, since your example uses the css class selector ("."), be sure to reference the style class in your fxml (e.g., styleClass="lbl").

Alternatively, you can use the css id selector ("#"). With that approach, you can specify an id in the fxml (id="lbl"). Or you can omit the id attribute from your fxml and by default the fx:id value will be used as the css id selector (fx:id="lbl").

Some info here and here.

Body:
If the Defined css is plain, scene builder renders the controls with the defined styles...

but if css custom color constants are used, scene builder renders the controls in white...

When I run the application, the style is applied properly(this is done by javaFX libraries) for the scene

note: linking the css file in the scene builder with preview > Scene StyleSheets > add a StyleSheet is implied and that's why the basic stylesheet(without the css color constants) was working.

My Question is:

How do I make it(Scene builder) understand the CSS(color constants) styles

CSS:

.root {
   -color1: #1BA1E2;
   -color2: #F8F8F8;

   -primary-color: -color1;
   -secondary-color: -color2;
}

.windowbox {
    -fx-border-radius: 50 0 50 0;
    -fx-background-radius: 50 0 50 0;
    -fx-background-color: -primary-color;
}

.lbl {
    -fx-background-color: derive(-primary-color, -10%);
    -fx-text-fill: -secondary-color;
}

the above css works perfectly during execution (in the runtime) but scene builder is oblivious to the styles


问:
MJPEG Image conversion problem
i am facing problem to convert an image to a defined size. i am converting from one image to another image of small size. The command i am executing is:

C:/xampp/htdocs/jcert6/seyretfiles/tools/converter/ffmpeg.exe -i "c:\knowledge base\videos\user_62\RHSSNet_Image_Library\images\Touchport_II\CD302_14_TPII_17in_PPR_Scanner.jpg" -y -f mjpeg -s 72x92 -vframes 1 -an c:/xampp/htdocs/jcert6/seyretfiles/uploads/thumbnails/user_62/user_62_tmu2qsgo0fr1j5w61292302705_0.jpg

and i am getting the following error:

[mjpeg @ 01de0050] unhandled pixel format 0x11111111

[image2 01cfd080] could not find codec parameters

c:\knowledge base\videos\user_62\RHSSNet_Image_Library\images\Touchport_II\CD302_14_TPII_17in_PPR_Scanner.jpg :could not find codec parameters

please help me :( :(

答:
The simplest solution is to use the appropriate software which is
http://www.imagemagick.org/

Edit: Once installed the command is:

```<code>convert original.jpg -resample 72x92 smaller.jpg
</code>```

Title: MJPEG Image conversion problem

Body:
The simplest solution is to use the appropriate software which is
http://www.imagemagick.org/

Edit: Once installed the command is:

convert original.jpg -resample 72x92 smaller.jpg


问:
Excel VBA: Insert N number of Sheets based on cell value
I'm new in Excel VBA. I want to insert number of cells based on a cell value.

I have sheet1, i want to use b4 as a reference as to the number of sheets (which is a template) to be inserted.

Example, if value of b4 = 4, I'd like to copy the template sheet 4 times.

How do i do that in vba?

THANKS. :)

答:
No magic, create them one by one in a loop, place each new one at the end. Edit: You want also to rename them 1, 2, 3, 4,.. so:</p>

```<code>Sub CreateSheets()
    Dim i As Long
    With ThisWorkbook.Sheets
      For i = 1 To Sheet1.Range("B4").Value2
        .Item("Template").Copy After:=.Item(.Count)
        .Item(.Count).Name = i
      Next
    End With
End Sub
</code>```

Body:
No magic, create them one by one in a loop, place each new one at the end. Edit: You want also to rename them 1, 2, 3, 4,.. so:

Sub CreateSheets()
    Dim i As Long
    With ThisWorkbook.Sheets
      For i = 1 To Sheet1.Range("B4").Value2
        .Item("Template").Copy After:=.Item(.Count)
        .Item(.Count).Name = i
      Next
    End With
End Sub


问:
NodeMCU version unknown
I'm new with NodeMCU firmware use. I have a Amica ESP-12E (v2?) dev kit connected to a DHT22 which I program using the Arduino IDE. All is setup and working fine.
My problem came when I wanted to update NodeMCU firmware. Since I don't really know what came pre installed from China, I downloaded ESPlorer to try to determine NodeMCU version. I get the following "error" when I reset the dev board:

Communication with MCU..Got answer! Communication with MCU established.
AutoDetect firmware...

Can't autodetect firmware, because proper answer not received (may be unknown firmware).
Please, reset module or continue.

{{a long string of weird characters that I can't copy and paste appear here}}

At this point I'm totally clueless about what version of firmware I have. Is there a way to obtain NodeMCU firmware version by software via Arduino IDE code, ESPlorer GUI or something similar?

On the other hand, is there a really easy way to compile/download latest NodeMCU firmware BIN file? Even one with all the modules active will be fine for me now, I'm just trying to understand and test things.

答:
As pointed out you have several options for firmware and you'll need to make a choice as to which suits you going forward. If you are going to stick with the Nodemcu LUA firmware you can determine the version by typing:

```<code>    print(node.info())
</code>```

at the command line prompt.

There are alternatives to using ESPlorer e.g. Putty or Coolterm that will give you the raw output from the device with no interpretation. So if you have the correct serial port settings and the device plugged into the USB port it will show the banner when you reset giving an indication of the origin and version of the installed firmware.

Title: NodeMCU version unknown

Body:
As pointed out you have several options for firmware and you'll need to make a choice as to which suits you going forward. If you are going to stick with the Nodemcu LUA firmware you can determine the version by typing:

    print(node.info())

at the command line prompt.

There are alternatives to using ESPlorer e.g. Putty or Coolterm that will give you the raw output from the device with no interpretation. So if you have the correct serial port settings and the device plugged into the USB port it will show the banner when you reset giving an indication of the origin and version of the installed firmware.


问:
can't open tensorboard 0.0.0.0:6006 or localhost:6006
when i use tensorboard in cmd with win10

D:\python document\tensorflow>tensorboard --logdir=D:\python document\tensorflow
Starting TensorBoard b'47' at http://0.0.0.0:6006

But when i open the webpage，it shows

"dial tcp 0.0.0.0:6006: connectex: The requested address is not valid in its context."

and i tried localhost:6006 then,and it shows

"No scalar data was found."

so what should i do now

答:
Refer to tensorflow issue#9701.

Run tensorboard --logdir=YOUR_LOG_DIR --host=127.0.0.1 in command prompt,
and type localhost:6006 in chrome, this works for me (Win10, anaconda4.3.16, python3.5.3, tensorflow1.1.0).