问:
Django REST Framework allow only superusers to access api web view
I'm using Django 2.0 and Django RESET Framework to write REST API for my application.

I have configured following authentication methods

```<code>REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
}
</code>```

As of now, It allows all authenticated users to access web api view.

What I want is to allow few users (probably superadmin users) to be able to access API from Session Authentication or from web browser by logging in.

Edit 2: contacts/views.py

```<code>class ContactViewSet(viewsets.ModelViewSet):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializer
    permission_classes = (IsAuthenticated,)

    def perform_create(self, serializer):
        serializer.save(user_id=self.request.user)
</code>```

答:
For Django 2 (Added in views.py)</p>

```<code>from rest_framework.permissions import IsAdminUser

class IsSuperUser(IsAdminUser):
    def has_permission(self, request, view):
        return bool(request.user and request.user.is_superuser)

class ListSmth(ListCreateAPIView):
    permission_classes = (IsSuperUser,)
    ... Your code...
</code>```

Body:
I'm using Django 2.0 and Django RESET Framework to write REST API for my application.

I have configured following authentication methods

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
}

As of now, It allows all authenticated users to access web api view.

What I want is to allow few users (probably superadmin users) to be able to access API from Session Authentication or from web browser by logging in.

Edit 2: contacts/views.py

class ContactViewSet(viewsets.ModelViewSet):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializer
    permission_classes = (IsAuthenticated,)

    def perform_create(self, serializer):
        serializer.save(user_id=self.request.user)

Body:
For Django 2 (Added in views.py)

from rest_framework.permissions import IsAdminUser

class IsSuperUser(IsAdminUser):
    def has_permission(self, request, view):
        return bool(request.user and request.user.is_superuser)

class ListSmth(ListCreateAPIView):
    permission_classes = (IsSuperUser,)
    ... Your code...


来源: stackexchange

问:
How to insert saturdays and sundays between two dates in a table using sql?
Say starting date is 8/04/2010
ending date is 8/04/2011
I need the dates of saturdays and sundays to be inserted in a table...
Need Help</p>

答:
Use an unambiguous date format, like '2010-08-04'. This sorts correctly as either date or text, and everybody knows it means 04-Aug, not 08-Apr.

I like to use a calendar table for queries like this.  This will select the dates.

```<code>select cal_date
from calendar
where cal_date between '2010-08-04' and '2011-08-04'
and (day_of_week = 'Sat' or day_of_week = 'Sun');
</code>```

Something like this will insert them into a table.  (Depending on the table.)

```<code>insert into your_table_name
select cal_date
from calendar
where cal_date between '2010-08-04' and '2011-08-04'
and (day_of_week = 'Sat' or day_of_week = 'Sun');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use an unambiguous date format, like '2010-08-04'. This sorts correctly as either date or text, and everybody knows it means 04-Aug, not 08-Apr.

I like to use a calendar table for queries like this.  This will select the dates.

select cal_date
from calendar
where cal_date between '2010-08-04' and '2011-08-04'
and (day_of_week = 'Sat' or day_of_week = 'Sun');

Something like this will insert them into a table.  (Depending on the table.)

insert into your_table_name
select cal_date
from calendar
where cal_date between '2010-08-04' and '2011-08-04'
and (day_of_week = 'Sat' or day_of_week = 'Sun');


问:
Android 9 (Pie), Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord
First of all,
I looked at these;

Context.startForegroundService() did not then call
Service.startForeground()

Context.startForegroundService() did not then call Service.startForeground

Android 9 (Pie) Only: Context.startForegroundService() did not then call Service.startForeground() - Works fine on Oreo

RemoteServiceException Context.startForegroundService() did not then call Service.startForeground()

https://issuetracker.google.com/issues/76112072

I have a streaming application used by almost a million people. I'm using foreground service for the player. I didn't implement MediaSession yet. I have a 99.95% crash-free sessions.
So this app works on all versions but I started getting crash reports(ANR) with android 9. This crash occurs only Samsung phones, especially s9, s9+, s10, s10+, note9 models.

I tried these,

Calling startForeground() method in onCreate()

Calling Service.startForeground() before Context.stopService()

Other stackoverflow answers to similar questions

I read some comments from developers of Google, they said it's just Intended Behavior. I wonder is it occurred by Samsung's system or Android OS. Does anyone have an opinion about this? How can I fix this?

答:
I was waiting my crash report to share the solution. I didn't get any crash or ANR almost 20 days. I want to share my solution. It can help those who encounter this problem.

In onCreate() method

First of all, my app is a media application. I didn't implement the mediasession yet. I'm creating a notification channel in the top of onCreate().  Official doc

I'm calling Service.startForeground() method after Context.startForegroundService() method. In my prepareAndStartForeground() method.

Note: I don't know why but ContextCompat.startForegroundService() doesn't work properly.

For this reason, I've added manually same function to my service class instead of calling ContextCompat.startForegroundService()

```<code>private fun startForegroundService(intent: Intent) {
    if (Build.VERSION.SDK_INT >= 26) {
        context.startForegroundService(intent)
    } else {
        // Pre-O behavior.
        context.startService(intent)
    }
}
</code>```

prepareAndStartForeground() method

```<code>private fun prepareAndStartForeground() {
    try {
        val intent = Intent(ctx, MusicService::class.java)
        startForegroundService(intent)

        val n = mNotificationBuilder.build()
        // do sth
        startForeground(Define.NOTIFICATION_ID, n)
    } catch (e: Exception) {
        Log.e(TAG, "startForegroundNotification: " + e.message)
    }
}
</code>```

It's my onCreate()

```<code>override fun onCreate() {
    super.onCreate()
    createNotificationChannel()
    prepareAndStartForeground()
}
</code>```

My onStartCommand()

```<code>override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    if (intent == null) {
        return START_STICKY_COMPATIBILITY
    } else {
        //....
        //...
    }
    return START_STICKY
}
</code>```

onRebind, onBind, onUnbind methods like these

```<code>internal var binder: IBinder? = null

override fun onRebind(intent: Intent) {
    stopForeground(true) // <- remove notification
}

override fun onBind(intent: Intent): IBinder? {
    stopForeground(true) // <- remove notification
    return binder
}

override fun onUnbind(intent: Intent): Boolean {
    prepareAndStartForeground() // <- show notification again
    return true
}
</code>```

We need to clear something when onDestroy() calling

```<code>   override fun onDestroy() {
    super.onDestroy()
    releaseService()
   }
</code>```

```<code>private fun releaseService() {
    stopMedia()
    stopTimer()
    // sth like these
    player = null
    mContext = null
    afChangeListener = null
    mAudioBecomingNoisy = null
    handler = null
    mNotificationBuilder = null
    mNotificationManager = null
    mInstance = null
}
</code>```

I hope this solution works properly for you.

ContentLicense: CC BY-SA 4.0

Body:
I was waiting my crash report to share the solution. I didn't get any crash or ANR almost 20 days. I want to share my solution. It can help those who encounter this problem.

In onCreate() method

First of all, my app is a media application. I didn't implement the mediasession yet. I'm creating a notification channel in the top of onCreate().  Official doc

I'm calling Service.startForeground() method after Context.startForegroundService() method. In my prepareAndStartForeground() method.

Note: I don't know why but ContextCompat.startForegroundService() doesn't work properly.

For this reason, I've added manually same function to my service class instead of calling ContextCompat.startForegroundService()

private fun startForegroundService(intent: Intent) {
    if (Build.VERSION.SDK_INT >= 26) {
        context.startForegroundService(intent)
    } else {
        // Pre-O behavior.
        context.startService(intent)
    }
}

prepareAndStartForeground() method

private fun prepareAndStartForeground() {
    try {
        val intent = Intent(ctx, MusicService::class.java)
        startForegroundService(intent)

        val n = mNotificationBuilder.build()
        // do sth
        startForeground(Define.NOTIFICATION_ID, n)
    } catch (e: Exception) {
        Log.e(TAG, "startForegroundNotification: " + e.message)
    }
}

It's my onCreate()

override fun onCreate() {
    super.onCreate()
    createNotificationChannel()
    prepareAndStartForeground()
}

My onStartCommand()

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    if (intent == null) {
        return START_STICKY_COMPATIBILITY
    } else {
        //....
        //...
    }
    return START_STICKY
}

onRebind, onBind, onUnbind methods like these

internal var binder: IBinder? = null

override fun onRebind(intent: Intent) {
    stopForeground(true) // <- remove notification
}

override fun onBind(intent: Intent): IBinder? {
    stopForeground(true) // <- remove notification
    return binder
}

override fun onUnbind(intent: Intent): Boolean {
    prepareAndStartForeground() // <- show notification again
    return true
}

We need to clear something when onDestroy() calling

   override fun onDestroy() {
    super.onDestroy()
    releaseService()
   }

private fun releaseService() {
    stopMedia()
    stopTimer()
    // sth like these
    player = null
    mContext = null
    afChangeListener = null
    mAudioBecomingNoisy = null
    handler = null
    mNotificationBuilder = null
    mNotificationManager = null
    mInstance = null
}

I hope this solution works properly for you.


问:
How to plot scatter pie chart using matplotlib
I find the code example for drawing scatter pie chat

In this example, the size of each pie slices is identical across all three scatters. I would like to know if it is possible to make each pie chart unique (different number of slices and different pie proportions)

答:
Yes, it's totally possible. Here's a function that plot a pie chart at given position with a given size:

```<code>def draw_pie(dist,
             xpos,
             ypos,
             size,
             ax=None):
    if ax is None:
        fig, ax = plt.subplots(figsize=(10,8))

    # for incremental pie slices
    cumsum = np.cumsum(dist)
    cumsum = cumsum/ cumsum[-1]
    pie = [0] + cumsum.tolist()

    for r1, r2 in zip(pie[:-1], pie[1:]):
        angles = np.linspace(2 * np.pi * r1, 2 * np.pi * r2)
        x = [0] + np.cos(angles).tolist()
        y = [0] + np.sin(angles).tolist()

        xy = np.column_stack([x, y])

        ax.scatter([xpos], [ypos], marker=xy, s=size)

    return ax
