问:
Send Custom Error response from serializer in django rest framework?
I want to send a custom response from serializers create view to front-end of my application. I tried rest framework Response tutorials but it does not work. My code is:</p>

```<code>class UserSerializer(serializers.ModelSerializer):
"""Serializer to serialize user model object"""

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        """create a new user"""

        firstname = self.initial_data['first_name']
        lastname = self.initial_data['last_name']
        fullname = str(firstname) +" "+ str(lastname)
        email = self.initial_data['username'].lower()

        try:
           customer = User.create(
                name=fullname,
                email=email)

        except Error as e:
            error = {'message': e._message or 'Unknown error'}
            return Response(error,status=status.HTTP_400_BAD_REQUEST)
</code>```

答:
So you want to change the representation of the User (the shape of the JSON response) from this view. To do this you need to change the .to_representation(self, obj) method in the serializer:

```<code>class UserSerializer(serializers.ModelSerializer):
    """Serializer to serialize user model object"""
     class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name',)
        write_only_fields = ('id', 'password',)

    def to_representation(self, obj):
        return {
            'firstname': obj.first_name,
            'lastname': obj.last_name,
            'fullname': obj.first_name+' '+obj.last_name,
            'email': obj.username.lower()
        }
</code>```

This should mean that whenever a request is made that uses this serializer the user will only ever see those 4 fields in the JSON, e.g.

```<code>{
    "firstname":"Salman",
    "lastname": "Ahmed",
    "fullname": "Salman Ahmed",
    "email": "salman_ahmed@email.com"
}
</code>```

More details on this is hidden in their docs here.

Body:
I want to send a custom response from serializers create view to front-end of my application. I tried rest framework Response tutorials but it does not work. My code is:

class UserSerializer(serializers.ModelSerializer):
"""Serializer to serialize user model object"""

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        """create a new user"""

        firstname = self.initial_data['first_name']
        lastname = self.initial_data['last_name']
        fullname = str(firstname) +" "+ str(lastname)
        email = self.initial_data['username'].lower()

        try:
           customer = User.create(
                name=fullname,
                email=email)

        except Error as e:
            error = {'message': e._message or 'Unknown error'}
            return Response(error,status=status.HTTP_400_BAD_REQUEST)

Body:
So you want to change the representation of the User (the shape of the JSON response) from this view. To do this you need to change the .to_representation(self, obj) method in the serializer:

class UserSerializer(serializers.ModelSerializer):
    """Serializer to serialize user model object"""
     class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name',)
        write_only_fields = ('id', 'password',)

    def to_representation(self, obj):
        return {
            'firstname': obj.first_name,
            'lastname': obj.last_name,
            'fullname': obj.first_name+' '+obj.last_name,
            'email': obj.username.lower()
        }

This should mean that whenever a request is made that uses this serializer the user will only ever see those 4 fields in the JSON, e.g.

{
    "firstname":"Salman",
    "lastname": "Ahmed",
    "fullname": "Salman Ahmed",
    "email": "salman_ahmed@email.com"
}

More details on this is hidden in their docs here.


来源: stackexchange

问:
get the wanted objects from the array of objects
This is my first question in stackoverflow, So any kind of help is appreciated.

I have an array like this

```<code>var products = [{status:'available', ...},{status:'none', ...},{status:'available', ...},{status:'', ...},{status:'none', ...}]
</code>```

how can I get an array that contains only  products[i].status = 'available' .

I already did this with for loop but isn't there a better method? My code is practically full of loops now & it's not easy to read.

Thank you for you help.

答:
var products = [{status:'available'},{status:'none'},{status:'available'},{status:''},{status:'none'}];
for(var i = 0; i < products.length; i++){
if(products[i].status == products[0].status){
 console.log(this.products[i]);
}
}```

ContentLicense: CC BY-SA 3.0

Body:
This is my first question in stackoverflow, So any kind of help is appreciated.

I have an array like this

var products = [{status:'available', ...},{status:'none', ...},{status:'available', ...},{status:'', ...},{status:'none', ...}]

how can I get an array that contains only  products[i].status = 'available' .

I already did this with for loop but isn't there a better method? My code is practically full of loops now & it's not easy to read.

Thank you for you help.


问:
Is the SQL Server IsShutdown property useful to determine whether a database is in a good state?
My company has a tool that monitors statuses on servers, services, databases, etc. We monitor a number of on-site servers for our customers. One particular simple check performed is to determine whether a SQL Server database is in a 'good' state by querying for the value of certain database properties. The four database properties we monitor are:

IsSuspect

IsOffline

IsEmergencyMode

IsShutdown

This is the query we use:

```<code>SELECT name AS [SuspectDB],
  DATABASEPROPERTY(name, N'IsSuspect') AS [Suspect],
  DATABASEPROPERTY(name, N'IsOffline') AS [Offline],
  ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) AS [Shutdown],
  DATABASEPROPERTY(name, N'IsEmergencyMode') AS [Emergency]
FROM sysdatabases
WHERE (DATABASEPROPERTY(name, N'IsSuspect') = 1)
   OR (DATABASEPROPERTY(name, N'IsOffline') = 1)
   OR (ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) = 1)
   OR (DATABASEPROPERTY(name, N'IsEmergencyMode') = 1)
</code>```

In testing an upgrade to SQL Server 2008, it seems that quite a few of our databases are returning a 1 (true) value for the IsShutdown property. This was never the case previously with SQL Server 2005. The MSDN documentation for the property simply states "Database encountered a problem at startup".

As far as I can tell, the databases are perfectly fine. They are up, can be queried, etc. No issues.

Does the IsShutdown property really matter for my monitoring purposes, i.e., does it indicate that the database is in a bad state? Or should I just remove it from my query?

NOTE: In talking to one of our resident DBAs, they found that on some of our new SQL Server 2008 databases, the fact that the IsAutoClose property is enabled might have something to do with the reason for these databases having an IsShutdown of true. Disabling IsAutoClose seems to "fix" the IsShutdown being true.

答:
Did you read the footnote that is linked to specifically for NULL for that property, on the MSDN page you linked to?

Returned value is also NULL if the database has never been started or has been autoclosed.

And so yes, if you change the AutoClose property, you'll get different results. Coalescing NULL to 1 on this property seems like a bad decision - I'd remove your ISNULL() and ignore NULL values.

ContentLicense: CC BY-SA 2.5

Body:
My company has a tool that monitors statuses on servers, services, databases, etc. We monitor a number of on-site servers for our customers. One particular simple check performed is to determine whether a SQL Server database is in a 'good' state by querying for the value of certain database properties. The four database properties we monitor are:

IsSuspect

IsOffline

IsEmergencyMode

IsShutdown

This is the query we use:

SELECT name AS [SuspectDB],
  DATABASEPROPERTY(name, N'IsSuspect') AS [Suspect],
  DATABASEPROPERTY(name, N'IsOffline') AS [Offline],
  ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) AS [Shutdown],
  DATABASEPROPERTY(name, N'IsEmergencyMode') AS [Emergency]
FROM sysdatabases
WHERE (DATABASEPROPERTY(name, N'IsSuspect') = 1)
   OR (DATABASEPROPERTY(name, N'IsOffline') = 1)
   OR (ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) = 1)
   OR (DATABASEPROPERTY(name, N'IsEmergencyMode') = 1)

In testing an upgrade to SQL Server 2008, it seems that quite a few of our databases are returning a 1 (true) value for the IsShutdown property. This was never the case previously with SQL Server 2005. The MSDN documentation for the property simply states "Database encountered a problem at startup".

As far as I can tell, the databases are perfectly fine. They are up, can be queried, etc. No issues.

Does the IsShutdown property really matter for my monitoring purposes, i.e., does it indicate that the database is in a bad state? Or should I just remove it from my query?

NOTE: In talking to one of our resident DBAs, they found that on some of our new SQL Server 2008 databases, the fact that the IsAutoClose property is enabled might have something to do with the reason for these databases having an IsShutdown of true. Disabling IsAutoClose seems to "fix" the IsShutdown being true.


问:
Using dplyr for dynamic group_by
Trying to get my head around this dplyr thingy. I have a sorted data frame that I want to group based on a variable. However, the groups need to be constructed so that each of them have a minimum sum of 30 on the grouping variable.

Consider this small example data frame:

```<code>df1 <- matrix(data = c(05,0.9,95,12,0.8,31,
    16,0.8,28,17,0.7,10,
        23,0.8,11,55,0.6,9,
    56,0.5,12,57,0.2,1,
    59,0.4,1),
  ncol = 3,
  byrow = TRUE,
  dimnames = list(c(1:9),
    c('freq', 'mean', 'count')
  )
)
</code>```

Now, I want to group so that count have a sum of at least 30. freq and mean should then be collapsed into a weighted.mean where the weights is the count values. Note that the last "bin" reaches a sum of 32 by row 7, but since row 8:9 only sums to 2, I add them to the last "bin".

Like so:

```<code>freq   mean   count
 5.00  0.90   95
12.00  0.80   31
16.26  0.77   38
45.18  0.61   34
</code>```

The simple summarizing with dplyr is not a problem, but this I can't figure out. I do think the the solution is hidden somewhere here:

Dynamic Grouping in R | Grouping based on condition on applied function

But how to apply it to my situation escapes me.

答:
I wish I had a shorter solution but here is what I came up with.

First we define a custom cumsum function :

```<code>cumsum2 <- function(x){
  Reduce(function(.x,.y){
    if(tail(.x,1)>30) x1 <- 0 else x1 <- tail(.x,1) ;c(.x,x1+.y)},x,0)[-1]
}
# cumsum2(1:10)
# [1]  1  3  6 10 15 21 28 36  9 19
</code>```

Then we can have fun with the dplyr chain :

```<code>library(dplyr)
library(tidyr)