</code>```

Using that function, we can draw, say three pie charts:

```<code>fig, ax = plt.subplots(figsize=(10,8))
draw_pie([1,2,1],1,1,10000,ax=ax)
draw_pie([2,2,2,2], 2, 1, 20000, ax=ax)
draw_pie([1,1,1,1,1], 1.5,1.5, 30000, ax=ax)
plt.xlim(0.6,2.5)
plt.ylim(0.8, 1.8)
plt.show()
</code>```

gives:

Body:
Yes, it's totally possible. Here's a function that plot a pie chart at given position with a given size:

def draw_pie(dist,
             xpos,
             ypos,
             size,
             ax=None):
    if ax is None:
        fig, ax = plt.subplots(figsize=(10,8))

    # for incremental pie slices
    cumsum = np.cumsum(dist)
    cumsum = cumsum/ cumsum[-1]
    pie = [0] + cumsum.tolist()

    for r1, r2 in zip(pie[:-1], pie[1:]):
        angles = np.linspace(2 * np.pi * r1, 2 * np.pi * r2)
        x = [0] + np.cos(angles).tolist()
        y = [0] + np.sin(angles).tolist()

        xy = np.column_stack([x, y])

        ax.scatter([xpos], [ypos], marker=xy, s=size)

    return ax

Using that function, we can draw, say three pie charts:

fig, ax = plt.subplots(figsize=(10,8))
draw_pie([1,2,1],1,1,10000,ax=ax)
draw_pie([2,2,2,2], 2, 1, 20000, ax=ax)
draw_pie([1,1,1,1,1], 1.5,1.5, 30000, ax=ax)
plt.xlim(0.6,2.5)
plt.ylim(0.8, 1.8)
plt.show()

gives:


问:
"sample larger than population" in random.sample python
creating a simple pass generator for myself, i noticed that if i want my population to be digits only (0-9) which is overall 10 options, if i want my length over 10, it wont use any of the digits more then once and return the "sample larger then population" error.

is it possible to maintain the code, but add/reduce code lines so it works? or do i HAVE To use a use random choice?

```<code>import string
import random

z=int(raw_input("for: \n numbers only choose 1, \n letters only choose 2, \n letters and numbers choose 3, \n for everything choose 4:"))

if z==1:
    x=string.digits
elif z==2:
    x=string.letters
elif z==3:
    x=string.letters+string.digits
elif z==4:
    x=string.letters+string.digits+string.punctuation
else:
    print "die in a fire"

y=int(raw_input("How many passwords would you like?:"))
v=int(raw_input("How long would you like the password to be?:"))

for i in range(y):
    string=""
    for n in random.sample(x,v):
        string+=n
    print string
</code>```

ty

答: Since the python_3.6 you can use random.choices(x, k=v) for your purpose. It returns a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

Body:
creating a simple pass generator for myself, i noticed that if i want my population to be digits only (0-9) which is overall 10 options, if i want my length over 10, it wont use any of the digits more then once and return the "sample larger then population" error.

is it possible to maintain the code, but add/reduce code lines so it works? or do i HAVE To use a use random choice?

import string
import random

z=int(raw_input("for: \n numbers only choose 1, \n letters only choose 2, \n letters and numbers choose 3, \n for everything choose 4:"))

if z==1:
    x=string.digits
elif z==2:
    x=string.letters
elif z==3:
    x=string.letters+string.digits
elif z==4:
    x=string.letters+string.digits+string.punctuation
else:
    print "die in a fire"

y=int(raw_input("How many passwords would you like?:"))
v=int(raw_input("How long would you like the password to be?:"))

for i in range(y):
    string=""
    for n in random.sample(x,v):
        string+=n
    print string

ty


问:
Concourse: What is the difference between "Resource Types" and "Resource"?
When i developing pipeline i can't understand the difference between "Resource Types" and "Resource".
According to documentation Resource type is there only to provide the type of the resource and check for the tags. Like in example bellow:

```<code>---
resource_types:
- name: rss
  type: docker-image
  source:
    repository: suhlig/concourse-rss-resource
    tag: latest

resources:
- name: booklit-releases
  type: rss
  source:
    url: http://www.qwantz.com/rssfeed.php

jobs:
- name: announce
  plan:
  - get: booklit-releases
    trigger: true
</code>```

Why do we need both of them? isn't it enough just to use resources?

答:
I'm also new to this project. Please correct me if I am wrong.

I think in the term of the container:

A resource type is an image and we need to config the repository and tag in its source so that the concourse can locate/download it.

A resource is a container which is an instance of that image and can be used in the jobs when the pipeline is running. Its source that we configure is the common parameters which will be passed on the stdin to the check, in and out scripts when the resource is configured in a get or put step.

I think it's a little similar to the comparison between the class and object.

Body:
When i developing pipeline i can't understand the difference between "Resource Types" and "Resource".
According to documentation Resource type is there only to provide the type of the resource and check for the tags. Like in example bellow:

---
resource_types:
- name: rss
  type: docker-image
  source:
    repository: suhlig/concourse-rss-resource
    tag: latest

resources:
- name: booklit-releases
  type: rss
  source:
    url: http://www.qwantz.com/rssfeed.php

jobs:
- name: announce
  plan:
  - get: booklit-releases
    trigger: true

Why do we need both of them? isn't it enough just to use resources?


问:
How can I set session timeout for 2-3 days in PHP?
I would like to set my sessions to last for 2-3 days so that my users will not have to login to get data after days of being idle.

Please help me with the code to achieve this.

答:
```<code><?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+(3600*24*2));  /* expire in 2 days */
?>
</code>```

http://php.net/manual/en/function.setcookie.php

Body:
<?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+(3600*24*2));  /* expire in 2 days */
?>

http://php.net/manual/en/function.setcookie.php


问:
CLion contexts and CMakeCache
I am running into the problem of easily switching between Debug and Release builds of my projects in CLion. After looking around, I found that in 2016, the system was changed and many users ran into trouble. However, none of the fixes that were suggested helped me.

Under Settings / Cmake, I entered two profiles, Release and Debug. However, in both the configuration selection at the top right of the editor and the context selection at the bottom right of the editor, only the first of the two profiles is available.

Also, the first profile seems to work fine with CMake, whereas for the second one I get an error message:

```<code>Cannot generate 'Debug' into /home/foo/code/cmake-build-debug
CMakeCache.txt is found in the project dir, only in-source generation will be performed.

[Failed to reload]
</code>```

答:
!! please backup your project before applying my instructions !!

I have got the same problem after adding new target to the CMakeLists.txt

To solve this error:

Cannot generate 'Release' into .....<path>.....
  CMakeCache.txt is found in the project dir, only in-source generation will be performed.

I delete folders cmake-build-* and CMakeCache.txt

After it I have got next error (or something like this):

Error cmake cache

To solve this error I just restart the clion.
Also sometimes I press File -> Reload CMake Project, but visually nothing happends.

As result I have got workable project.

Title: CLion contexts and CMakeCache

Body:
I am running into the problem of easily switching between Debug and Release builds of my projects in CLion. After looking around, I found that in 2016, the system was changed and many users ran into trouble. However, none of the fixes that were suggested helped me.

Under Settings / Cmake, I entered two profiles, Release and Debug. However, in both the configuration selection at the top right of the editor and the context selection at the bottom right of the editor, only the first of the two profiles is available.

Also, the first profile seems to work fine with CMake, whereas for the second one I get an error message:

Cannot generate 'Debug' into /home/foo/code/cmake-build-debug
CMakeCache.txt is found in the project dir, only in-source generation will be performed.

[Failed to reload]


问:
Spring MongoDB Aggregation Group - Can't get the group query right
I have a document in a MongoDB, which looks like follows.

```<code>{
    "_id" : ObjectId("5ceb812b3ec6d22cb94c82ca"),
    "key" : "KEYCODE001",
    "values" : [
        {
            "classId" : "CLASS_01",
            "objects" : [
                {
                    "code" : "DD0001"
                },
                {
                    "code" : "DD0010"
                }
            ]
        },
        {
            "classId" : "CLASS_02",
            "objects" : [
                {
                    "code" : "AD0001"
                }
            ]
        }
    ]
}
</code>```

I am interested in getting a result like follows.

```<code>{
    "classId" : "CLASS_01",
    "objects" : [
        {
            "code" : "DD0001"
        },
        {
            "code" : "DD0010"
        }
    ]
}
</code>```

To get this, I came up with an aggregation pipeline in Robo 3T, which looks like follows. And it's working as expected.

```<code>[
    {
        $match:{
            'key':'KEYCODE001'
        }
    },
    {
        "$unwind":{
            "path": "$values",
            "preserveNullAndEmptyArrays": true
        }
    },
    {
        "$unwind":{
            "path": "$values.objects",
            "preserveNullAndEmptyArrays": true
        }
    },
    {
        $match:{
            'values.classId':'CLASS_01'
        }
    },
    {
        $project:{
            'object':'$values.objects',
            'classId':'$values.classId'
        }
    },
    {
        $group:{
            '_id':'$classId',
            'objects':{
                $push:'$object'
            }
        }
    },
    {
        $project:{
            '_id':0,
            'classId':'$_id',
            'objects':'$$objects'
        }
    }
]
</code>```

Now, when I try to do the same in a SpringBoot application, I can't get it running. I ended up having the error java.lang.IllegalArgumentException: Invalid reference '$complication'!. Following is what I have done in Java so far.

```<code>final Aggregation aggregation = newAggregation(
        match(Criteria.where("key").is("KEYCODE001")),
        unwind("$values", true),
        unwind("$values.objects", true),
        match(Criteria.where("classId").is("CLASS_01")),
        project().and("$values.classId").as("classId").and("$values.objects").as("object"),
        group("classId", "objects").push("$object").as("objects").first("$classId").as("_id"),
        project().and("$_id").as("classId").and("$objects").as("objects")
);
</code>```

What am I doing wrong? Upon research, I found that multiple fields in group does not work or something like that (please refer to this question). So, is what I am currently doing even possible in Spring Boot?

答:
After hours of debugging + trial and error, found the following solution to be working.

```<code>final Aggregation aggregation = newAggregation(
        match(Criteria.where("key").is("KEYCODE001")),
        unwind("values", true),
        unwind("values.objects", true),
        match(Criteria.where("values.classId").is("CLASS_01")),
        project().and("values.classId").as("classId").and("values.objects").as("object"),
        group(Fields.from(Fields.field("_id", "classId"))).push("object").as("objects"),
        project().and("_id").as("classId").and("objects").as("objects")
);
</code>```

It all boils down to group(Fields.from(Fields.field("_id", "classId"))).push("object").as("objects") that which introduces a org.springframework.data.mongodb.core.aggregation.Fields object that wraps a list of org.springframework.data.mongodb.core.aggregation.Field objects. Within Field, the name of the field and the target could be encapsulated. This resulted in the following pipeline which is a match for the expected.

```<code>[
    {
        "$match" :{
            "key" : "KEYCODE001"
        }
    },
    {
        "$unwind" :{
            "path" : "$values", "preserveNullAndEmptyArrays" : true
        }
    },
    {
        "$unwind" :{
            "path" : "$values.objects", "preserveNullAndEmptyArrays" : true
        }
    },
    {
        "$match" :{
            "values.classId" : "CLASS_01"
        }
    },
    {
        "$project" :{
            "classId" : "$values.classId", "object" : "$values.objects"
        }
    },
    {
        "$group" :{
            "_id" : "$classId",
            "objects" :{
                "$push" : "$object"
            }
        }
    },
    {
        "$project" :{
            "classId" : "$_id", "objects" : 1
        }
    }
]
</code>```

Additionally, figured that there is no need to using $ sign anywhere and everywhere.

Body:
I have a document in a MongoDB, which looks like follows.

{
    "_id" : ObjectId("5ceb812b3ec6d22cb94c82ca"),
    "key" : "KEYCODE001",
    "values" : [
        {
            "classId" : "CLASS_01",
            "objects" : [
                {
                    "code" : "DD0001"
                },
                {
                    "code" : "DD0010"
                }
            ]
        },
        {
            "classId" : "CLASS_02",
            "objects" : [
                {
                    "code" : "AD0001"
                }
            ]
        }
    ]
}

I am interested in getting a result like follows.

{
    "classId" : "CLASS_01",
    "objects" : [
        {
            "code" : "DD0001"
        },
        {
            "code" : "DD0010"
        }
    ]
}

To get this, I came up with an aggregation pipeline in Robo 3T, which looks like follows. And it's working as expected.

[
    {
        $match:{
            'key':'KEYCODE001'
        }
    },
    {
        "$unwind":{
            "path": "$values",
            "preserveNullAndEmptyArrays": true
        }
    },
    {
        "$unwind":{
            "path": "$values.objects",
            "preserveNullAndEmptyArrays": true
        }
    },
    {
        $match:{
            'values.classId':'CLASS_01'
        }
    },
    {
        $project:{
            'object':'$values.objects',
            'classId':'$values.classId'
        }
    },
    {
        $group:{
            '_id':'$classId',
            'objects':{
                $push:'$object'
            }
        }
    },
    {
        $project:{
            '_id':0,
            'classId':'$_id',
            'objects':'$$objects'
        }
    }
]

Now, when I try to do the same in a SpringBoot application, I can't get it running. I ended up having the error java.lang.IllegalArgumentException: Invalid reference '$complication'!. Following is what I have done in Java so far.

final Aggregation aggregation = newAggregation(
        match(Criteria.where("key").is("KEYCODE001")),
        unwind("$values", true),
        unwind("$values.objects", true),
        match(Criteria.where("classId").is("CLASS_01")),
        project().and("$values.classId").as("classId").and("$values.objects").as("object"),
        group("classId", "objects").push("$object").as("objects").first("$classId").as("_id"),
        project().and("$_id").as("classId").and("$objects").as("objects")
);

What am I doing wrong? Upon research, I found that multiple fields in group does not work or something like that (please refer to this question). So, is what I am currently doing even possible in Spring Boot?

Body:
After hours of debugging + trial and error, found the following solution to be working.

final Aggregation aggregation = newAggregation(
        match(Criteria.where("key").is("KEYCODE001")),
        unwind("values", true),
        unwind("values.objects", true),
        match(Criteria.where("values.classId").is("CLASS_01")),
        project().and("values.classId").as("classId").and("values.objects").as("object"),
        group(Fields.from(Fields.field("_id", "classId"))).push("object").as("objects"),
        project().and("_id").as("classId").and("objects").as("objects")
);

It all boils down to group(Fields.from(Fields.field("_id", "classId"))).push("object").as("objects") that which introduces a org.springframework.data.mongodb.core.aggregation.Fields object that wraps a list of org.springframework.data.mongodb.core.aggregation.Field objects. Within Field, the name of the field and the target could be encapsulated. This resulted in the following pipeline which is a match for the expected.

[
    {
        "$match" :{
            "key" : "KEYCODE001"
        }
    },
    {
        "$unwind" :{
            "path" : "$values", "preserveNullAndEmptyArrays" : true
        }
    },
    {
        "$unwind" :{
            "path" : "$values.objects", "preserveNullAndEmptyArrays" : true
        }
    },
    {
        "$match" :{
            "values.classId" : "CLASS_01"
        }
    },
    {
        "$project" :{
            "classId" : "$values.classId", "object" : "$values.objects"
        }
    },
    {
        "$group" :{
            "_id" : "$classId",
            "objects" :{
                "$push" : "$object"
            }
        }
    },
    {
        "$project" :{
            "classId" : "$_id", "objects" : 1
        }
    }
]

Additionally, figured that there is no need to using $ sign anywhere and everywhere.


问:
When does nomad throttle a task?
How does nomad limit resource consumption for a task? If there are two tasks within a group that each have cpu = 100, is there a shared pool of 200 that both tasks have access to? What happens if one of those tasks wants access to more CPU ticks?

```<code>job "docs" {
  group "example" {
    task "server" {
      resources {
        cpu    = 100
        memory = 256
      }
    }
    task "greeter" {
      resources {
        cpu    = 100
        memory = 256
      }
    }
  }
}
</code>```

Looking at /client/allocation/:alloc_id/stats, I see ThrottledPeriods, ThrottledTicks broken down for both resources and tasks -- will both resources and tasks throttle resource usage?

答:
This doesn't fully answer the question, but the docker driver docs have some details about how part of it works:

CPU

Nomad limits containers' CPU based on CPU shares. CPU shares allow containers to burst past their CPU limits. CPU limits will only be imposed when there is contention for resources. When the host is under load your process may be throttled to stabilize QoS depending on how many shares it has. You can see how many CPU shares are available to your process by reading NOMAD_CPU_LIMIT. 1000 shares are approximately equal to 1 GHz.

Please keep the implications of CPU shares in mind when you load test workloads on Nomad.

Memory

Nomad limits containers' memory usage based on total virtual memory. This means that containers scheduled by Nomad cannot use swap. This is to ensure that a swappy process does not degrade performance for other workloads on the same host.

Since memory is not an elastic resource, you will need to make sure your container does not exceed the amount of memory allocated to it, or it will be terminated or crash when it tries to malloc. A process can inspect its memory limit by reading NOMAD_MEMORY_LIMIT, but will need to track its own memory usage. Memory limit is expressed in megabytes so 1024 = 1 GB.

Title: When does nomad throttle a task?

Body:
How does nomad limit resource consumption for a task? If there are two tasks within a group that each have cpu = 100, is there a shared pool of 200 that both tasks have access to? What happens if one of those tasks wants access to more CPU ticks?

job "docs" {
  group "example" {
    task "server" {
      resources {
        cpu    = 100
        memory = 256
      }
    }
    task "greeter" {
      resources {
        cpu    = 100
        memory = 256
      }
    }
  }
}

Looking at /client/allocation/:alloc_id/stats, I see ThrottledPeriods, ThrottledTicks broken down for both resources and tasks -- will both resources and tasks throttle resource usage?


问:
JSP Page not rendering in SpringBoot Application
I have seen lot of same problem but My problem is not resolving with all those solutions. My JSP page is not rendering.

I have added all required jars like thymeleaf, tomcat, jstl to run the application but still getting error

Below is my controller

```<code>@RequestMapping("/rest/user")
public class BookResource {

@GetMapping("/recommend")
    public List<String> recommend() {
        return bookrepo.BookDetail(bookname);

    }
@RequestMapping(value = "/recommendation", method = RequestMethod.GET)
    public String recommend(Model model) {
        model.addAttribute("recommendations", bookrepo.BookDetail(bookname));
        model.addAttribute("name", "Harsh");
        return "recommendation";

    }
}
</code>```

After i Hit the URL I am getiing below error:

```<code>Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue May 28 09:50:33 IST 2019
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template "recommendation", template might not exist or might not be accessible by any of the configured Template Resolvers
</code>```

The JSP Page I have created not rendering, I put my jsp page inside resources/templates and also at WEB-INF/jsp/.
And properties file is also updated

```<code>spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
</code>```

Pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springBootApp</groupId>
    <artifactId>FirstSpringBootApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.6</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap-datepicker</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>1.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Redis Dependencies -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- GCP Dependencies -->

        <!-- <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter-sql-mysql</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency> -->

    </dependencies>

    <build>
        <plugins>
             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!-- GCP plugin -->
            <!-- <plugin>
                <groupId>com.google.cloud.tools</groupId>
                <artifactId>appengine-maven-plugin</artifactId>
                <version>1.3.2</version>
            </plugin> -->
        </plugins>
    </build>

</project>
</code>```