df1 %>%
  as.data.frame %>%                        # as you started with a matrix
  mutate(id = row_number(),                # we'll need this to sort in the end
         cumcount = cumsum2(count))    %>% # adding nex cumulate count
  `[<-`(.$cumcount < 30,"cumcount",NA) %>% # setting as NA values less than 30 ...
  fill(cumcount,.direction = "up")     %>% # ... in order to fill them with cumcount
  fill(cumcount,.direction = "down")   %>% # the last NAs belong to the last group so we fill down too
  group_by(cumcount)                   %>% # these are our new groups to aggregate freq and mean
  summarize(id = min(id),
            freq = sum(freq*count)/sum(count),
            mean = sum(mean*count)/sum(count)) %>%
  arrange(id)                          %>% # sort
  select(freq,mean,count=cumcount)         # and lay out as expected output

# # A tibble: 4 x 3
#       freq      mean count
#      <dbl>     <dbl> <dbl>
# 1  5.00000 0.9000000    95
# 2 12.00000 0.8000000    31
# 3 16.26316 0.7736842    38
# 4 45.17647 0.6117647    32
</code>```

Title: Using dplyr for dynamic group_by

Body:
Trying to get my head around this dplyr thingy. I have a sorted data frame that I want to group based on a variable. However, the groups need to be constructed so that each of them have a minimum sum of 30 on the grouping variable.

Consider this small example data frame:

df1 <- matrix(data = c(05,0.9,95,12,0.8,31,
    16,0.8,28,17,0.7,10,
        23,0.8,11,55,0.6,9,
    56,0.5,12,57,0.2,1,
    59,0.4,1),
  ncol = 3,
  byrow = TRUE,
  dimnames = list(c(1:9),
    c('freq', 'mean', 'count')
  )
)

Now, I want to group so that count have a sum of at least 30. freq and mean should then be collapsed into a weighted.mean where the weights is the count values. Note that the last "bin" reaches a sum of 32 by row 7, but since row 8:9 only sums to 2, I add them to the last "bin".

Like so:

freq   mean   count
 5.00  0.90   95
12.00  0.80   31
16.26  0.77   38
45.18  0.61   34

The simple summarizing with dplyr is not a problem, but this I can't figure out. I do think the the solution is hidden somewhere here:

Dynamic Grouping in R | Grouping based on condition on applied function

But how to apply it to my situation escapes me.

Body:
I wish I had a shorter solution but here is what I came up with.

First we define a custom cumsum function :

cumsum2 <- function(x){
  Reduce(function(.x,.y){
    if(tail(.x,1)>30) x1 <- 0 else x1 <- tail(.x,1) ;c(.x,x1+.y)},x,0)[-1]
}
# cumsum2(1:10)
# [1]  1  3  6 10 15 21 28 36  9 19

Then we can have fun with the dplyr chain :

library(dplyr)
library(tidyr)

df1 %>%
  as.data.frame %>%                        # as you started with a matrix
  mutate(id = row_number(),                # we'll need this to sort in the end
         cumcount = cumsum2(count))    %>% # adding nex cumulate count
  `[<-`(.$cumcount < 30,"cumcount",NA) %>% # setting as NA values less than 30 ...
  fill(cumcount,.direction = "up")     %>% # ... in order to fill them with cumcount
  fill(cumcount,.direction = "down")   %>% # the last NAs belong to the last group so we fill down too
  group_by(cumcount)                   %>% # these are our new groups to aggregate freq and mean
  summarize(id = min(id),
            freq = sum(freq*count)/sum(count),
            mean = sum(mean*count)/sum(count)) %>%
  arrange(id)                          %>% # sort
  select(freq,mean,count=cumcount)         # and lay out as expected output

# # A tibble: 4 x 3
#       freq      mean count
#      <dbl>     <dbl> <dbl>
# 1  5.00000 0.9000000    95
# 2 12.00000 0.8000000    31
# 3 16.26316 0.7736842    38
# 4 45.17647 0.6117647    32


问:
SELECT QUERY LIKE containing only specific words in a string
I have one table like below ,table name is js_skills_achievements

```<code>id   skill1  skill2  skill3  skill4
1     java    php    html    android
2     php     java   jquery  html
3     sql     php    html    jquery
</code>```

When admin search key is "java developer in nersupalli"

my query is below

```<code>SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java developer in nersupalli%'
   OR `skill2`  LIKE '%java developer in nersupalli%'
   OR `skill3`  LIKE '%java developer in nersupalli%'
   OR `skill4`  LIKE '%java developer in nersupalli%'
ORDER BY id DESC
LIMIT 10
</code>```

Its not working for me . My Requirement is i need to display all java records . here total 2 records in java . i.e id1,id2. But am getting empty rows.

Below ways only working

```<code>SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java%'
   OR `skill2`  LIKE '%java%'
   OR `skill3`  LIKE '%java%'
   OR `skill4`  LIKE '%java%'
ORDER BY id DESC
LIMIT 10
</code>```

I need based on string specified keyword search . can you any one please help on this . Am very appreciate. Thanks

答:
Add full text in your filed

```<code>ALTER TABLE `js_skills_achievements` ADD FULLTEXT(`skill1`);
ALTER TABLE `js_skills_achievements` ADD FULLTEXT(`skill2`);
ALTER TABLE `js_skills_achievements` ADD FULLTEXT(`skill3`);
ALTER TABLE `js_skills_achievements` ADD FULLTEXT(`skill4`);
</code>```

And then run this query

```<code>SELECT * FROM js_skills_achievements
WHERE MATCH(skill1,skill2,skill3,skill4) AGAINST ('java developer in nersupalli');
</code>```

Body:
I have one table like below ,table name is js_skills_achievements

id   skill1  skill2  skill3  skill4
1     java    php    html    android
2     php     java   jquery  html
3     sql     php    html    jquery

When admin search key is "java developer in nersupalli"

my query is below

SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java developer in nersupalli%'
   OR `skill2`  LIKE '%java developer in nersupalli%'
   OR `skill3`  LIKE '%java developer in nersupalli%'
   OR `skill4`  LIKE '%java developer in nersupalli%'
ORDER BY id DESC
LIMIT 10

Its not working for me . My Requirement is i need to display all java records . here total 2 records in java . i.e id1,id2. But am getting empty rows.

Below ways only working

SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java%'
   OR `skill2`  LIKE '%java%'
   OR `skill3`  LIKE '%java%'
   OR `skill4`  LIKE '%java%'
ORDER BY id DESC
LIMIT 10

I need based on string specified keyword search . can you any one please help on this . Am very appreciate. Thanks

Body:
Add full text in your filed

ALTER TABLE `js_skills_achievements` ADD FULLTEXT(`skill1`);
ALTER TABLE `js_skills_achievements` ADD FULLTEXT(`skill2`);
ALTER TABLE `js_skills_achievements` ADD FULLTEXT(`skill3`);
ALTER TABLE `js_skills_achievements` ADD FULLTEXT(`skill4`);

And then run this query

SELECT * FROM js_skills_achievements
WHERE MATCH(skill1,skill2,skill3,skill4) AGAINST ('java developer in nersupalli');


答:
A bit ugly way to do this is reverse your like clauses and match your string against columns

```<code>SELECT
  *
FROM
  js_skills_achievements
WHERE 'java developer in nersupalli' LIKE CONCAT('%',skill1,'%')
  OR 'java developer in nersupalli' LIKE CONCAT('%',skill2,'%')
  OR 'java developer in nersupalli' LIKE CONCAT('%',skill3,'%')
  OR 'java developer in nersupalli' LIKE CONCAT('%',skill4,'%')
  OR skill1  LIKE '%java developer in nersupalli%'
  OR skill2  LIKE '%java developer in nersupalli%'
  OR skill3  LIKE '%java developer in nersupalli%'
  OR skill4  LIKE '%java developer in nersupalli%'
ORDER BY id DESC
LIMIT 10
</code>```

Demo

Title: SELECT QUERY LIKE containing only specific words in a string

Body:
A bit ugly way to do this is reverse your like clauses and match your string against columns

SELECT
  *
FROM
  js_skills_achievements
WHERE 'java developer in nersupalli' LIKE CONCAT('%',skill1,'%')
  OR 'java developer in nersupalli' LIKE CONCAT('%',skill2,'%')
  OR 'java developer in nersupalli' LIKE CONCAT('%',skill3,'%')
  OR 'java developer in nersupalli' LIKE CONCAT('%',skill4,'%')
  OR skill1  LIKE '%java developer in nersupalli%'
  OR skill2  LIKE '%java developer in nersupalli%'
  OR skill3  LIKE '%java developer in nersupalli%'
  OR skill4  LIKE '%java developer in nersupalli%'
ORDER BY id DESC
LIMIT 10

Demo


问:
What are some best practices for optimizing multiple column LIKE SQL queries?
I have a search query that I'm inheriting and attempting to optimize. I am curious to hear if anyone has any best practices and recommendations for such.  The production server is still SQL Server 2000 also.

The query is an advanced customer search stored procedure that accepts 5 different search criteria parameters (i.e. first name, last name, address, phone, etc.) to search a multi-million record table.  There are indexes on all joined columns and columns in the WHERE clause.  In addition, the initial query dumps the records into a table variable for paging capacity.

```<code>INSERT INTO   @tempCustTable (CustomerID, FirstName, LastName, City, StateProvince, Zip, PhoneNumber)
SELECT  DISTINCT cu.CustomerID, cu.FirstName, cu.LastName, a.City,
a.StateProvince, a.Zip, p.PhoneNumber
FROM Customer cu WITH(NOLOCK)
LEFT OUTER JOIN Address a WITH(NOLOCK) ON cu.CustomerID = a.CustomerID
LEFT OUTER JOIN Phone p WITH(NOLOCK) ON cu.CustomerID = p.CustomerID
WHERE  (cu.LastName = @LastName OR cu.LastName LIKE @LastName + '%')
AND (@FirstName IS NULL OR cu.FirstName = @FirstName OR cu.FirstName LIKE @FirstName + '%')
AND (@StateProvince = '' OR a.StateProvince LIKE @StateProvince)
AND (@City = '' OR a.City LIKE @City + '%')
AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
ORDER BY cu.LastName, cu.FirstName
</code>```

Does anyone have any recommendations on how I could improve the performance of the query?

答:
I would try to not have my sql code add the '%' but instead expect the parameter to already have it, this of course, after you have validated it in your application! Then don't include '=' comparisons, use LIKE all the time:

WHERE  (cu.LastName LIKE @LastName)

instead of:

WHERE  (cu.LastName = @LastName OR cu.LastName LIKE @LastName + '%')

OwnerDisplayName: JamesEggers

Body:
I have a search query that I'm inheriting and attempting to optimize. I am curious to hear if anyone has any best practices and recommendations for such.  The production server is still SQL Server 2000 also.

The query is an advanced customer search stored procedure that accepts 5 different search criteria parameters (i.e. first name, last name, address, phone, etc.) to search a multi-million record table.  There are indexes on all joined columns and columns in the WHERE clause.  In addition, the initial query dumps the records into a table variable for paging capacity.

INSERT INTO   @tempCustTable (CustomerID, FirstName, LastName, City, StateProvince, Zip, PhoneNumber)
SELECT  DISTINCT cu.CustomerID, cu.FirstName, cu.LastName, a.City,
a.StateProvince, a.Zip, p.PhoneNumber
FROM Customer cu WITH(NOLOCK)
LEFT OUTER JOIN Address a WITH(NOLOCK) ON cu.CustomerID = a.CustomerID
LEFT OUTER JOIN Phone p WITH(NOLOCK) ON cu.CustomerID = p.CustomerID
WHERE  (cu.LastName = @LastName OR cu.LastName LIKE @LastName + '%')
AND (@FirstName IS NULL OR cu.FirstName = @FirstName OR cu.FirstName LIKE @FirstName + '%')
AND (@StateProvince = '' OR a.StateProvince LIKE @StateProvince)
AND (@City = '' OR a.City LIKE @City + '%')
AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
ORDER BY cu.LastName, cu.FirstName

Does anyone have any recommendations on how I could improve the performance of the query?

OwnerDisplayName: Ricardo Villamil


问:
How to load complete package with Jaxb
I am trying to load the package with Jaxrb.

```<code>JAXBContext jc = JAXBContext.newInstance("abc.acs");
Unmarshaller u = jc.createUnmarshaller();
</code>```

But during marshalling I am getting an exception

"abc.acs" doesn't contain ObjectFactory.class or jaxb.index .

How to fix?

答: Use JAXBContext.newInstance(ObjectFactory.class) for the respective ObjectFactory.

Title: How to load complete package with Jaxb

Body:
I am trying to load the package with Jaxrb.

JAXBContext jc = JAXBContext.newInstance("abc.acs");
Unmarshaller u = jc.createUnmarshaller();

But during marshalling I am getting an exception

"abc.acs" doesn't contain ObjectFactory.class or jaxb.index .

How to fix?


问:
Does the Log method cost a lot of execution time?
In my project, the Log function has been used in many places, and there isn't any "if statement" to control it.we use just like this:

```<code>...
String s = generateString();
Log.d(TAG, "result is : " + s);
...
</code>```

When I see the consumer of time by the android profiler, the Log function seems to cost a lot of time.

Does anyone know the actual time consume of Log function?Thank you very much!

答:
From the documentation:

The order in terms of verbosity, from least to most is ERROR, WARN,
  INFO, DEBUG, VERBOSE. Verbose should never be compiled into an
  application except during development. Debug logs are compiled in but
  stripped at runtime. Error, warning and info logs are always kept.

So, if you're looking to show logs while debugging only, you can rely on the DEBUG logs (Log.d), as they are removed for release builds (which may be bad if you rely on log dumbs from user feedback). Of course, if you're just using logs for debugging and plan to remove them once you're done, then it doesn't really matter.

As for how much time, I think that's the wrong question, as times will vary between devices. The question should be "Is there a significant cost?"

To answer this question - Yes, logs absolutely cause a heavy strain on performance and should be stripped from the code apart from the most important ones before releasing. Try to avoid printing logs on the main / render threads, as these will have a direct & substantial impact on your app's responsiveness.

Body:
In my project, the Log function has been used in many places, and there isn't any "if statement" to control it.we use just like this:

...
String s = generateString();
Log.d(TAG, "result is : " + s);
...

When I see the consumer of time by the android profiler, the Log function seems to cost a lot of time.

Does anyone know the actual time consume of Log function?Thank you very much!


问:
Layout for screen size 18.5x9
I want to create a layout.xml for Samsung galaxy S8. I tried to set it up with a Screen size of  18.5x9 .. but when I start the App it didn't fit.

I also tried to work with the resolution (2220x1080 / 2960x1080) but this didn't work too.

Any idea to set the screen size of one layout.xml to exactly the size of the phone (its also working for large/xlarge phones.. so why not for the s8)?

答:
Samsung galaxy s8 resolution is 1440 x 2560 pixels. So, if you want to create layout for this, you need to maintain your values and drawables folders for xxxhdpi. you can create your dimen file for xxxhdpi layouts.

For drawables :

```<code>drawable-ldpi        //240x320
drawable-mdpi        //320x480
drawable-hdpi        //480x800
drawable-xhdpi       //720x1280
drawable-xxhdpi      //1080X1920
drawable-xxxhdpi     //1440X2560
</code>```

For Values :

```<code>values-ldpi\dimens.xml
values-mdpi\dimens.xml
values-hdpi\dimens.xml
values-xhdpi\dimens.xml
values-xxhdpi\dimens.xml
values-xxxhdpi\dimens.xml
</code>```

Title: Layout for screen size 18.5x9

Body:
Samsung galaxy s8 resolution is 1440 x 2560 pixels. So, if you want to create layout for this, you need to maintain your values and drawables folders for xxxhdpi. you can create your dimen file for xxxhdpi layouts.

For drawables :

drawable-ldpi        //240x320
drawable-mdpi        //320x480
drawable-hdpi        //480x800
drawable-xhdpi       //720x1280
drawable-xxhdpi      //1080X1920
drawable-xxxhdpi     //1440X2560

For Values :

values-ldpi\dimens.xml
values-mdpi\dimens.xml
values-hdpi\dimens.xml
values-xhdpi\dimens.xml
values-xxhdpi\dimens.xml
values-xxxhdpi\dimens.xml


问:
Certain NotificationBuilder methods are deprecated in Xamarin.Android, which ones should I use?
I have been working with Notification.Builder class but some of the options are deprecated apparently, for example SetSound, SetDefaults, SetVibrate, SetPriority, etc.

What methods should I use to set these options now? The official Android documentation tells me to use enableSound or enableVibrate but these are not available in Xamarin.Android.

Does anyone have some advice?

Thanks!

答:
Yes, Notification builder methods have been deprecated but they have been deprecated on API level 26 OR Android Oreo(8.0) and using these methods below them should not be a problem, (FOR NOW!)
Other than that as per the Xamarin release notes the new methods will probably be available in the next release :

For more information please check here :
https://developer.xamarin.com/releases/android/xamarin.android_8/xamarin.android_8.0/


问:
<access sslFlags="SslRequireCert" /> using IIS Express -> HTTP Error 500.19
I'm trying to test client certificate authentication with IIS Express. Is it possible or do I need to use IIS?

I have modified my web.config like this:

```<code><configuration>
    <system.webServer>
        <security>
            <access sslFlags="SslRequireCert" />
        </security>
    </system.webServer>
</configuration>
</code>```

Guide that I use:

https://dotnetcodr.com/2016/01/11/using-client-certificates-in-net-part-1-introduction/

.vs\config\applicationhost.config looks like this, no deny or allowOverride set to false.:

```<code><security>
    <access sslFlags="None" />
    ...
</security>
</code>```

Error:

HTTP Error 500.19 - Internal Server Error The requested page cannot be
  accessed because the related configuration data for the page is
  invalid.

This configuration section cannot be used at this path. This happens
  when the section is locked at a parent level. Locking is either by
  default (overrideModeDefault="Deny"), or set explicitly by a location
  tag with overrideMode="Deny" or the legacy allowOverride="false".

答:
In .vs\config\applicationhost.config I found these lines:

```<code><configuration>
    <configSections>
        <sectionGroup name="system.webServer">
            <sectionGroup name="security">
                <section name="access" overrideModeDefault="Deny" />
            </sectionGroup>
        </sectionGroup>
    </configSections>
</configuration>
</code>```

Changed it to this and now it works.

```<code><section name="access" overrideModeDefault="Allow" />
</code>```

Body:
I'm trying to test client certificate authentication with IIS Express. Is it possible or do I need to use IIS?

I have modified my web.config like this:

<configuration>
    <system.webServer>
        <security>
            <access sslFlags="SslRequireCert" />
        </security>
    </system.webServer>
</configuration>

Guide that I use:

https://dotnetcodr.com/2016/01/11/using-client-certificates-in-net-part-1-introduction/

.vs\config\applicationhost.config looks like this, no deny or allowOverride set to false.:

<security>
    <access sslFlags="None" />
    ...
</security>

Error:

HTTP Error 500.19 - Internal Server Error The requested page cannot be
  accessed because the related configuration data for the page is
  invalid.

This configuration section cannot be used at this path. This happens
  when the section is locked at a parent level. Locking is either by
  default (overrideModeDefault="Deny"), or set explicitly by a location
  tag with overrideMode="Deny" or the legacy allowOverride="false".

Body:
In .vs\config\applicationhost.config I found these lines:

<configuration>
    <configSections>
        <sectionGroup name="system.webServer">
            <sectionGroup name="security">
                <section name="access" overrideModeDefault="Deny" />
            </sectionGroup>
        </sectionGroup>
    </configSections>
</configuration>

Changed it to this and now it works.

<section name="access" overrideModeDefault="Allow" />


问:
Rails Assets intermittent Timeout https://rails-assets.org
Intermittently getting error when doing bundle install for this and also on Continuous Integration server.</p>

```<code>Retrying dependency api due to error (4/4): Bundler::HTTPError Network error while fetching https://rails-assets.org/api/v1/dependencies?gems=rails-assets-angular%2Crails-assets-bootstrap-2.3.2%2Crails-assets-bootstrap-3%2Crails-assets-jasmine%2Crails-assets-jqueryjs%2Crails-assets-rainbow%2Crails-assets-typeahead.js (too many connection resets (due to Net::ReadTimeout - Net::ReadTimeout) after 0 requests on 70190348894440, last used 22.186127 seconds ago)
</code>```

答:
It's likely maintenance happens every once and awhile (especially this late) although they have definitely had downtime before (see https://github.com/tenex/rails-assets/issues/329).

Doing a simple curl you can see they simply aren't responding to any requests:

```<code>$ curl 'https://rails-assets.org/api/v1/dependencies?gems=rails-assets-angular%2Crails-assets-bootstrap-2.3.2%2Crails-assets-bootstrap-3%2Crails-assets-jasmine%2Crails-assets-jqueryjs%2Crails-assets-rainbow%2Crails-assets-typeahead.js' -D - --max-time 10
curl: (28) Operation timed out after 10004 milliseconds with 0 bytes received
</code>```

Body:
Intermittently getting error when doing bundle install for this and also on Continuous Integration server.

Retrying dependency api due to error (4/4): Bundler::HTTPError Network error while fetching https://rails-assets.org/api/v1/dependencies?gems=rails-assets-angular%2Crails-assets-bootstrap-2.3.2%2Crails-assets-bootstrap-3%2Crails-assets-jasmine%2Crails-assets-jqueryjs%2Crails-assets-rainbow%2Crails-assets-typeahead.js (too many connection resets (due to Net::ReadTimeout - Net::ReadTimeout) after 0 requests on 70190348894440, last used 22.186127 seconds ago)

Body:
It's likely maintenance happens every once and awhile (especially this late) although they have definitely had downtime before (see https://github.com/tenex/rails-assets/issues/329).

Doing a simple curl you can see they simply aren't responding to any requests:

$ curl 'https://rails-assets.org/api/v1/dependencies?gems=rails-assets-angular%2Crails-assets-bootstrap-2.3.2%2Crails-assets-bootstrap-3%2Crails-assets-jasmine%2Crails-assets-jqueryjs%2Crails-assets-rainbow%2Crails-assets-typeahead.js' -D - --max-time 10
curl: (28) Operation timed out after 10004 milliseconds with 0 bytes received


问:
linear-gradient IE11 white space issue
I'm trying to build a css framework for myself for some status boxes on my site.

I have put up an example here:

https://jsfiddle.net/ravcg28r/

```<code>    background: -moz-linear-gradient(    left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: -webkit-linear-gradient( left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: -o-linear-gradient(      left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: linear-gradient(     to right,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#aeaeae', endColorstr='#aeaeae',GradientType=1 );
</code>```

It works really well in chrome and ff, but in IE 11 my linear gradient doesn't quite fill my span and I get an annoying little white space appearing around the border, see image and note the white space in the green box above the icon.

Does anyone know how to prevent this?

linear gradient issue in IE11

答:
I unfortunately don't exactly know why but it happens on 135% zoom in IE 10 and it seems to be a problem with border, not in gradient bg itself.

I managed to fix it changing border of .sb-green to this:

```<code>.sb-green {
     border: 0.21em solid #75de75 !important;/*please mind the 0.21 */
}
</code>```

In pixels it failed to work at 4, 7.

I guess its some problem with IE rounding the border size when its calculated by fractions of sizes like 0.2em of 12px * 135% zooom etc. It wouldn't happen with pixel sizes I think... but I understand why you try to use relative ones ;-)

Title: linear-gradient IE11 white space issue

Body:
I'm trying to build a css framework for myself for some status boxes on my site.

I have put up an example here:

https://jsfiddle.net/ravcg28r/

    background: -moz-linear-gradient(    left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: -webkit-linear-gradient( left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: -o-linear-gradient(      left,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    background: linear-gradient(     to right,  #aeaeae, #aeaeae 2em, transparent 2em, transparent 100% );
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#aeaeae', endColorstr='#aeaeae',GradientType=1 );

It works really well in chrome and ff, but in IE 11 my linear gradient doesn't quite fill my span and I get an annoying little white space appearing around the border, see image and note the white space in the green box above the icon.

Does anyone know how to prevent this?

linear gradient issue in IE11

Body:
I unfortunately don't exactly know why but it happens on 135% zoom in IE 10 and it seems to be a problem with border, not in gradient bg itself.

I managed to fix it changing border of .sb-green to this:

.sb-green {
     border: 0.21em solid #75de75 !important;/*please mind the 0.21 */
}

In pixels it failed to work at 4, 7.

I guess its some problem with IE rounding the border size when its calculated by fractions of sizes like 0.2em of 12px * 135% zooom etc. It wouldn't happen with pixel sizes I think... but I understand why you try to use relative ones ;-)


问:
Meizu notification badge issue
I'm trying to set a Push Notification badge on the app icon.

I have an issue with Meizu phone, It doesn't display the badges.
Does anyone has a solution for it?

I searched the stuck, but didn't find a solution for it.

I tried @Tadas Valaitis solotion from here:
https://stackoverflow.com/a/25849212/5223744

I also tried using ShortcutBadger library, but no luck.

答:
For your kind information, it is facility provided by manufacturer,

Please read article provided by WhatsApp

Title: Meizu notification badge issue


问:
MongoDB Robo 3T add array (list) to index
I'm new to MongoDB and I would like to know how to add an index to a collection which is a version list with sub-indexes using Robo 3T?

I'll elaborate on my current collection index structure:

```<code>{
    "_id" : 1,
    "Name" : "My name"
    "VersionList": 1
}
</code>```

The required collection index structure should become as follows:

```<code>{
    "_id" : 1,
    "Name" : "My name"
    "VersionList":
    [
        0:
        {
            "Frequency" : 0,
            "Information" : "Revision information",
            "Trigger" : {},
            "D" :
            {
                "DataType": "Actual value",
                "Unit": 1
            }
        }
    ]
}
</code>```

I used tool Robo 3T to add the indexes. My problem is that I don't know how to add the sub-indexes of VersionList with Robo 3T and could not find clear examples how to do this. Could someone please show me how to do this?

Thanx in advance,

Bokki

答:
Dissapointing to not get any answers from the "mongo guru's", so I found out myself how to fix this by trying things out...

For other MongoDB newbies struggling with this issue:
It's as easy as: just insert documents to collection.

Steps in Robo 3T to add "sub-indexes" with arrays and so on:

RightClick on server connection -> Create Database

RightClick on Collections -> Create Collection...

RightClick on Indexes -> Add Indexes...

RightClick on your collection -> Insert Document...

In "Insert Document" window, add any valid JSON structure (this can be tested with the "Validate" button) and then press "Save".

Hope this helps someone!

Body:
I'm new to MongoDB and I would like to know how to add an index to a collection which is a version list with sub-indexes using Robo 3T?

I'll elaborate on my current collection index structure:

{
    "_id" : 1,
    "Name" : "My name"
    "VersionList": 1
}

The required collection index structure should become as follows:

{
    "_id" : 1,
    "Name" : "My name"
    "VersionList":
    [
        0:
        {
            "Frequency" : 0,
            "Information" : "Revision information",
            "Trigger" : {},
            "D" :
            {
                "DataType": "Actual value",
                "Unit": 1
            }
        }
    ]
}

I used tool Robo 3T to add the indexes. My problem is that I don't know how to add the sub-indexes of VersionList with Robo 3T and could not find clear examples how to do this. Could someone please show me how to do this?

Thanx in advance,

Bokki


问:
how to stop/close an audio file(mp3/.wav) using python script
I wrote code to play an audio file using python, like below.

```<code>def playSound(self):
    os.system('start C:\\Users\\unavaras\\Music\\223.wav')
    time.sleep(10)
</code>```

It's playing the audio file recursively and it's not being closed untill i manually close it.

Tried below code as well to stop audio, but didn't work

```<code>def playSound(self):
    p1 = Popen('start C:\\Users\\unavaras\\Music\\223.wav', shell=True)
    time.sleep(5)
    p1.kill()
</code>```

In both cases audio is being played recursively.

Can some help me how I can stop the audio after some time or once it finishes playing.

答:
I am using linux but you can try this

```<code>def playSound(self):
     os.system('timeout 10 start C:\\Users\\unavaras\\Music\\223.wav')
</code>```

For finding the time duration of audio this link
Get .wav file length or duration

Body:
I wrote code to play an audio file using python, like below.

def playSound(self):
    os.system('start C:\\Users\\unavaras\\Music\\223.wav')
    time.sleep(10)

It's playing the audio file recursively and it's not being closed untill i manually close it.

Tried below code as well to stop audio, but didn't work

def playSound(self):
    p1 = Popen('start C:\\Users\\unavaras\\Music\\223.wav', shell=True)
    time.sleep(5)
    p1.kill()

In both cases audio is being played recursively.

Can some help me how I can stop the audio after some time or once it finishes playing.

Body:
I am using linux but you can try this

def playSound(self):
     os.system('timeout 10 start C:\\Users\\unavaras\\Music\\223.wav')

For finding the time duration of audio this link
Get .wav file length or duration


问:
Validation Summary For Ajax Call
What is the best way to send back Validation Summaries back to the client when making an ajax call using jquery?</p>

答:
An easy way to achieve this is to have a div inside your page containing a partial with the validation summary. When you invoke the controller action using AJAX it would return this partial and you will be able to update the summary. Example:

```<code>$('#validationSummary').load('/home/someaction');
</code>```

where the action would return a view:

```<code>public ActionResult SomeAction()
{
    return View();
}
</code>```

and the corresponding view:

```<code><%= Html.ValidationSummary() %>
</code>```

This way the controller action directly sends the partial HTML that needs to be updated/substituted inside your page. If your controller action returns JSON you will need to accommodate in your existing JSON structure an additional parameter containing the list of error messages so that in the AJAX success callback you could update the corresponding DOM sections. A bit more work here but with things like jQuery Templates this might even be fun :-)

Title: Validation Summary For Ajax Call

Body:
An easy way to achieve this is to have a div inside your page containing a partial with the validation summary. When you invoke the controller action using AJAX it would return this partial and you will be able to update the summary. Example:

$('#validationSummary').load('/home/someaction');

where the action would return a view:

public ActionResult SomeAction()
{
    return View();
}

and the corresponding view:

<%= Html.ValidationSummary() %>

This way the controller action directly sends the partial HTML that needs to be updated/substituted inside your page. If your controller action returns JSON you will need to accommodate in your existing JSON structure an additional parameter containing the list of error messages so that in the AJAX success callback you could update the corresponding DOM sections. A bit more work here but with things like jQuery Templates this might even be fun :-)


问:
Replace anchor tag value with anchor title if href value is empty by regex
I am trying to replace the anchor tag value with anchor's title value if any anchor tag's href attribute is blank.

Like

```<code><a xlink:href="">Lorem Ipsum</a>  is simply dummy text of the printing and typesetting industry<a xlink:href ="http://google.com">Google</a>.
</code>```

if I try with below regex:

```<code><a [^>]+>(.*?)<\/a>
</code>```

DEMO http://regexr.com/3h6on

then output I am getting below

```<code>Lorem Ipsum is simply dummy text of the printing and typesetting industry Google.
</code>```

it replaced both anchor tag with Anchor Text value, and I need to replace those anchor tag where the href attribute value is empty.

I need an output like below

```<code>Lorem Ipsum is simply dummy text of the printing and typesetting industry<a xlink:href ="http://google.com">Google</a>
</code>```

答:
My approach looks rather messy but for the test link you provided it seems to work just like you want it to:

```<code><a [^>]+?(?=href=(?:"|')(?:"|'))[^>]*?>(.*?)<\/a>
</code>```

Try it with this link.

What I've added to the regex is the following part

```<code>[^>]+?(?=href=(?:"|')(?:"|'))[^>]*?
</code>```

The . wildcards at the beginning and end of the part I've added are just there to match with any additional attributes or whitespaces between the < >.

The regex inside the parenthesis is called a positive lookahead. This means that it will match whatever is inside the parenthesis but will not include it into the results.

The positive lookahead matches an href followed by an empty string.

Note that my regex still matches if the quotation marks after the href= expression do not match

I hope this answered your question.

Body:
I am trying to replace the anchor tag value with anchor's title value if any anchor tag's href attribute is blank.

Like

Lorem Ipsum  is simply dummy text of the printing and typesetting industryGoogle.

if I try with below regex:

]+>(.*?)<\/a>

DEMO http://regexr.com/3h6on

then output I am getting below

Lorem Ipsum is simply dummy text of the printing and typesetting industry Google.

it replaced both anchor tag with Anchor Text value, and I need to replace those anchor tag where the href attribute value is empty.

I need an output like below

Lorem Ipsum is simply dummy text of the printing and typesetting industryGoogle

Body:
My approach looks rather messy but for the test link you provided it seems to work just like you want it to:

<a [^>]+?(?=href=(?:"|')(?:"|'))[^>]*?>(.*?)<\/a>

Try it with this link.

What I've added to the regex is the following part

[^>]+?(?=href=(?:"|')(?:"|'))[^>]*?

The . wildcards at the beginning and end of the part I've added are just there to match with any additional attributes or whitespaces between the < >.

The regex inside the parenthesis is called a positive lookahead. This means that it will match whatever is inside the parenthesis but will not include it into the results.

The positive lookahead matches an href followed by an empty string.

Note that my regex still matches if the quotation marks after the href= expression do not match

I hope this answered your question.


问:
Notify UITable from an other Thread
I've got a simple UITable implementation and an array which is called fruits. Taken out of this example. The only difference is that I am using a UIViewController for the UITable insted of a UITableViewController, but this should be irrelevant for now.

```<code>class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var fruits : [String] = Array()
    let thread : GetDataForFruitsArrayThread

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

        cell.textLabel?.text = fruits[indexPath.row]

        return cell
    }

    }
</code>```

Now I have got a viewDidLoad function in this class also. In the function I am calling a thread which is getting the array as a parameter. The thread is filling up the array with new values asynchronously. Means I don't know if there will be any values or when do the value appear and are set into the array. So you can imagine what I want to ask on this point: How do I signal the UITableView that I have changed the content of the array once the view has loaded the array into the UITable. In c# there is the NotifyAll() function which notfies all the Listener to an attribute. Is there an easy and performant way to do this in swift, optionally without importing any non-included libraries?

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.thread = GetDataForFruitsArrayThread(array: &fruits)
    self.thread.StartAsynchronously()

}
</code>```

EDIT - adding GetDataForFruitsArrayThread

```<code> class GetDataForFruitsArrayThread : MyThread {

 var array : [String]

 init(array: inout [String] ) {
   self.array = array
 }

 override func main() {

      // init socket

 while(true){

      _ = withUnsafeMutablePointer(to: &rcvaddr){
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1){
      recvfrom(m_socket, &pData, bufferlength, 0, UnsafeMutablePointer($0),
               &socketAddressLength)
            }
        }

        var fruit = String(cString:inet_ntoa(rcvaddr.sin_addr), encoding: .ascii)
        self.array.append(fruit)

   }
 }
}
</code>```

EDIT - 21.11.2017:

Following Sandeep Bhandari's answer I changed the following code in the ViewController:

```<code>@IBOutlet weak var tableView1: UITableView!

var fruits : [String] = Array() {
        didSet {
            self.tableView1.reloadData()
        }
    }
</code>```

PROBLEM: I am setting a breakpoint at array.append(fruit) in the GetDataForFruitsArrayThread-class. After that there is a breakpoint in the didSet method. But this breakpoint does not get called after the append()-call! NOTE: The parameter on the init function of the GetDataForFruitsArrayThread-class is an in-out parameter!

UPDATE: I found out that if I do the array.append(fruit)-call on the GetDataForFruitsArrayThread.array in the GetDataForFruitsArrayThread-thread, the Fruits-array in ViewController-class does not get changed, therefore didSet did not get called. How can I change this behaviour?

答:
Because you said you are running a endless process to keep updating your array and you want the UI update once the array changes you can use the below solution.

```<code>var fruits : [String] = Array() {
        didSet {
            self.tableView.reloadData()
        }
    }
</code>```

What am I doing ? Simple added a setter to array and whenever value changes I reload the tableView.

EDIT:

The above solution will work only if you modify the inout fruits array you pass to GetDataForFruitsArrayThread

```<code>self.thread = GetDataForFruitsArrayThread(array: &fruits)
</code>```

So don't create  one more array property in GetDataForFruitsArrayThread rather directly modify the array passed to GetDataForFruitsArrayThread.

Title: Notify UITable from an other Thread

Body:
I've got a simple UITable implementation and an array which is called fruits. Taken out of this example. The only difference is that I am using a UIViewController for the UITable insted of a UITableViewController, but this should be irrelevant for now.

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var fruits : [String] = Array()
    let thread : GetDataForFruitsArrayThread

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

        cell.textLabel?.text = fruits[indexPath.row]

        return cell
    }

    }

Now I have got a viewDidLoad function in this class also. In the function I am calling a thread which is getting the array as a parameter. The thread is filling up the array with new values asynchronously. Means I don't know if there will be any values or when do the value appear and are set into the array. So you can imagine what I want to ask on this point: How do I signal the UITableView that I have changed the content of the array once the view has loaded the array into the UITable. In c# there is the NotifyAll() function which notfies all the Listener to an attribute. Is there an easy and performant way to do this in swift, optionally without importing any non-included libraries?

override func viewDidLoad() {
    super.viewDidLoad()
    self.thread = GetDataForFruitsArrayThread(array: &fruits)
    self.thread.StartAsynchronously()

}

EDIT - adding GetDataForFruitsArrayThread

 class GetDataForFruitsArrayThread : MyThread {

 var array : [String]

 init(array: inout [String] ) {
   self.array = array
 }

 override func main() {

      // init socket

 while(true){

      _ = withUnsafeMutablePointer(to: &rcvaddr){
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1){
      recvfrom(m_socket, &pData, bufferlength, 0, UnsafeMutablePointer($0),
               &socketAddressLength)
            }
        }

        var fruit = String(cString:inet_ntoa(rcvaddr.sin_addr), encoding: .ascii)
        self.array.append(fruit)

   }
 }
}

EDIT - 21.11.2017:

Following Sandeep Bhandari's answer I changed the following code in the ViewController:

@IBOutlet weak var tableView1: UITableView!

var fruits : [String] = Array() {
        didSet {
            self.tableView1.reloadData()
        }
    }

PROBLEM: I am setting a breakpoint at array.append(fruit) in the GetDataForFruitsArrayThread-class. After that there is a breakpoint in the didSet method. But this breakpoint does not get called after the append()-call! NOTE: The parameter on the init function of the GetDataForFruitsArrayThread-class is an in-out parameter!

UPDATE: I found out that if I do the array.append(fruit)-call on the GetDataForFruitsArrayThread.array in the GetDataForFruitsArrayThread-thread, the Fruits-array in ViewController-class does not get changed, therefore didSet did not get called. How can I change this behaviour?

Body:
Because you said you are running a endless process to keep updating your array and you want the UI update once the array changes you can use the below solution.

var fruits : [String] = Array() {
        didSet {
            self.tableView.reloadData()
        }
    }

What am I doing ? Simple added a setter to array and whenever value changes I reload the tableView.

EDIT:

The above solution will work only if you modify the inout fruits array you pass to GetDataForFruitsArrayThread

self.thread = GetDataForFruitsArrayThread(array: &fruits)

So don't create  one more array property in GetDataForFruitsArrayThread rather directly modify the array passed to GetDataForFruitsArrayThread.


问:
How can we disable the datatable export buttons(Or prevent click event) when datatable is empty?
I'm using  datatable , I need to disable the export buttons(Excel, PDF) when the grid having the empty rows.
How can we handle the datatable export buttons click actions?

I have done the grid initialization as below.
I don't know how to handle the datatable export buttons(PDF, Excel).
Can you please help me how to fix this.

Update:

And I have one more issue that when user click on the Excel or PDF button then the grid columns width is collapsing.

I need even user click on the Excel or PDF buttons the grid column width should not change. How can we achieve this?

After exporting the data in to excel, columns are not auto adjusted in the excel.

How can we make the columns(After export datatable data into excel) auto adjusted?

```<code> var buttonCommon = {
    exportOptions: {
      format: {
        body: function(data, column, row, node) {
          return data;
        }
      }
    }
  };

     var dataTableObj = {
      "processing": true,
      "destroy": true,
      "scrollX": true,
      "columns": [{
        "data": "CollegeName",
        "width":"30%"

      }, {
        "data": "AffiliatedTo",
         "width":"15%"

      }, {
        "data": "TPOName",
        "width":"20%"

      }, {
        "data": "Phone",

      }, {
        "data": "Website",

        "bSortable": false
      }],
      dom: 'lBfrtip',
      buttons: [
      $.extend( true, {}, buttonCommon, {
                extend: 'excelHtml5',
                  title: 'Colleges',

            } ),

        {
          extend: 'pdf',
          title: 'Colleges'
        }

      ],

      fnRowCallback: function(nRow, aData, iDisplayIndex) {
         //Some code
        return nRow;
      }

    };

      var dataTbl = $('#tblColleges').DataTable(dataTableObj);
</code>```

答:
This solution has worked for me put it in fnDrawCallback function</p>

```<code>$(tableName).dataTable({

 "fnDrawCallback":function () {
                   var table = $(tableName).DataTable();
                    if (table.data().length === 0)
            table.buttons('.buttons-html5').disable();
                 else
            table.buttons('.buttons-html5').enable();

            }
});
</code>```

Body:
I'm using  datatable , I need to disable the export buttons(Excel, PDF) when the grid having the empty rows.
How can we handle the datatable export buttons click actions?

I have done the grid initialization as below.
I don't know how to handle the datatable export buttons(PDF, Excel).
Can you please help me how to fix this.

Update:

And I have one more issue that when user click on the Excel or PDF button then the grid columns width is collapsing.

I need even user click on the Excel or PDF buttons the grid column width should not change. How can we achieve this?

After exporting the data in to excel, columns are not auto adjusted in the excel.

How can we make the columns(After export datatable data into excel) auto adjusted?

 var buttonCommon = {
    exportOptions: {
      format: {
        body: function(data, column, row, node) {
          return data;
        }
      }
    }
  };

     var dataTableObj = {
      "processing": true,
      "destroy": true,
      "scrollX": true,
      "columns": [{
        "data": "CollegeName",
        "width":"30%"

      }, {
        "data": "AffiliatedTo",
         "width":"15%"

      }, {
        "data": "TPOName",
        "width":"20%"

      }, {
        "data": "Phone",

      }, {
        "data": "Website",

        "bSortable": false
      }],
      dom: 'lBfrtip',
      buttons: [
      $.extend( true, {}, buttonCommon, {
                extend: 'excelHtml5',
                  title: 'Colleges',

            } ),

        {
          extend: 'pdf',
          title: 'Colleges'
        }

      ],

      fnRowCallback: function(nRow, aData, iDisplayIndex) {
         //Some code
        return nRow;
      }

    };

      var dataTbl = $('#tblColleges').DataTable(dataTableObj);

Body:
This solution has worked for me put it in fnDrawCallback function

$(tableName).dataTable({

 "fnDrawCallback":function () {
                   var table = $(tableName).DataTable();
                    if (table.data().length === 0)
            table.buttons('.buttons-html5').disable();
                 else
            table.buttons('.buttons-html5').enable();

            }
});


问:
Functors () overloading for classes
I do not think this is possible and curious if it is or why it is not:

```<code>class A
{

}
</code>```

I would like to treat instances of A as functions such as

```<code>A a = new A();

a();
or
a(3);
etc...
</code>```

This is to treat classes as functions for special cases when it is useful to do so. For example, I'm essentially wrapping a Func object but would love to treat an instance of such a class to act as the Func object itself. This way I don't have to have a "dummy" function to call in the class.

```<code>    public class Condition
    {
        protected Func<bool> Eval { get; set; }
        protected bool Or = false;

        protected Condition() { }
        public Condition(Func<bool> f, bool Or = false) { Eval = f; this.Or = Or; }
        protected Func<bool> GetEval(Condition c) { return c.Eval; }
        protected bool GetOr(Condition c) { return c.Or; }

    }

    public class ConditionBlock : Condition
    {
        List<Condition> Conditions;

        public ConditionBlock() { Eval = _Eval; }

        public ConditionBlock(List<Condition> Conditions) : this() { this.Conditions = Conditions; }
        public ConditionBlock(Condition[] Conditions) : this() { this.Conditions = new List<Condition>(Conditions); }
        public void Add(Condition c) { if (Conditions == null) Conditions = new List<Condition>(); Conditions.Add(c); }

        private bool _Eval()
        {
            if (Conditions == null || Conditions.Count == 0) return true;

            bool ans = !GetOr(Conditions[0]);
            for (int i = 0; i < Conditions.Count; i++)
                ans = GetOr(Conditions[i]) ? ans | GetEval(Conditions[i])() : ans & GetEval(Conditions[i])();

            return ans;
        }

        public bool _()
        {
            return Eval();
        }
    }
</code>```

To initiate the Computation I call the member (), e.g., cblock.(). It would look much nicer if I could call it as cblock(). Effectively a ConditionBlock is a compound function. Would be nice to be able to treat it as such. Using _() is quite ugly as is renaming it to anything else such as cblock.fire(), cblock.eval(), etc...

答:
You could always just provide an indexer (or overloaded indexers).

The only difference would be square brackets.

Title: Functors () overloading for classes

Body:
I do not think this is possible and curious if it is or why it is not:

class A
{

}

I would like to treat instances of A as functions such as

A a = new A();

a();
or
a(3);
etc...

This is to treat classes as functions for special cases when it is useful to do so. For example, I'm essentially wrapping a Func object but would love to treat an instance of such a class to act as the Func object itself. This way I don't have to have a "dummy" function to call in the class.

    public class Condition
    {
        protected Func<bool> Eval { get; set; }
        protected bool Or = false;

        protected Condition() { }
        public Condition(Func<bool> f, bool Or = false) { Eval = f; this.Or = Or; }
        protected Func<bool> GetEval(Condition c) { return c.Eval; }
        protected bool GetOr(Condition c) { return c.Or; }

    }

    public class ConditionBlock : Condition
    {
        List<Condition> Conditions;

        public ConditionBlock() { Eval = _Eval; }

        public ConditionBlock(List<Condition> Conditions) : this() { this.Conditions = Conditions; }
        public ConditionBlock(Condition[] Conditions) : this() { this.Conditions = new List<Condition>(Conditions); }
        public void Add(Condition c) { if (Conditions == null) Conditions = new List<Condition>(); Conditions.Add(c); }

        private bool _Eval()
        {
            if (Conditions == null || Conditions.Count == 0) return true;

            bool ans = !GetOr(Conditions[0]);
            for (int i = 0; i < Conditions.Count; i++)
                ans = GetOr(Conditions[i]) ? ans | GetEval(Conditions[i])() : ans & GetEval(Conditions[i])();

            return ans;
        }

        public bool _()
        {
            return Eval();
        }
    }

To initiate the Computation I call the member (), e.g., cblock.(). It would look much nicer if I could call it as cblock(). Effectively a ConditionBlock is a compound function. Would be nice to be able to treat it as such. Using _() is quite ugly as is renaming it to anything else such as cblock.fire(), cblock.eval(), etc...


问:
Can i use product flavor to make diffrent apps for single feature from one multi feature app?
Currently, I have an app that contains three features, which is published on the store.

I would like to create a separate app for each feature, but I don't want to copy and paste, since I will then have to maintain multiple codebases.

I have read about Product Flavors, which can be used to create different applications from the same codebase. How do I go about creating four separate apps, while maintaining only one codebase?

Specifically: where do I place the source of the main app that contains all the features?

Can anyone suggest how I can organise my code?

答:
You can create product flavours in gradle file as mentioned in above link you shared moreover you need to create different package name while creating those flavours e.g.

In gradle

```<code>    productFlavors {

            demo{
                applicationId "com.mycompany.myproject.demo"
                versionCode getCustomBuildVersion()
                versionName VERSION_NAME
            }
            full{
                applicationId "com.mycompany.myproject.full"
                versionCode getCustomBuildVersion()
                versionName VERSION_NAME
            }
}
</code>```

In this way you can generate different apps from same code base. You can use and set flags for enabling or disabling certain features. check out this link for further help: Android using Gradle Build flavors in the code like an if case

In activities you want to change do something like this in onCreate():

```<code>if (BuildConfig.FLAVOR.equals("demo")){
switchToDemoHomePage()
}
else if(BuildConfig.FLAVOR.equals("full")){
switchToFullHomePage()
}
</code>```

In this way you can show/hide/change any feature/options/flows based on flavour of the app

Body:
You can create product flavours in gradle file as mentioned in above link you shared moreover you need to create different package name while creating those flavours e.g.

In gradle

    productFlavors {

            demo{
                applicationId "com.mycompany.myproject.demo"
                versionCode getCustomBuildVersion()
                versionName VERSION_NAME
            }
            full{
                applicationId "com.mycompany.myproject.full"
                versionCode getCustomBuildVersion()
                versionName VERSION_NAME
            }
}

In this way you can generate different apps from same code base. You can use and set flags for enabling or disabling certain features. check out this link for further help: Android using Gradle Build flavors in the code like an if case

In activities you want to change do something like this in onCreate():

if (BuildConfig.FLAVOR.equals("demo")){
switchToDemoHomePage()
}
else if(BuildConfig.FLAVOR.equals("full")){
switchToFullHomePage()
}

In this way you can show/hide/change any feature/options/flows based on flavour of the app


问:
Handling None when adding numbers
I would like to perform addition of 2 integers, which can also be None, with the following results:

```<code>add(None, None) = None
add(None, b) = b
add(a, None) = a
add(a, b) = a + b
</code>```

What is the most pythonic, concise expression for this?
So far I have:

```<code>def add1(a, b):
    if a is None:
        return b
    elif b is None:
        return a
    else:
        return a + b
</code>```

or

```<code>def add2(a, b):
    try:
        return a + b
    except TypeError:
        return a if a is not None else b
</code>```

Is there any shorter way to achieve it?

答:
This is reasonably compact and can handle different numbers of terms:</p>

```<code>def None_sum(*args):
    args = [a for a in args if not a is None]
    return sum(args) if args else None
</code>```

Title: Handling None when adding numbers

Body:
I would like to perform addition of 2 integers, which can also be None, with the following results:

add(None, None) = None
add(None, b) = b
add(a, None) = a
add(a, b) = a + b

What is the most pythonic, concise expression for this?
So far I have:

def add1(a, b):
    if a is None:
        return b
    elif b is None:
        return a
    else:
        return a + b

or

def add2(a, b):
    try:
        return a + b
    except TypeError:
        return a if a is not None else b

Is there any shorter way to achieve it?

Body:
This is reasonably compact and can handle different numbers of terms:

def None_sum(*args):
    args = [a for a in args if not a is None]
    return sum(args) if args else None


问:
Rails Event EventType model association - undefined method `title' for nil:NilClass
I have a problem with listing EventType title from Event-EventType model association.

In this case, I have a simple Event model and EventType model.
Event model has field eventtype_id.

Now when I want to show EventType Title I am getting error 'undefined methodtitle' for nil:NilClass'`

I tried with belongs_to and has_many associations but not work. Probably I am doing something wrong.

答:
If your model is EventType, then your foreign key should be event_type_id

To go on with your structure you can try to customize belongs_to with parameter foreign_key: :eventtype_id, but it's a hack.

On the other hand you should get errors about your associations and it's not clear for me why don't you have it.

If that's not working for you, then provide call please your target object in rails c (rails console), show it's attributes and double check that you really have EventType with id from Event calling EventType.find([yout_event_id])


问:
How to stop BackgroundWorker correctly
I have a form with 2 comboboxes on it. And I want to fill combobox2.DataSource based on combobox1.Text and combobox2.Text (I assume that the user has completed input in combobox1 and is in the middle of inputting in combobox2). So I have an event handler for combobox2 like this:

```<code>private void combobox2_TextChanged(object sender, EventArgs e)
{
    if (cmbDataSourceExtractor.IsBusy)
       cmbDataSourceExtractor.CancelAsync();

    var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
       V2 = combobox2.Text};
    cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
}
</code>```

As far as building DataSource is time-consuming process (it creates a request to database and executes it) I decided that it's better to perform it in another process using BackgroundWorker. So there's a scenario when cmbDataSourceExtractor hasn't completed its work and the user types one more symbol. In this case I get an exception on this line

cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues ); about that BackgroundWorker is busy and cannot perform several actions in the same time.

How to get rid of this exception?

答:
You will have to use a flag shared between the main thread and the BackgroundWorker, such as BackgroundWorker.CancellationPending. When you want the BackgroundWorker to exit, just set the flag using BackgroundWorker.CancelAsync().

MSDN has a sample: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancellationpending.aspx

ContentLicense: CC BY-SA 4.0

Title: How to stop BackgroundWorker correctly

Body:
I have a form with 2 comboboxes on it. And I want to fill combobox2.DataSource based on combobox1.Text and combobox2.Text (I assume that the user has completed input in combobox1 and is in the middle of inputting in combobox2). So I have an event handler for combobox2 like this:

private void combobox2_TextChanged(object sender, EventArgs e)
{
    if (cmbDataSourceExtractor.IsBusy)
       cmbDataSourceExtractor.CancelAsync();

    var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
       V2 = combobox2.Text};
    cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
}

As far as building DataSource is time-consuming process (it creates a request to database and executes it) I decided that it's better to perform it in another process using BackgroundWorker. So there's a scenario when cmbDataSourceExtractor hasn't completed its work and the user types one more symbol. In this case I get an exception on this line

cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues ); about that BackgroundWorker is busy and cannot perform several actions in the same time.

How to get rid of this exception?


问:
CSS bootstrap alignment
I'm making a webpage but it seems I have an alignment issue.
The lower row is further indented than the top row.
Is there any simple way I can fix this without redoing my whole code?
I have a feeling it is just some padding I've missed, but I can't find it out.

Any help would be greatly appreciated.

Just started learning CSS yesterday.

Code:

```<code><div class="container">
    <div class="row" style="height: 395px">
        <div class="col-sm8" style="background-color: lightgrey">
            <iframe src="https://api.kaltura.nordu.net/p/261/sp/26100/embedIframeJs/uiconf_id/14973541/partner_id/261?iframeembed=true&playerId=kaltura_player&entry_id=0_jv96e7co&flashvars[streamerType]=auto" width="662+padding" height="395+padding" allowfullscreen webkitallowfullscreen mozAllowFullScreen frameborder="0" style="padding-left:25px;"></iframe>

        </div>

        <div class="col-sm4" style="background-color: lightgrey; ">
            <div class="imageContainer" style="padding-left: 30px">
                <img src="Fronter_Canvas.png" style="height: 395px; align-content: center; padding-left: 20px; padding: 10px;">
                <div class="dato">1.Juni.2018</div>
            </div>
        </div>
    </div>

<div class="container-fluid"  style="padding-top: 10px; height:380px">
    <div class="row" style="background-color: lightgrey; height: inherit; width: 960px">
        <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px;">
                <div class="container">
                <h4><b>Topp 5 Spørsmål.</b></h4>
                <p>For deg som er ny til Canvas.</p>
            </div>
            </div>
        </div>

    <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px; ali">
                <div class="container">
                    <h4><b>Fakultetskontakt</b></h4>
                    <p>Finn din Canvas kontakt på ditt institutt.</p>
                </div>
            </div>
       </div>

    <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px;">
                <div class="container">
                    <h4><b>Kurskontakt</b></h4>
                    <p>Få en oversikt over kursene.</p>
                </div>
            </div>
        </div>

    <div class="col-3">
                <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px;">
                <div class="container">
                    <h4><b>Innføringsplan av Canvas</b></h4>
                    <p>Hvordan canvas skal rulles ut.</p>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

```<code>.containter{
    padding: 2px 16px;
}

.imageContainer{
    position: relative;
    text-align: center;
}

.dato{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 40px;
    color: white;
    padding-top: 250px;
    font-family: sans-serif;
    font-style: normal;
    padding-left: 30px
}

.card{
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transition: 0.3s;
    height: 350px;
    float: left;
    padding: inherit;
    margin: inherit;
    padding: 10px;
    display: inline-block;
}

.col-3{
    height: 250px;
    padding: 10px;
}

.row{
    height: 250px
}
</code>```

My result.

答:
Div not close first container also class Name is wrong col-sm8 col-sm-8 col-sm-4 or col-3 to col-md,lg,sm,xs,-3

```<code><div class="container">
    <div class="row" style="height: 395px">
        <div class="col-sm8" style="background-color: lightgrey">
            <iframe src="https://api.kaltura.nordu.net/p/261/sp/26100/embedIframeJs/uiconf_id/14973541/partner_id/261?iframeembed=true&playerId=kaltura_player&entry_id=0_jv96e7co&flashvars[streamerType]=auto" width="662+padding" height="395+padding" allowfullscreen webkitallowfullscreen mozAllowFullScreen frameborder="0" style="padding-left:25px;"></iframe>

        </div>

        <div class="col-sm4" style="background-color: lightgrey; ">
            <div class="imageContainer" style="padding-left: 30px">
                <img src="Fronter_Canvas.png" style="height: 395px; align-content: center; padding-left: 20px; padding: 10px;">
                <div class="dato">1.Juni.2018</div>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid" style="padding-top: 10px; height:380px">
    <div class="row" style="background-color: lightgrey; height: inherit; width: 960px">
        <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px;">
                <div class="container">
                    <h4><b>Topp 5 Spørsmål.</b></h4>
                    <p>For deg som er ny til Canvas.</p>
                </div>
            </div>
        </div>

        <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px; ali">
                <div class="container">
                    <h4><b>Fakultetskontakt</b></h4>
                    <p>Finn din Canvas kontakt på ditt institutt.</p>
                </div>
            </div>
        </div>

        <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px;">
                <div class="container">
                    <h4><b>Kurskontakt</b></h4>
                    <p>Få en oversikt over kursene.</p>
                </div>
            </div>
        </div>

        <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px;">
                <div class="container">
                    <h4><b>Innføringsplan av Canvas</b></h4>
                    <p>Hvordan canvas skal rulles ut.</p>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Title: CSS bootstrap alignment

Body:
I'm making a webpage but it seems I have an alignment issue.
The lower row is further indented than the top row.
Is there any simple way I can fix this without redoing my whole code?
I have a feeling it is just some padding I've missed, but I can't find it out.

Any help would be greatly appreciated.

Just started learning CSS yesterday.

Code:

1.Juni.2018

Topp 5 Spørsmål.

For deg som er ny til Canvas.

Fakultetskontakt

Finn din Canvas kontakt på ditt institutt.

Kurskontakt

Få en oversikt over kursene.

Innføringsplan av Canvas

Hvordan canvas skal rulles ut.

.containter{
    padding: 2px 16px;
}

.imageContainer{
    position: relative;
    text-align: center;
}

.dato{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 40px;
    color: white;
    padding-top: 250px;
    font-family: sans-serif;
    font-style: normal;
    padding-left: 30px
}

.card{
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transition: 0.3s;
    height: 350px;
    float: left;
    padding: inherit;
    margin: inherit;
    padding: 10px;
    display: inline-block;
}

.col-3{
    height: 250px;
    padding: 10px;
}

.row{
    height: 250px
}

My result.

Body:
Div not close first container also class Name is wrong col-sm8 col-sm-8 col-sm-4 or col-3 to col-md,lg,sm,xs,-3

<div class="container">
    <div class="row" style="height: 395px">
        <div class="col-sm8" style="background-color: lightgrey">
            <iframe src="https://api.kaltura.nordu.net/p/261/sp/26100/embedIframeJs/uiconf_id/14973541/partner_id/261?iframeembed=true&playerId=kaltura_player&entry_id=0_jv96e7co&flashvars[streamerType]=auto" width="662+padding" height="395+padding" allowfullscreen webkitallowfullscreen mozAllowFullScreen frameborder="0" style="padding-left:25px;"></iframe>

        </div>

        <div class="col-sm4" style="background-color: lightgrey; ">
            <div class="imageContainer" style="padding-left: 30px">
                <img src="Fronter_Canvas.png" style="height: 395px; align-content: center; padding-left: 20px; padding: 10px;">
                <div class="dato">1.Juni.2018</div>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid" style="padding-top: 10px; height:380px">
    <div class="row" style="background-color: lightgrey; height: inherit; width: 960px">
        <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px;">
                <div class="container">
                    <h4><b>Topp 5 Spørsmål.</b></h4>
                    <p>For deg som er ny til Canvas.</p>
                </div>
            </div>
        </div>

        <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px; ali">
                <div class="container">
                    <h4><b>Fakultetskontakt</b></h4>
                    <p>Finn din Canvas kontakt på ditt institutt.</p>
                </div>
            </div>
        </div>

        <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px;">
                <div class="container">
                    <h4><b>Kurskontakt</b></h4>
                    <p>Få en oversikt over kursene.</p>
                </div>
            </div>
        </div>

        <div class="col-3">
            <div class="card">
                <img src="Avatar_01.png" alt="Image" style="width: 200px;">
                <div class="container">
                    <h4><b>Innføringsplan av Canvas</b></h4>
                    <p>Hvordan canvas skal rulles ut.</p>
                </div>
            </div>
        </div>
    </div>
</div>


问:
Sharing variables in Tensorflow, how to share conv2d()?
I am trying to access once created variable(or Tensor and variable altoghter, not sure yet about separation of those definitions in TF) in following way:

```<code>def C2d(Tensor, params):
    with tf.variable_scope("conv"):
        Tensor = tf.pad(Tensor, params)
        conv = tf.contrib.layers.conv2d(Tensor, params)
    return conv

with tf.variable_scope('scope1'):
    var1 = C2d(Tensor, params)

with tf.variable_scope('scope1', reuse=True):
    var2 = C2d(Tensor, params)
</code>```

and

```<code>print(var1 == var2)
</code>```

prints False

var1: <tf.Tensor 'scope1/conv/Conv/Relu:0' shape=(475, 473, 256) dtype=float32>

```<code>var2:  <tf.Tensor 'scope1_1/conv/Conv/Relu:0' shape=(475, 473, 256) dtype=float32>
</code>```

How do I get same Tensor with such function call?

And follow-up question, tf.contrib.layers.conv2d(...) takes as a parameter weigth_initializer, if I am trying to get a reference by variable to an existing tensor that already has it's initialization, what happens when I pass this parameter initializer second time?

答:
Actually the functioning seems correct to me, tf.contrib.layers.conv2d() returns the output of the layer, and it is normal that it returns different outputs when you call it two times.

If you check the variables created in your graph, for instance with tf.global_variables(), you will see that it has created only one copy of the variables initiated by the layer.

For the second question, you can pass the same variable initializer to many variables, so it should not conflict.

Body:
I am trying to access once created variable(or Tensor and variable altoghter, not sure yet about separation of those definitions in TF) in following way:

def C2d(Tensor, params):
    with tf.variable_scope("conv"):
        Tensor = tf.pad(Tensor, params)
        conv = tf.contrib.layers.conv2d(Tensor, params)
    return conv

with tf.variable_scope('scope1'):
    var1 = C2d(Tensor, params)

with tf.variable_scope('scope1', reuse=True):
    var2 = C2d(Tensor, params)

and

print(var1 == var2)

prints False

var1: <tf.Tensor 'scope1/conv/Conv/Relu:0' shape=(475, 473, 256) dtype=float32>

var2:  <tf.Tensor 'scope1_1/conv/Conv/Relu:0' shape=(475, 473, 256) dtype=float32>

How do I get same Tensor with such function call?

And follow-up question, tf.contrib.layers.conv2d(...) takes as a parameter weigth_initializer, if I am trying to get a reference by variable to an existing tensor that already has it's initialization, what happens when I pass this parameter initializer second time?


问:
How to use tilde in css correctly in structure?
I have the following issue.

In a demo part I have the code below:

Standard size

Big size

Very big size

```

When you move the mouse cursor over one of the text paragraphs an image should appear. That will work if I replace the paragraphs above the code with the images.

But when I put in the structure like I showed above it doesn't work.

I tried to find answer online why it doesn't work... I post my question here because I didn't fine a clear answer.

答:
Maybe this is what you are looking for?

Anyway siblings selector is for element that come after not before.

.manImgA { display: none; }
.manImgB { display: none; }
.manImgC { display: none; }

.text.prijsa:hover ~ .manImgA { display: block; }
.text.prijsb:hover ~ .manImgB { display: block; }
.text.prijsc:hover ~ .manImgC { display: block; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="text prijsa">Standard size</p>
<p class="text prijsb">Big size</p>
<p class="text prijsc">Very big size</p>

<div class="manImgA">
   <img src="https://dummyimage.com/300x300/000/fff&text=ONE">
</div>

<div class="manImgB">
   <img src="https://dummyimage.com/400x400/000/fff&text=TWO">
</div>

<div class="manImgC">
   <img src="https://dummyimage.com/600x600/000/fff&text=THREE">
</div></code>```

Body:
I have the following issue.

In a demo part I have the code below:

Standard size

Big size

Very big size

When you move the mouse cursor over one of the text paragraphs an image should appear. That will work if I replace the paragraphs above the code with the images.

But when I put in the structure like I showed above it doesn't work.

I tried to find answer online why it doesn't work... I post my question here because I didn't fine a clear answer.

Body:
Maybe this is what you are looking for?

Anyway siblings selector is for element that come after not before.

.manImgA { display: none; }
.manImgB { display: none; }
.manImgC { display: none; }

.text.prijsa:hover ~ .manImgA { display: block; }
.text.prijsb:hover ~ .manImgB { display: block; }
.text.prijsc:hover ~ .manImgC { display: block; }

<p class="text prijsa">Standard size</p>
<p class="text prijsb">Big size</p>
<p class="text prijsc">Very big size</p>

<div class="manImgA">
   <img src="https://dummyimage.com/300x300/000/fff&text=ONE">
</div>

<div class="manImgB">
   <img src="https://dummyimage.com/400x400/000/fff&text=TWO">
</div>

<div class="manImgC">
   <img src="https://dummyimage.com/600x600/000/fff&text=THREE">
</div>


问:
ng test JavaScript heap out of memory in angular due to large mock data
I am doing testing in angular 4 in my test cases i need large amount of data.
I dynamically require the json which is needed in my spec files.
These files are approximately 4 to 5 MB.

Here is some reference ...

```<code>  it('Multiple JSON:', () => {
    rdocList.forEach(element => {
      if (element.rdoc_id) {
        service.rdoc = require('../mock/' +
          element.rdoc_id +
          '.json');
        service.rdoc = new RDoc(service.rdoc);
        const storage = service.rdoc.descendants.filter({
          class_id: STORAGE_CLASS_IDS.ID
        });
        const clusterNode = storage[0].descendants.filter({
          class_id: STORAGE_CLASS_IDS.CLUSTERID
        });
        component.id = clusterNode[0].id;
        fixture.detectChanges();
      }
    });
  });
</code>```

i have cleared the json in after each..

```<code>  afterEach(() => {
    service.rdoc = null;
    service = null;
  });
</code>```

i get this issue

```<code>FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
</code>```

答:
Move to npm location in this path - C:\Users*UserName*\AppData\Roaming\npm

try to changing ng.cmd to this:

```<code>@IF EXIST "%~dp0\node.exe" (
   "%~dp0\node.exe" --max_old_space_size=8192 "%~dp0\..\@angular\cli\bin\ng" %*
) ELSE (
   @SETLOCAL
   @SET PATHEXT=%PATHEXT:;.JS;=;%
   node --max_old_space_size=8192 "%~dp0\..\@angular\cli\bin\ng" %*
)
</code>```

change in ngc.cmd to:

```<code>@IF EXIST "%~dp0\node.exe" (
       "%~dp0\node.exe" --max_old_space_size=8192 "%~dp0\..\@angular\compiler-cli\src\main.js" %*
 ) ELSE (
       @SETLOCAL
       @SET PATHEXT=%PATHEXT:;.JS;=;%
       node --max_old_space_size=8192 "%~dp0\..\@angular\compiler-cli\src\main.js" %*
 )
</code>```

Body:
I am doing testing in angular 4 in my test cases i need large amount of data.
I dynamically require the json which is needed in my spec files.
These files are approximately 4 to 5 MB.

Here is some reference ...

  it('Multiple JSON:', () => {
    rdocList.forEach(element => {
      if (element.rdoc_id) {
        service.rdoc = require('../mock/' +
          element.rdoc_id +
          '.json');
        service.rdoc = new RDoc(service.rdoc);
        const storage = service.rdoc.descendants.filter({
          class_id: STORAGE_CLASS_IDS.ID
        });
        const clusterNode = storage[0].descendants.filter({
          class_id: STORAGE_CLASS_IDS.CLUSTERID
        });
        component.id = clusterNode[0].id;
        fixture.detectChanges();
      }
    });
  });

i have cleared the json in after each..

  afterEach(() => {
    service.rdoc = null;
    service = null;
  });

i get this issue

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

Body:
Move to npm location in this path - C:\Users*UserName*\AppData\Roaming\npm

try to changing ng.cmd to this:

@IF EXIST "%~dp0\node.exe" (
   "%~dp0\node.exe" --max_old_space_size=8192 "%~dp0\..\@angular\cli\bin\ng" %*
) ELSE (
   @SETLOCAL
   @SET PATHEXT=%PATHEXT:;.JS;=;%
   node --max_old_space_size=8192 "%~dp0\..\@angular\cli\bin\ng" %*
)

change in ngc.cmd to:

@IF EXIST "%~dp0\node.exe" (
       "%~dp0\node.exe" --max_old_space_size=8192 "%~dp0\..\@angular\compiler-cli\src\main.js" %*
 ) ELSE (
       @SETLOCAL
       @SET PATHEXT=%PATHEXT:;.JS;=;%
       node --max_old_space_size=8192 "%~dp0\..\@angular\compiler-cli\src\main.js" %*
 )