Structure .

答:
As per spring boot there are Limitations when it comes to jsp's.

If packaging is not declared in pom.xml, spring boot by default considers it as jar.

To overcome these limitations we need to have the configuration made in the application to render jsp by placing the jsp's under src/main/resources/META-INF/resources/WEB-INF/jsp folder.

Sample Code: Click Here

References:

https://dzone.com/articles/spring-boot-with-jsps-in-executable-jars-1

https://github.com/hengyunabc/spring-boot-fat-jar-jsp-sample

Body:
I have seen lot of same problem but My problem is not resolving with all those solutions. My JSP page is not rendering.

I have added all required jars like thymeleaf, tomcat, jstl to run the application but still getting error

Below is my controller

@RequestMapping("/rest/user")
public class BookResource {

@GetMapping("/recommend")
    public List<String> recommend() {
        return bookrepo.BookDetail(bookname);

    }
@RequestMapping(value = "/recommendation", method = RequestMethod.GET)
    public String recommend(Model model) {
        model.addAttribute("recommendations", bookrepo.BookDetail(bookname));
        model.addAttribute("name", "Harsh");
        return "recommendation";

    }
}

After i Hit the URL I am getiing below error:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue May 28 09:50:33 IST 2019
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template "recommendation", template might not exist or might not be accessible by any of the configured Template Resolvers

The JSP Page I have created not rendering, I put my jsp page inside resources/templates and also at WEB-INF/jsp/.
And properties file is also updated

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springBootApp</groupId>
    <artifactId>FirstSpringBootApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.6</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap-datepicker</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>1.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>

</project>

Structure .


问:
find and replace a text in different header for each section in docx using java
I am trying to find and replace a text different sections of header in each page using Apache poi but getting only null data, but Docx has different header sections and footer too

```<code>    package com.concretepage;
    import java.io.FileInputStream;
    import org.apache.poi.openxml4j.opc.OPCPackage;
    import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
    import org.apache.poi.xwpf.usermodel.XWPFDocument;
    import org.apache.poi.xwpf.usermodel.XWPFFooter;
    import org.apache.poi.xwpf.usermodel.XWPFHeader;
    public class ReadDOCXHeaderFooter {
        public static void main(String[] args) {
            try {
                FileInputStream fis = new FileInputStream("D:/docx/read-test.docx");
                XWPFDocument xdoc=new XWPFDocument(OPCPackage.open(fis));
                XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(xdoc);
                //read header

                for(int i=0;i<90;i++)
                {
                 XWPFHeader header = policy.getHeader(i);
       List<XWPFRun> runs = header.getRuns();
  if (runs != null) {
         for (XWPFRun r : runs) {
          String text = r.getText(0);
          if (text != null && text.contains("$$key$$")) {
           text = text.replace("$$key$$", "ABCD");//your content
           r.setText(text, 0);
          }
         }
                    System.out.println(header.getText());

                    //read footer
                    XWPFFooter footer = policy.getFooter(i);
                    System.out.println(footer.getText());
                }
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
</code>```

1.Screen shot of Docx header sections.

2.Screen shot of Docx header another section.

3.Screen shot of Docx header another section.

4.Screen Shot

答:
This function should do the job</p>

```<code>static void replaceHeaderText(XWPFDocument document, String searchValue, String replacement)
{
    List<XWPFHeader> headers = document.getHeaderList();
    for(XWPFHeader h : headers)
    {
        for (XWPFParagraph p : h.getParagraphs()) {
            List<XWPFRun> runs = p.getRuns();
            if (runs != null) {
                for (XWPFRun r : runs) {
                    String text = r.getText(0);
                    if (text != null && text.contains(searchValue)) {
                        text = text.replace(searchValue, replacement);
                        r.setText(text, 0);
                    }
                }
            }
        }
        for (XWPFTable tbl : h.getTables()) {
            for (XWPFTableRow row : tbl.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph p : cell.getParagraphs()) {
                        for (XWPFRun r : p.getRuns()) {
                            String text = r.getText(0);
                            if (text != null && text.contains(searchValue)) {
                                text = text.replace(searchValue, replacement);
                                r.setText(text,0);
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

Body:
I am trying to find and replace a text different sections of header in each page using Apache poi but getting only null data, but Docx has different header sections and footer too

    package com.concretepage;
    import java.io.FileInputStream;
    import org.apache.poi.openxml4j.opc.OPCPackage;
    import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
    import org.apache.poi.xwpf.usermodel.XWPFDocument;
    import org.apache.poi.xwpf.usermodel.XWPFFooter;
    import org.apache.poi.xwpf.usermodel.XWPFHeader;
    public class ReadDOCXHeaderFooter {
        public static void main(String[] args) {
            try {
                FileInputStream fis = new FileInputStream("D:/docx/read-test.docx");
                XWPFDocument xdoc=new XWPFDocument(OPCPackage.open(fis));
                XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(xdoc);
                //read header

                for(int i=0;i<90;i++)
                {
                 XWPFHeader header = policy.getHeader(i);
       List<XWPFRun> runs = header.getRuns();
  if (runs != null) {
         for (XWPFRun r : runs) {
          String text = r.getText(0);
          if (text != null && text.contains("$$key$$")) {
           text = text.replace("$$key$$", "ABCD");//your content
           r.setText(text, 0);
          }
         }
                    System.out.println(header.getText());

                    //read footer
                    XWPFFooter footer = policy.getFooter(i);
                    System.out.println(footer.getText());
                }
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }

1.Screen shot of Docx header sections.

2.Screen shot of Docx header another section.

3.Screen shot of Docx header another section.

4.Screen Shot

Body:
This function should do the job

static void replaceHeaderText(XWPFDocument document, String searchValue, String replacement)
{
    List<XWPFHeader> headers = document.getHeaderList();
    for(XWPFHeader h : headers)
    {
        for (XWPFParagraph p : h.getParagraphs()) {
            List<XWPFRun> runs = p.getRuns();
            if (runs != null) {
                for (XWPFRun r : runs) {
                    String text = r.getText(0);
                    if (text != null && text.contains(searchValue)) {
                        text = text.replace(searchValue, replacement);
                        r.setText(text, 0);
                    }
                }
            }
        }
        for (XWPFTable tbl : h.getTables()) {
            for (XWPFTableRow row : tbl.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph p : cell.getParagraphs()) {
                        for (XWPFRun r : p.getRuns()) {
                            String text = r.getText(0);
                            if (text != null && text.contains(searchValue)) {
                                text = text.replace(searchValue, replacement);
                                r.setText(text,0);
                            }
                        }
                    }
                }
            }
        }
    }
}


问:
Passing ecrypted id in url parameter using javascript
Can any one tell me how to pass encrypted id in url using JS like as localhost/data?action=23 convert 23 to encrypt

I have already tried

btoa()

atob()

but these convert only string I want to convert id in encrypted form in url parameter

```<code>var action= id;

localhost/data.php?action=encrypt(id)
</code>```

答: You can use crypto-js for encryption and decryption</p>

Body:
Can any one tell me how to pass encrypted id in url using JS like as localhost/data?action=23 convert 23 to encrypt

I have already tried

btoa()

atob()

but these convert only string I want to convert id in encrypted form in url parameter

var action= id;

localhost/data.php?action=encrypt(id)


问:
How to set Library directory for "Object" target
I would need to specify a library directory property for OBJECT target like this:

```<code>add_library( ObjTargetName OBJECT "main.cpp" )
set_target_properties( ObjTargetName PROPERTIES STATIC_LIBRARY_FLAGS "/DEF")
</code>```

It is an OBJECT target, but there is /DEF flag. And because it is OBJECT target type and not SHARED so link_directories does not work for this case. Is there a way how to specify it? I am using cmake 3.13 and VC2017.

Thanks for any hint.

答:
```<code>set_target_properties( ObjTargetName PROPERTIES STATIC_LIBRARY_OPTIONS "/DEF;/OUT:${IMPLIB_FILE_PATH}")
</code>```

Body:
I would need to specify a library directory property for OBJECT target like this:

add_library( ObjTargetName OBJECT "main.cpp" )
set_target_properties( ObjTargetName PROPERTIES STATIC_LIBRARY_FLAGS "/DEF")

It is an OBJECT target, but there is /DEF flag. And because it is OBJECT target type and not SHARED so link_directories does not work for this case. Is there a way how to specify it? I am using cmake 3.13 and VC2017.

Thanks for any hint.


问:
Https request, authentication in Android
I am currently trying to authenticate with a server via a http Get call. The code provided below works when compiled in a java project. Returning the correct token to the program. However whenever I try to implement the same code in Android I do not get a token returned via the Get call.

In Android I am returning inputLine in a function, however inputLine is always an empty string.

The system.out.println() prints the returned token.

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class JavaHttpsExample
{

public static void main(String[] args)
{   String inputLine = new String();
    try
    {
    String httpsURL = "https://the url";
    URL myurl = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
    InputStream ins = con.getInputStream();
    InputStreamReader isr=new InputStreamReader(ins);
    BufferedReader in =new BufferedReader(isr);

    inputLine = in.readLine();

    System.out.println(inputLine);

    in.close();

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

thanks for your help!!!

答:
I'm using POST and FormEntity for retrieving data from the server (such as authentication), and i have never had any problems:

```<code>final String httpsURL = "https://the url";
final DefaultHttpClient client = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(httpsURL);

//authentication block:
final List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("userName", userName));
nvps.add(new BasicNameValuePair("password", password));
final UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httppost.setEntity(p_entity);

//sending the request and retrieving the response:
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();

//handling the response: responseEntity.getContent() is your InputStream
final InputSource inputSource = new InputSource(responseEntity.getContent());
[...]
</code>```

maybe you'll find this usefull

ContentLicense: CC BY-SA 2.5

Body:
I am currently trying to authenticate with a server via a http Get call. The code provided below works when compiled in a java project. Returning the correct token to the program. However whenever I try to implement the same code in Android I do not get a token returned via the Get call.

In Android I am returning inputLine in a function, however inputLine is always an empty string.

The system.out.println() prints the returned token.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class JavaHttpsExample
{

public static void main(String[] args)
{   String inputLine = new String();
    try
    {
    String httpsURL = "https://the url";
    URL myurl = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
    InputStream ins = con.getInputStream();
    InputStreamReader isr=new InputStreamReader(ins);
    BufferedReader in =new BufferedReader(isr);

    inputLine = in.readLine();

    System.out.println(inputLine);

    in.close();

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

thanks for your help!!!

Body:
I'm using POST and FormEntity for retrieving data from the server (such as authentication), and i have never had any problems:

final String httpsURL = "https://the url";
final DefaultHttpClient client = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(httpsURL);

//authentication block:
final List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("userName", userName));
nvps.add(new BasicNameValuePair("password", password));
final UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httppost.setEntity(p_entity);

//sending the request and retrieving the response:
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();

//handling the response: responseEntity.getContent() is your InputStream
final InputSource inputSource = new InputSource(responseEntity.getContent());
[...]

maybe you'll find this usefull


问:
Problem with sending events to analytics over Facebook SDK
I using com.facebook.android:facebook-core:5.0.0
When I try send event to analytics like this

```<code>val logger = AppEventsLogger.newLogger(context, "my_app_id")
logger.logEvent("event", Bundle())
</code>```

But I has error in logs

```<code>    E/GraphResponse: {HttpStatus: 404, errorCode: 803, subErrorCode: -1,
 errorType: OAuthException, errorMessage: (#803) Some of the aliases you
 requested do not exist: "my_app_id"}
</code>```

App was setup like in https://developers.facebook.com/quickstarts/?platform=android

Facebook's support don't answer

答:
I fix with two point:

1: add two activities in manifest .

```<code><activity android:name="com.facebook.FacebookActivity"
          android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
          android:label="@string/app_name"/>

<activity android:name="com.facebook.CustomTabActivity"
          android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="@string/fb_login_protocol_scheme"/>
    </intent-filter>
</activity>
</code>```

2: replace manifestPlaceholders in app/build.gradle with

```<code>resValue "string", "facebook_app_id", "$fbAppId"
resValue "string", "fb_login_protocol_scheme", "fb$fbAppId"
</code>```

I don't know why did't work manifestPlaceholders.

Body:
I using com.facebook.android:facebook-core:5.0.0
When I try send event to analytics like this

val logger = AppEventsLogger.newLogger(context, "my_app_id")
logger.logEvent("event", Bundle())

But I has error in logs

    E/GraphResponse: {HttpStatus: 404, errorCode: 803, subErrorCode: -1,
 errorType: OAuthException, errorMessage: (#803) Some of the aliases you
 requested do not exist: "my_app_id"}

App was setup like in https://developers.facebook.com/quickstarts/?platform=android

Facebook's support don't answer

Body:
I fix with two point:

1: add two activities in manifest .

<activity android:name="com.facebook.FacebookActivity"
          android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
          android:label="@string/app_name"/>

<activity android:name="com.facebook.CustomTabActivity"
          android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="@string/fb_login_protocol_scheme"/>
    </intent-filter>
</activity>

2: replace manifestPlaceholders in app/build.gradle with

resValue "string", "facebook_app_id", "$fbAppId"
resValue "string", "fb_login_protocol_scheme", "fb$fbAppId"

I don't know why did't work manifestPlaceholders.


问:
Microsoft Graph REST API v1.0 - List personal contacts using application permissions
I've registered a web application in Azure Portal, granted it a Contacts.Read permission, gave it an administrator consent and now trying to list personal contacts of a particular user with Microsoft Graph REST API v1.0 using this application.

At first i'm trying to get an access token by sending POST request to
https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token with following body parameters: scope=https://graph.microsoft.com/contacts.read, grant_type=client_credentials, my client_id and my client_secret.

In response i'm getting an error 400 Bad Request. Body:
{"error":"invalid_scope","error_description":"AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is not valid. The scope https://graph.microsoft.com/contacts.read is not valid."}

When i'm replacing scope parameter in token request like this: scope=https://graph.microsoft.com/.default, i'm actually receiving 200 OK and my Bearer token in response.

But when i'm requesting user personal contacts by sending GET request to https://graph.microsoft.com/v1.0/users/{user_id}/contacts with this token, i'm getting 401 Unauthorized in response with following error:

"code": "NoPermissionsInAccessToken",
"message": "The token contains no permissions, or permissions can not be understood.",

I've also tried to replace the scope value in my token request with {app_id_uri}/.default and {app_id_uri}/contacts.read with no luck.

So how do i list user personal contacts using Microsoft Graph REST API v1.0? What am i doing wrong?

EDIT: Permissions screenshot:

答:
I granted to my application wrong permissions. It was Contacts.Read and User.Read.All permissions in Exchange section instead of Microsoft Graph section.

I granted those permissions in Microsoft Graph section and everything worked. In fact Contacts.Read permission is enough.

P.S. the scope is https://graph.microsoft.com/.default


问:
Difference between a web-service and web-socket
As I mentioned in the title: I would like to know the difference between the web-service and the web-socket? when we used each one?

Thanks!

答:
Web services are based on HTTP protocol and use HTTP methods to relay data in a request and response paradigm. Thus the client will always be the one responsible for communicating with the server, requesting data and submitting data to the server i.e getting list of customers or products, adding products or customers to server.

In contrast, Web sockets allow bidirectional communication, meaning server can initiate communication as much as client can do the same. Typically you supply a host IP Address and port to the socket. Web sockets can be used to implement a chat application.

The key difference between Web sockets and Web services is that with web sockets you get bi-directional connection in which the server and client can continuously send messages back and forth while Web services are uni-directional connection concerned with supplying clients with resources


问:
BehaviorSubject doesn't immediately change value
I am creating a custom login service with AuthGuard from Angular. I have a SessionService which have methods such a login() or onUserLoggedIn() which basically returns BehaviorSubject with the current value of user status (logged in/not logged in). Based on this service I created an implementation of AuthGuard implements CanActivate service. I call onUserLoggedIn method and check the current value in subject. The problem here is that in login method value is changed after the AuthGuard call onUserLoggedIn. Therefore in a first attempt I receive false value from BehaviorSubject but when I try the second time, I received a true value.

How can I change the implementation of those two services to achieve current value in a first attempt?

AuthGuard:

```<code>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
    : Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    console.log('auth');

    return this.sessionService.onUserLoggedIn()
      .pipe(
        map(res => {
          console.log('res', res);
          return res;
        }),
        take(1),
        tap(allowed => {
          console.log(allowed);
          if (!allowed) {
            this.router.navigate(['/login']);
          }
        })
      );
  }
</code>```

SessionService:

```<code>private isLoggedIn = new BehaviorSubject(false);

  constructor(private apiService: ApiService) {
  }

  login(user: User): Observable<any> {
    console.log('hello before');
    return this.apiService.post(`${BASE_URL}/login`, user)
      .pipe(
        tap((token: Token) => {
          this.isLoggedIn.next(true);
          localStorage.setItem('token', token.token);
          console.log('hello');
        })
      );
  }

  onUserLoggedIn() {
    return this.isLoggedIn;
  }
</code>```

First attempt goes with printing value:

SessionService.ts:19 hello before

AuthGuard.ts:17 auth

AuthGuard.ts:22 res false

AuthGuard.ts:27 false

SessionService.ts:25 hello

The second one (which I expect to be first):

SessionService.ts:19 hello before

AuthGuard.ts:17 auth

AuthGuard.ts:22 res true

AuthGuard.ts:27 true

SessionService.ts:25 hello

答:
The nature of BehaviorSubject is, it emit the given value immediately whenever you subscribe.

So based on your use case use Subject. Also use skip operator to skip the first value.

```<code>return this.sessionService.onUserLoggedIn()
      .pipe(
        take(1),
        map(res => {
          console.log('res', res);
          return res;
        }),
        tap(allowed => {
          console.log(allowed);
          if (!allowed) {
            this.router.navigate(['/login']);
          }
        })
      );
  }
</code>```

use startsWith(false) in other components.

Body:
I am creating a custom login service with AuthGuard from Angular. I have a SessionService which have methods such a login() or onUserLoggedIn() which basically returns BehaviorSubject with the current value of user status (logged in/not logged in). Based on this service I created an implementation of AuthGuard implements CanActivate service. I call onUserLoggedIn method and check the current value in subject. The problem here is that in login method value is changed after the AuthGuard call onUserLoggedIn. Therefore in a first attempt I receive false value from BehaviorSubject but when I try the second time, I received a true value.

How can I change the implementation of those two services to achieve current value in a first attempt?

AuthGuard:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
    : Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    console.log('auth');

    return this.sessionService.onUserLoggedIn()
      .pipe(
        map(res => {
          console.log('res', res);
          return res;
        }),
        take(1),
        tap(allowed => {
          console.log(allowed);
          if (!allowed) {
            this.router.navigate(['/login']);
          }
        })
      );
  }

SessionService:

private isLoggedIn = new BehaviorSubject(false);

  constructor(private apiService: ApiService) {
  }

  login(user: User): Observable<any> {
    console.log('hello before');
    return this.apiService.post(`${BASE_URL}/login`, user)
      .pipe(
        tap((token: Token) => {
          this.isLoggedIn.next(true);
          localStorage.setItem('token', token.token);
          console.log('hello');
        })
      );
  }

  onUserLoggedIn() {
    return this.isLoggedIn;
  }

First attempt goes with printing value:

SessionService.ts:19 hello before

AuthGuard.ts:17 auth

AuthGuard.ts:22 res false

AuthGuard.ts:27 false

SessionService.ts:25 hello

The second one (which I expect to be first):

SessionService.ts:19 hello before

AuthGuard.ts:17 auth

AuthGuard.ts:22 res true

AuthGuard.ts:27 true

SessionService.ts:25 hello

Body:
The nature of BehaviorSubject is, it emit the given value immediately whenever you subscribe.

So based on your use case use Subject. Also use skip operator to skip the first value.

return this.sessionService.onUserLoggedIn()
      .pipe(
        take(1),
        map(res => {
          console.log('res', res);
          return res;
        }),
        tap(allowed => {
          console.log(allowed);
          if (!allowed) {
            this.router.navigate(['/login']);
          }
        })
      );
  }

use startsWith(false) in other components.


问:
how to group elements of a table in a vector
I am a new member of stack and I am learning to program in r.
I have a data frame with three columns, requete, id_requete and possition_url_cliquee.
For each requete we have different id_requete.
For each id_requete we have 1 or more values of position_url_cliquee.
I want to put the position_url_cliquee in a vector for each id_requete.
I created this function which will have to return an array with id_requete and associated vectors.
But it does not work as I want

```<code>table_data=group_by(table_data,requete,id_requete)

tab_vect=data.frame(id_requete=c(),vect=c(v[]))

vecteurs=function(table_data){
  id=table_data$id_requete[1]
  j=1
  for (i in 1:5) {
    if(id==table_data$id_requete[i]){
      v[j]=c(table_data$position_url_cliquee[i])
      j=j+1
    }
    else{
      tab_vect=rbind(id,v[j])
      j=1
      v=c()
      v[j]=c(table_data$position_url_cliquee[i])

    }
  }
  return(tab_vect)
}

tablevect=vecteurs(table_data)

</code>```

I want to output a data frame with the different id_requete and associated vectors.

答:
Here is a solution in base R :

```<code>ids <- sort(unique(table_data$id_requete))
res <- lapply(ids, function(id) sort(table_data$position_url_cliquee[table_data$id_requete == id]))
names(res) <- ids
res
</code>```

Output :

```<code>$`45`
[1] 3 4

$`123`
[1] 1 2 5
</code>```

Then to convert to a dataframe, you have to complete values with NA :

```<code>tmax <- max(sapply(res, length))
res <- lapply(res, function(r) { length(r) <- tmax; r })
as.data.frame(res)
</code>```

Output :

```<code>  X45 X123
1   3    1
2   4    2
3  NA    5
</code>```

Body:
I am a new member of stack and I am learning to program in r.
I have a data frame with three columns, requete, id_requete and possition_url_cliquee.
For each requete we have different id_requete.
For each id_requete we have 1 or more values of position_url_cliquee.
I want to put the position_url_cliquee in a vector for each id_requete.
I created this function which will have to return an array with id_requete and associated vectors.
But it does not work as I want

table_data=group_by(table_data,requete,id_requete)

tab_vect=data.frame(id_requete=c(),vect=c(v[]))

vecteurs=function(table_data){
  id=table_data$id_requete[1]
  j=1
  for (i in 1:5) {
    if(id==table_data$id_requete[i]){
      v[j]=c(table_data$position_url_cliquee[i])
      j=j+1
    }
    else{
      tab_vect=rbind(id,v[j])
      j=1
      v=c()
      v[j]=c(table_data$position_url_cliquee[i])

    }
  }
  return(tab_vect)
}

tablevect=vecteurs(table_data)

I want to output a data frame with the different id_requete and associated vectors.

Body:
Here is a solution in base R :

ids <- sort(unique(table_data$id_requete))
res <- lapply(ids, function(id) sort(table_data$position_url_cliquee[table_data$id_requete == id]))
names(res) <- ids
res

Output :

$`45`
[1] 3 4

$`123`
[1] 1 2 5

Then to convert to a dataframe, you have to complete values with NA :

tmax <- max(sapply(res, length))
res <- lapply(res, function(r) { length(r) <- tmax; r })
as.data.frame(res)

Output :

  X45 X123
1   3    1
2   4    2
3  NA    5


问:
openPyXL - assign value to range of cells during unmerge
So I have excel files with several sheets in each and I'm working on script which will gather data from selected sheets if they exist in file and combine it in one, big sheet. Generally it's working, iterating through files and if desired sheet exist it finds range of cells with data and append it to dataframe. The thing I need to do now is to add header row (column names) to Dataframe, but in sheet those are multiline headers.

To make it look the same in dataframe i need to unmerge cells in top header row and copy value from first cell to rest of them in range which was merged before).

I'm using OpenPyXL for accessing excel sheets. My function receives sheet to work on as only parameter. It looks like this:

```<code>def checkForMergedCells(sheet):
    merged = ws.merged_cell_ranges
    for mergedCell in merged:
        mc_start, mc_stop = str(mergedCell).split(':')
        cp_value = sheet[mc_start]
        sheet.unmerge_cells(mergedCell)
        cell_range = sheet[mergedCell]
        for cell in cell_range:
            cell.value = cp_value
</code>```

The thing is that cell_range returns a tuple which ends up in getting error message:

AttributeError: 'tuple' object has no attribute 'value'
  Below you can see screencap during debug which shows values passed in each variable.

Debugger running

答:
I was getting errors and a deprecation warning until I did this:</p>

```<code>from openpyxl.utils import range_boundaries

for group in sheet.merged_cells.ranges: # merged_cell_ranges deprecated
    display(range_boundaries(group._get_range_string())) # expects a string instead of an object
    min_col, min_row, max_col, max_row = range_boundaries(group._get_range_string())
    top_left_cell_value = sheet.cell(row=min_row, column=min_col).value
    for row in sheet.iter_rows(min_col=min_col, min_row=min_row, max_col=max_col, max_row=max_row):
        for cell in row:
            cell.value = top_left_cell_value
</code>```

Body:
So I have excel files with several sheets in each and I'm working on script which will gather data from selected sheets if they exist in file and combine it in one, big sheet. Generally it's working, iterating through files and if desired sheet exist it finds range of cells with data and append it to dataframe. The thing I need to do now is to add header row (column names) to Dataframe, but in sheet those are multiline headers.

To make it look the same in dataframe i need to unmerge cells in top header row and copy value from first cell to rest of them in range which was merged before).

I'm using OpenPyXL for accessing excel sheets. My function receives sheet to work on as only parameter. It looks like this:

def checkForMergedCells(sheet):
    merged = ws.merged_cell_ranges
    for mergedCell in merged:
        mc_start, mc_stop = str(mergedCell).split(':')
        cp_value = sheet[mc_start]
        sheet.unmerge_cells(mergedCell)
        cell_range = sheet[mergedCell]
        for cell in cell_range:
            cell.value = cp_value

The thing is that cell_range returns a tuple which ends up in getting error message:

AttributeError: 'tuple' object has no attribute 'value'
  Below you can see screencap during debug which shows values passed in each variable.

Debugger running

Body:
I was getting errors and a deprecation warning until I did this:

from openpyxl.utils import range_boundaries

for group in sheet.merged_cells.ranges: # merged_cell_ranges deprecated
    display(range_boundaries(group._get_range_string())) # expects a string instead of an object
    min_col, min_row, max_col, max_row = range_boundaries(group._get_range_string())
    top_left_cell_value = sheet.cell(row=min_row, column=min_col).value
    for row in sheet.iter_rows(min_col=min_col, min_row=min_row, max_col=max_col, max_row=max_row):
        for cell in row:
            cell.value = top_left_cell_value


问:
Audio Streaming on Android
I need to create an audio streamer for Android. I want it to play MP3(and other formats too if possible). I also want to be able to progressive download the audio. Does anyone knows a good way to do that?

Thanks!

答:
You should start by checking this link: http://developer.android.com/guide/topics/media/index.html

Apparently this is already done for video, since you can specify a URL as the source for your stream.

You also will have to check some references about audio streaming and the size of the buffering you should use, as well as its dependency with the rate at which you're getting data from the stream in question.

Title: Audio Streaming on Android


问:
How to fix 'Unchecked cast from MyClass to T'
I have a method that works, but give me a warning, is there any solution to remove it, cleanly?

In this method I call the method :
<T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)

That return an object that extends SonarContainPaging.

I try to add an object that extends SonarContainPaging to my list, but I get a warning.

The SonarContainPaging object has a method canContinuePaging that takes a page integer and return a boolean.

The warning:

Type safety: Unchecked cast from SonarContainPaging to T

```<code>private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables,
        Class<T> klass, List<T> list) {
    int page = 1;
    SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
    page++;

    list.add((T)sonarObject); // Warning
    while (sonarObject.canContinueLooping(page)) {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        page++;

        list.add((T) sonarObject); // Warning
    }
}
</code>```

Any solution you can think of?

The solution given by @Sweeper is to change the type of sonarObject to T

The error I made, was assuming that a generic T object could not call method from its parent.

答:
You can use cast method.
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#cast-java.lang.Object-

list.add(klass.cast(sonarObject));

Body:
I have a method that works, but give me a warning, is there any solution to remove it, cleanly?

In this method I call the method :
<T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)

That return an object that extends SonarContainPaging.

I try to add an object that extends SonarContainPaging to my list, but I get a warning.

The SonarContainPaging object has a method canContinuePaging that takes a page integer and return a boolean.

The warning:

Type safety: Unchecked cast from SonarContainPaging to T

private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables,
        Class<T> klass, List<T> list) {
    int page = 1;
    SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
    page++;

    list.add((T)sonarObject); // Warning
    while (sonarObject.canContinueLooping(page)) {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        page++;

        list.add((T) sonarObject); // Warning
    }
}

Any solution you can think of?

The solution given by @Sweeper is to change the type of sonarObject to T

The error I made, was assuming that a generic T object could not call method from its parent.


问:
How to use Calligraphy with multi-language support Oreo
I'm developing an app that need to support multiple languages and if the language is RTL I have to apply a custom font. For the requirement I have created my Class that extends Application. Everything was perfect till I got Oreo version device (Before I have Marshmellow enabled device). In Oreo if we want to change the language we have to create a custom ContextWrapper class, here problem come in.

To use Calligraphy we need to Override the attachBaseContext
method. And

To change language we need to Override the attachBaseContext too

I tried to call super.attachBaseContext in the Overrided method twice One for the Calligraphy and Other for the Language code like below.

```<code>@Override
protected void attachBaseContext(Context newBase) {

    // create or get your new Locale object here.
    String lang = Preferences
            .getSharedPreferenceString(appContext, LANGUAGE_KEY, "ar");

    Context context = MyContextWrapper.wrap(newBase, lang);
    super.attachBaseContext(context);
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
</code>```

It give IllegalStateException as we can attach base context once.

If I use super.attachBaseContext(context); the language change works But Calligraphy does not.

If I use super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); Calligraphy works But Language change does not.

In such case how can I make all working (Calligraphy + Multi-language). I have viewed many posts/tutorials but I'm stuck in this for three days now.

Please help me complete this. Thanks

Edit: References

CalligraphyContextWrapper.java

ContextWrapper Class Accepted answer in link.

Looking for a solution to be able to use custom font with Calligraphy and Change Language Functionality. Alternatively provide a way so that I may be able to change Language and Apply Font to the whole app.

Note: The solution must be compatible with API 17 to the latest 27. I'm using AppCompat.

答:
```<code>@Override
protected void attachBaseContext(Context newBase) {
    ContextWrapper localeContextWrapper = LocaleManager.wrap(newBase, "en");
    ContextWrapper calligraphyContextWrapper = CalligraphyContextWrapper.wrap(localeContextWrapper);
    super.attachBaseContext(calligraphyContextWrapper);
}
</code>```

LocaleManager.java

```<code>public class LocaleManager {
    public static ContextWrapper wrap(Context context, String language) {
        Resources res = context.getResources();
        Configuration configuration = res.getConfiguration();
        Locale newLocale = new Locale(language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            configuration.setLocale(newLocale);
            LocaleList localeList = new LocaleList(newLocale);
            LocaleList.setDefault(localeList);
            configuration.setLocales(localeList);
            context = context.createConfigurationContext(configuration);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(newLocale);
            context = context.createConfigurationContext(configuration);

        } else {
            configuration.locale = newLocale;
            res.updateConfiguration(configuration, res.getDisplayMetrics());
        }

        return new ContextWrapper(context);
    }
}
</code>```

Body:
I'm developing an app that need to support multiple languages and if the language is RTL I have to apply a custom font. For the requirement I have created my Class that extends Application. Everything was perfect till I got Oreo version device (Before I have Marshmellow enabled device). In Oreo if we want to change the language we have to create a custom ContextWrapper class, here problem come in.

To use Calligraphy we need to Override the attachBaseContext
method. And

To change language we need to Override the attachBaseContext too

I tried to call super.attachBaseContext in the Overrided method twice One for the Calligraphy and Other for the Language code like below.

@Override
protected void attachBaseContext(Context newBase) {

    // create or get your new Locale object here.
    String lang = Preferences
            .getSharedPreferenceString(appContext, LANGUAGE_KEY, "ar");

    Context context = MyContextWrapper.wrap(newBase, lang);
    super.attachBaseContext(context);
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

It give IllegalStateException as we can attach base context once.

If I use super.attachBaseContext(context); the language change works But Calligraphy does not.

If I use super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); Calligraphy works But Language change does not.

In such case how can I make all working (Calligraphy + Multi-language). I have viewed many posts/tutorials but I'm stuck in this for three days now.

Please help me complete this. Thanks

Edit: References

CalligraphyContextWrapper.java

ContextWrapper Class Accepted answer in link.

Looking for a solution to be able to use custom font with Calligraphy and Change Language Functionality. Alternatively provide a way so that I may be able to change Language and Apply Font to the whole app.

Note: The solution must be compatible with API 17 to the latest 27. I'm using AppCompat.

Body:
@Override
protected void attachBaseContext(Context newBase) {
    ContextWrapper localeContextWrapper = LocaleManager.wrap(newBase, "en");
    ContextWrapper calligraphyContextWrapper = CalligraphyContextWrapper.wrap(localeContextWrapper);
    super.attachBaseContext(calligraphyContextWrapper);
}

LocaleManager.java

public class LocaleManager {
    public static ContextWrapper wrap(Context context, String language) {
        Resources res = context.getResources();
        Configuration configuration = res.getConfiguration();
        Locale newLocale = new Locale(language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            configuration.setLocale(newLocale);
            LocaleList localeList = new LocaleList(newLocale);
            LocaleList.setDefault(localeList);
            configuration.setLocales(localeList);
            context = context.createConfigurationContext(configuration);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(newLocale);
            context = context.createConfigurationContext(configuration);

        } else {
            configuration.locale = newLocale;
            res.updateConfiguration(configuration, res.getDisplayMetrics());
        }

        return new ContextWrapper(context);
    }
}


问:
Argument type 'SecretSpec' does not conform to expected type 'Sequence'
I want to encrypt a message on playground. my code is given below. i write another class to generate a secretkey. when convert the secret key into string, it gives error.

```<code>import UIKit

import Foundation
import CommonCrypto

class SecretSpec {
    var algorithm: String = "AES/ECB/PKCS5padding"
    var key = [UInt8]()

    func SecretSpec(key: [UInt8], algorithm: String){
        self.key = key
        self.algorithm = algorithm
    }

    func getAlgorithm() -> String {
        return self.algorithm
    }

    func getFormat() -> String {
        return "RAW"
    }

    func getEncoded() -> [UInt8] {
        return self.key
    }

    func hashCode() -> Int {
        var retval: Int = 0
        for i in 1...key.count-1 {
            retval = retval + Int(key[i]) * Int(i)
        }

        if (algorithm.lowercased() == "tripledes"){
            retval = retval ^ Int("desede".hashValue)
            return retval
        }else{
            retval = retval ^ Int(algorithm.lowercased().hashValue)
            return retval
        }
    }
}

extension String {

    func aesEncrypt(key: String, options:Int = (kCCOptionECBMode + kCCOptionPKCS7Padding)) -> String? {
        if let keyData = key.data(using: String.Encoding.utf8),
            let data = self.data(using: String.Encoding.utf8),
            let cryptData = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {

            let keyLength = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCEncrypt)
            let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options: CCOptions = UInt32(options)

            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation, algoritm, options,
                                      (keyData as NSData).bytes, keyLength,
                                      nil, (data as NSData).bytes, data.count,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)

                var bytes = [UInt8](repeating: 0, count: cryptData.length)
                cryptData.getBytes(&bytes, length: cryptData.length)

                var hexString = ""
                for byte in bytes {
                    hexString += String(format:"%02x", UInt8(byte))
                }

                return hexString
            }
            else {
                return nil
            }
        }
        return nil
    }
}

func MD5(_ string: String) -> String? {
    let length = Int(CC_MD5_DIGEST_LENGTH)
    var digest = [UInt8](repeating: 0, count: length)

    if let d = string.data(using: String.Encoding.utf8) {
        _ = d.withUnsafeBytes { (body: UnsafePointer<UInt8>) in
            CC_MD5(body, CC_LONG(d.count), &digest)
        }
    }

    return (0..<length).reduce("") {
        $0 + String(format: "%02x", digest[$1])
    }
}

var mdT = "YourStrongKeyasdfghjklzxcvbnm"
var algorithm: String = "AES/ECB/PKCS7padding"

var s = MD5(mdT)
let buf: [UInt8] = Array(s!.utf8)

var skcSpec = SecretSpec()
skcSpec.SecretSpec(key: buf, algorithm: algorithm)

print("hello: \(skcSpec)")

skcSpec.getEncoded()
skcSpec.getFormat()
skcSpec.getAlgorithm()
skcSpec.hashCode()

let msg: NSMutableDictionary = NSMutableDictionary()

msg.setValue("uttam kumar", forKey: "name")
msg.setValue("1001", forKey: "id")

let msgData: NSData
var msgStr: String = ""
var requestUrl: String = ""

do {
    msgData = try JSONSerialization.data(withJSONObject: msg, options: JSONSerialization.WritingOptions()) as NSData
    msgStr = NSString(data: msgData as Data, encoding: String.Encoding.utf8.rawValue)! as String

} catch _ {
    print ("JSON Failure")
}

var skc = String(data: Data(skcSpec), encoding: .utf8)!
var encoded = msgStr.aesEncrypt(key: String(skc))!

print("encoded: \(encoded)")
</code>```

I want to get String value of 'skc'. and print it. but it gives 'Argument type 'SecretSpec' does not conform to expected type 'Sequence'' error. please help me.

答:
Data does not have an initialiser for your custom type. Did you mean to get the encoded value?

```<code>var skc = String(data: Data(skcSpec.getEncoded()), encoding: .utf8)!
</code>```

Body:
I want to encrypt a message on playground. my code is given below. i write another class to generate a secretkey. when convert the secret key into string, it gives error.

import UIKit

import Foundation
import CommonCrypto

class SecretSpec {
    var algorithm: String = "AES/ECB/PKCS5padding"
    var key = [UInt8]()

    func SecretSpec(key: [UInt8], algorithm: String){
        self.key = key
        self.algorithm = algorithm
    }

    func getAlgorithm() -> String {
        return self.algorithm
    }

    func getFormat() -> String {
        return "RAW"
    }

    func getEncoded() -> [UInt8] {
        return self.key
    }

    func hashCode() -> Int {
        var retval: Int = 0
        for i in 1...key.count-1 {
            retval = retval + Int(key[i]) * Int(i)
        }

        if (algorithm.lowercased() == "tripledes"){
            retval = retval ^ Int("desede".hashValue)
            return retval
        }else{
            retval = retval ^ Int(algorithm.lowercased().hashValue)
            return retval
        }
    }
}

extension String {

    func aesEncrypt(key: String, options:Int = (kCCOptionECBMode + kCCOptionPKCS7Padding)) -> String? {
        if let keyData = key.data(using: String.Encoding.utf8),
            let data = self.data(using: String.Encoding.utf8),
            let cryptData = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {

            let keyLength = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCEncrypt)
            let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options: CCOptions = UInt32(options)

            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation, algoritm, options,
                                      (keyData as NSData).bytes, keyLength,
                                      nil, (data as NSData).bytes, data.count,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)

                var bytes = [UInt8](repeating: 0, count: cryptData.length)
                cryptData.getBytes(&bytes, length: cryptData.length)

                var hexString = ""
                for byte in bytes {
                    hexString += String(format:"%02x", UInt8(byte))
                }

                return hexString
            }
            else {
                return nil
            }
        }
        return nil
    }
}

func MD5(_ string: String) -> String? {
    let length = Int(CC_MD5_DIGEST_LENGTH)
    var digest = [UInt8](repeating: 0, count: length)

    if let d = string.data(using: String.Encoding.utf8) {
        _ = d.withUnsafeBytes { (body: UnsafePointer<UInt8>) in
            CC_MD5(body, CC_LONG(d.count), &digest)
        }
    }

    return (0..<length).reduce("") {
        $0 + String(format: "%02x", digest[$1])
    }
}

var mdT = "YourStrongKeyasdfghjklzxcvbnm"
var algorithm: String = "AES/ECB/PKCS7padding"

var s = MD5(mdT)
let buf: [UInt8] = Array(s!.utf8)

var skcSpec = SecretSpec()
skcSpec.SecretSpec(key: buf, algorithm: algorithm)

print("hello: \(skcSpec)")

skcSpec.getEncoded()
skcSpec.getFormat()
skcSpec.getAlgorithm()
skcSpec.hashCode()

let msg: NSMutableDictionary = NSMutableDictionary()

msg.setValue("uttam kumar", forKey: "name")
msg.setValue("1001", forKey: "id")

let msgData: NSData
var msgStr: String = ""
var requestUrl: String = ""

do {
    msgData = try JSONSerialization.data(withJSONObject: msg, options: JSONSerialization.WritingOptions()) as NSData
    msgStr = NSString(data: msgData as Data, encoding: String.Encoding.utf8.rawValue)! as String

} catch _ {
    print ("JSON Failure")
}

var skc = String(data: Data(skcSpec), encoding: .utf8)!
var encoded = msgStr.aesEncrypt(key: String(skc))!

print("encoded: \(encoded)")

I want to get String value of 'skc'. and print it. but it gives 'Argument type 'SecretSpec' does not conform to expected type 'Sequence'' error. please help me.

Body:
Data does not have an initialiser for your custom type. Did you mean to get the encoded value?

var skc = String(data: Data(skcSpec.getEncoded()), encoding: .utf8)!


问:
"No files matched the search pattern" in tfs build
I want to build my project from TFS Azure(VSTS).
I have made one project which is under Asp.Net Core.

I have made Build definition with Asp.Net Core Template and given the path for restore like **\*.csproj but I am not sure about this path or not?

I have tried many options like **\admis.csproj and some others, but I have faced the same error as the one on the following image:

I am using Asp.Net Core 2.1. Any ideas?

答:
Please check!

1) Server path should be: $/YourDevOpsProjectName/YourBranchName/TheRestPathUntil .csproj file

As I see on your screenshot, your path should be $/0424Test/NetCoreApp/NetCoreApp (I'm assuming that your .csproj file is there).

2) I had the same problem, because when I tried to Queue build for my project, in Source version I set 1 and the process of the queue tried to take 1 source code version, that of course not exists.

If Source version's value is empty, it try to get the last version of your source code

3) Use **/*.csproj as "Path to project(s)" for every task in your Agent job.


问:
SVG being overflow:hidden by bootstrap. Why?
I have an inline SVG on my webpage. I'm dynamically adjusting it's start and end coordinates with some Javascript like so https://codepen.io/anon/pen/rrYNaP?editors=1010.

However, in my webpage, I noticed that I can't see the svg due to:

```<code>svg:not(:root) {
    overflow: hidden;
}
</code>```

Looks like it's coming from bootstrap (I think normalize.css). I can override it

```<code>svg {
    overflow: visible;
}
</code>```

but then I get horizontal scroll bars and the svg is layered on top of every other div on the page (kinda needs to be in the background and z-index: -1 isn't working)

The weird thing is, when I view it in codepen, it doesn't have any of those issues.

What is going on and how can I fix this?

答:
try with</p>

```<code>svg {
    overflow: visible !important;
}
</code>```

Body:
I have an inline SVG on my webpage. I'm dynamically adjusting it's start and end coordinates with some Javascript like so https://codepen.io/anon/pen/rrYNaP?editors=1010.

However, in my webpage, I noticed that I can't see the svg due to:

svg:not(:root) {
    overflow: hidden;
}

Looks like it's coming from bootstrap (I think normalize.css). I can override it

svg {
    overflow: visible;
}

but then I get horizontal scroll bars and the svg is layered on top of every other div on the page (kinda needs to be in the background and z-index: -1 isn't working)

The weird thing is, when I view it in codepen, it doesn't have any of those issues.

What is going on and how can I fix this?

Body:
try with

svg {
    overflow: visible !important;
}


问:
Get null when generating JSONObject with String
I'm now trying this code with JUnit.

```<code>try {
    JSONObject jsonObject = new JSONObject("{\"name\":\"foo\",\"id\":\"2\"}");
    String name = jsonObject.getString("name");
    Log.d(TAG, "name = " + name);
} catch (JSONException e) {
    e.printStackTrace();
}
</code>```

I'm now testing put break point line at "Log.d...", but jsonObject always null.
What is my mistake? This code is no problem on actual device.

答:
Android JSON API is part of android its not part of Java API.
i.e they are not available to run on JVM they run on android environment.

If you want to use JSON API for unit testing you need to integrate below dependency in build.gradle file in android studio

```<code>testImplementation 'org.json:json:20140107'
</code>```

Body:
I'm now trying this code with JUnit.

try {
    JSONObject jsonObject = new JSONObject("{\"name\":\"foo\",\"id\":\"2\"}");
    String name = jsonObject.getString("name");
    Log.d(TAG, "name = " + name);
} catch (JSONException e) {
    e.printStackTrace();
}

I'm now testing put break point line at "Log.d...", but jsonObject always null.
What is my mistake? This code is no problem on actual device.

Body:
Android JSON API is part of android its not part of Java API.
i.e they are not available to run on JVM they run on android environment.

If you want to use JSON API for unit testing you need to integrate below dependency in build.gradle file in android studio

testImplementation 'org.json:json:20140107'