问:
Firebase & User Profile "Security"
I am currently tackling an issue within my code, which somewhat relates to security. Not in the sense of payment or personal information, but more so just the "ownership" of someones profile.

Currently, a users basic information (name, email, bio, etc) is stored on Firebase, and all information is displayed publicly on their profile.

However, to decide whether the current owner logged in using Firebase Auth is the owner of the profile they are currently on, I run a basic if function.

```<code>if(this.userInfo.user_slug == this.$route.params.id && this.user)
</code>```

then I set "can edit" to true. However, this feels... weak. Can someone just hop in, toggle that to true and get access to the ability to edit the profiles information, even if not the owner? And, if so what is the best/simplest way to make sure that the only person who can edit the profile is the one who is logged in and matchs it.

Thanks!

答:
Currently, a users basic information (name, email, bio, etc) is stored on Firebase, and all information is displayed publicly on their profile.

When using the Firebase Authentication client-side SDK, a user is only allowed to access and update their own profile information. Through these SDKs there is no way for them to read/write other user's information.

Title: Firebase & User Profile "Security"

Body:
I am currently tackling an issue within my code, which somewhat relates to security. Not in the sense of payment or personal information, but more so just the "ownership" of someones profile.

Currently, a users basic information (name, email, bio, etc) is stored on Firebase, and all information is displayed publicly on their profile.

However, to decide whether the current owner logged in using Firebase Auth is the owner of the profile they are currently on, I run a basic if function.

if(this.userInfo.user_slug == this.$route.params.id && this.user)

then I set "can edit" to true. However, this feels... weak. Can someone just hop in, toggle that to true and get access to the ability to edit the profiles information, even if not the owner? And, if so what is the best/simplest way to make sure that the only person who can edit the profile is the one who is logged in and matchs it.

Thanks!


来源: stackexchange

问:
Randomly select number (without repetition) for each group in R
I have the following dataframe containing a variable "group" and a variable "number of elements per group"

```<code>group    elements
1        3
2        1
3        14
4        10
..       ..
..       ..
30       5
</code>```

then I have a bunch of numbers going from 1 to (let's say) 30

when summing "elements" I would get 900. what I want to obtain is to randomly select a number (from 0 to 30) from 1-30 and assign it to each group until I fill the number of elements for that group. Each of those should appear 30 times in total.

thus, for group 1, I want to randomly select 3 number from 0 to 30
for group 2, 1 number from 0 to 30 etc. until I filled all of the groups.

the final table should look like this:

```<code>group     number(randomly selected)
1           7
1           20
1           7
2           4
3           21
3           20
...
</code>```

any suggestions on how I can achieve this?

答:
Yo have to generate a new dataframe repeating $group $element times, and then using sample you can generate the exact number of random numbers:

```<code>data<-data.frame(group=c(1,2,3,4,5),
                 elements=c(2,5,2,1,3))

data.elements<-data.frame(group=rep(data$group,data$elements),
                          number=sample(1:30,sum(data$elements)))
</code>```

The result:

```<code>group number
1      1      9
2      1      4
3      2     29
4      2     28
5      2     18
6      2      7
7      2     25
8      3     17
9      3     22
10     4      5
11     5      3
12     5      8
13     5     26
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following dataframe containing a variable "group" and a variable "number of elements per group"

group    elements
1        3
2        1
3        14
4        10
..       ..
..       ..
30       5

then I have a bunch of numbers going from 1 to (let's say) 30

when summing "elements" I would get 900. what I want to obtain is to randomly select a number (from 0 to 30) from 1-30 and assign it to each group until I fill the number of elements for that group. Each of those should appear 30 times in total.

thus, for group 1, I want to randomly select 3 number from 0 to 30
for group 2, 1 number from 0 to 30 etc. until I filled all of the groups.

the final table should look like this:

group     number(randomly selected)
1           7
1           20
1           7
2           4
3           21
3           20
...

any suggestions on how I can achieve this?

Body:
Yo have to generate a new dataframe repeating $group $element times, and then using sample you can generate the exact number of random numbers:

data<-data.frame(group=c(1,2,3,4,5),
                 elements=c(2,5,2,1,3))

data.elements<-data.frame(group=rep(data$group,data$elements),
                          number=sample(1:30,sum(data$elements)))

The result:

group number
1      1      9
2      1      4
3      2     29
4      2     28
5      2     18
6      2      7
7      2     25
8      3     17
9      3     22
10     4      5
11     5      3
12     5      8
13     5     26


问:
Return a value from python script to the a makefile variable
I have a requirement where I have to run a python script through a makefile. Python script performs some calculations and return a value. I want to get that value in that makefile variable. How I can do that?

I want something like this:

mymakefile.mke

```<code>$output = python process.py
</code>```

process.py

```<code>import os

def main():
    value = "01.00.00"
    return value
if __name__ == "__main__":
    main()
</code>```

答:
If you want the value in a Make variable, you can do this:

```<code>output := $(shell python process.py)
</code>```

(Note the use of := rather than =, because if you use =, Make will run the script every time it evaluates the variable.)

If you want the value in a shell variable within a recipe, look at the syntax you would use on the command line in your shell, which is probably something like:

```<code>output=$(python process.py); echo $output
</code>```

but in a makefile rule you must escape the dollar signs with more dollar signs:

```<code>some_target:
    output=$$(python process.py); echo $$output
</code>```

Note that since each line of a recipe executes in its own sub-shell, the assignment and use of the variable must be on the same line; it won't survive to the next line.

Body:
I have a requirement where I have to run a python script through a makefile. Python script performs some calculations and return a value. I want to get that value in that makefile variable. How I can do that?

I want something like this:

mymakefile.mke

$output = python process.py

process.py

import os

def main():
    value = "01.00.00"
    return value
if __name__ == "__main__":
    main()

Body:
If you want the value in a Make variable, you can do this:

output := $(shell python process.py)

(Note the use of := rather than =, because if you use =, Make will run the script every time it evaluates the variable.)

If you want the value in a shell variable within a recipe, look at the syntax you would use on the command line in your shell, which is probably something like:

output=$(python process.py); echo $output

but in a makefile rule you must escape the dollar signs with more dollar signs:

some_target:
    output=$$(python process.py); echo $$output

Note that since each line of a recipe executes in its own sub-shell, the assignment and use of the variable must be on the same line; it won't survive to the next line.


问:
Error adding/removing Outlook Distribution List users through .NET
I am a co-owner of several Outlook Distribution Lists (DL's).  I can edit them in Outlook, adding and removing members directly in there.  However, I cannot edit them through a simple .NET program:

```<code>using System;
using System.DirectoryServices.AccountManagement;

namespace DL_Remove_User
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                RemoveUser("My Distribution List", "jimtut");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
            }
        }

        private static void RemoveUser(string dl, string username)
        {
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "CORP"))
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, dl);
                bool result = group.Members.Remove(pc, IdentityType.SamAccountName, username);
                Console.WriteLine(result.ToString());
                group.Save();
            }
        }
    }
}
</code>```

This same code works on many other DL's, but for a couple, I get the message "Access is Denied".  Full stack trace:

```<code>at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.SetInfo()

at System.DirectoryServices.DirectoryEntry.CommitChanges()

at System.DirectoryServices.AccountManagement.ADStoreCtx.UpdateGroupMembership(Principal group, DirectoryEntry de, NetCred credentials, AuthenticationTypes authTypes)

at System.DirectoryServices.AccountManagement.SDSUtils.ApplyChangesToDirectory(Principal p, StoreCtx storeCtx, GroupMembershipUpdater updateGroupMembership, NetCred credentials, AuthenticationTypes authTypes)

at System.DirectoryServices.AccountManagement.ADStoreCtx.Update(Principal p)

at System.DirectoryServices.AccountManagement.Principal.Save()

at Department_Distribution_Lists.Program.RemoveUser(String dl, String username) in Program.cs:line 483
</code>```

Of course, "Access is denied" does indicate a permission problem, but I can edit these DL's directly in Outlook.  I can even query the DL "owners" in AD/LDAP, and I'm in the collection "msExchCoManagedByLink".

Any thoughts on why I can edit in Outlook but not through .NET?

答:
I finally figured this out.  I was confused by this permissions problem since I could edit the DL in Outlook, but not thru .NET.

I started looking for differences between the DL's that I could edit thru .NET and those that I could not, and found the difference was represented in the AD property shown in this GUI as "Manager can update membership list":

Even though I was the "manager" (list owner), if the DL didn't have that property set, I could ONLY edit in Outlook.

I didn't want to have to visually check all the DL's, so I wrote the following code to detect the "real" owners/editors of a DL:

```<code>    static List<string> GetGroupOwners(GroupPrincipal group)
    {
        List<string> owners = new List<string>();
        DirectoryEntry deGroup = group.GetUnderlyingObject() as DirectoryEntry;
        ActiveDirectorySecurity ads = deGroup.ObjectSecurity;
        AuthorizationRuleCollection rules = ads.GetAccessRules(true, true, typeof(SecurityIdentifier));
        Guid exRight_Member = new Guid("{bf9679c0-0de6-11d0-a285-00aa003049e2}");

        foreach (ActiveDirectoryAccessRule ar in rules)
        {
            if (ar.ActiveDirectoryRights.HasFlag(ActiveDirectoryRights.GenericWrite) || (ar.ObjectType.Equals(exRight_Member) && ar.ActiveDirectoryRights.HasFlag(ActiveDirectoryRights.WriteProperty)))
            {
                string friendlyName = "";
                try
                {
                    friendlyName = ar.IdentityReference.Translate(typeof(NTAccount)).Value;
                }
                catch
                {
                }
                owners.Add(friendlyName);
            }
        }
        return owners;
    }
</code>```

If you want to know who has Outlook-based edit access, that's different:

```<code>    static List<string> GetGroupOwnersOutlook(GroupPrincipal group)
    {
        List<string> owners = new List<string>();
        DirectoryEntry deGroup = group.GetUnderlyingObject() as DirectoryEntry;
        System.DirectoryServices.PropertyCollection r = deGroup.Properties;
        foreach (string a in r["managedBy"])
        {
            owners.Add(a);
        }
        foreach (string a in r["msExchCoManagedByLink"])
        {
            owners.Add(a);
        }

        return owners;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am a co-owner of several Outlook Distribution Lists (DL's).  I can edit them in Outlook, adding and removing members directly in there.  However, I cannot edit them through a simple .NET program:

using System;
using System.DirectoryServices.AccountManagement;

namespace DL_Remove_User
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                RemoveUser("My Distribution List", "jimtut");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
            }
        }

        private static void RemoveUser(string dl, string username)
        {
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "CORP"))
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, dl);
                bool result = group.Members.Remove(pc, IdentityType.SamAccountName, username);
                Console.WriteLine(result.ToString());
                group.Save();
            }
        }
    }
}

This same code works on many other DL's, but for a couple, I get the message "Access is Denied".  Full stack trace:

at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.SetInfo()

at System.DirectoryServices.DirectoryEntry.CommitChanges()

at System.DirectoryServices.AccountManagement.ADStoreCtx.UpdateGroupMembership(Principal group, DirectoryEntry de, NetCred credentials, AuthenticationTypes authTypes)

at System.DirectoryServices.AccountManagement.SDSUtils.ApplyChangesToDirectory(Principal p, StoreCtx storeCtx, GroupMembershipUpdater updateGroupMembership, NetCred credentials, AuthenticationTypes authTypes)

at System.DirectoryServices.AccountManagement.ADStoreCtx.Update(Principal p)

at System.DirectoryServices.AccountManagement.Principal.Save()

at Department_Distribution_Lists.Program.RemoveUser(String dl, String username) in Program.cs:line 483

Of course, "Access is denied" does indicate a permission problem, but I can edit these DL's directly in Outlook.  I can even query the DL "owners" in AD/LDAP, and I'm in the collection "msExchCoManagedByLink".

Any thoughts on why I can edit in Outlook but not through .NET?

Body:
I finally figured this out.  I was confused by this permissions problem since I could edit the DL in Outlook, but not thru .NET.

I started looking for differences between the DL's that I could edit thru .NET and those that I could not, and found the difference was represented in the AD property shown in this GUI as "Manager can update membership list":

Even though I was the "manager" (list owner), if the DL didn't have that property set, I could ONLY edit in Outlook.

I didn't want to have to visually check all the DL's, so I wrote the following code to detect the "real" owners/editors of a DL:

    static List<string> GetGroupOwners(GroupPrincipal group)
    {
        List<string> owners = new List<string>();
        DirectoryEntry deGroup = group.GetUnderlyingObject() as DirectoryEntry;
        ActiveDirectorySecurity ads = deGroup.ObjectSecurity;
        AuthorizationRuleCollection rules = ads.GetAccessRules(true, true, typeof(SecurityIdentifier));
        Guid exRight_Member = new Guid("{bf9679c0-0de6-11d0-a285-00aa003049e2}");

        foreach (ActiveDirectoryAccessRule ar in rules)
        {
            if (ar.ActiveDirectoryRights.HasFlag(ActiveDirectoryRights.GenericWrite) || (ar.ObjectType.Equals(exRight_Member) && ar.ActiveDirectoryRights.HasFlag(ActiveDirectoryRights.WriteProperty)))
            {
                string friendlyName = "";
                try
                {
                    friendlyName = ar.IdentityReference.Translate(typeof(NTAccount)).Value;
                }
                catch
                {
                }
                owners.Add(friendlyName);
            }
        }
        return owners;
    }

If you want to know who has Outlook-based edit access, that's different:

    static List<string> GetGroupOwnersOutlook(GroupPrincipal group)
    {
        List<string> owners = new List<string>();
        DirectoryEntry deGroup = group.GetUnderlyingObject() as DirectoryEntry;
        System.DirectoryServices.PropertyCollection r = deGroup.Properties;
        foreach (string a in r["managedBy"])
        {
            owners.Add(a);
        }
        foreach (string a in r["msExchCoManagedByLink"])
        {
            owners.Add(a);
        }

        return owners;
    }


问:
Desperately seeking the answer to my pointer problem
I have been working on a college C assignment, and have been trying to make sense of a bug I seem to be having with my code. Basically, it seems like something is wrong with my pointers (and or memory allocation).

This assignment is primarily about linked lists, so the structs contain pointers to the next element in the list. Obviously, to traverse the list until I find that the current element has a NULL pointer to the next element (and then I change that to be the pointer to the 'new' element I want to add.

The problem I have though, is for some reason my code seems to be completely screwing with my memory pointers, because they're getting garbled somehow.  They seem fine for moment but very soon go rubbish.

Here is what my watches in XCode's debugger are showing me:

The first circle shows me the values as the first element in the list, which as far as I can tell are initially set correctly, and should be "C0001\0". The second circle shows the current->nextCategory pointer which should be NULL (0x0) but instead show that weird memory address (look at the size of it!). I assume that these problems are related, but as I am new to C, I don't know how or why.

In either case, when I check current->nextCategory != NULL in my while statement, it throws EXC_BAD_ACCESS:

I've spent the past few hours pulling my hair out becasue I cannot work out what the heck is happening to my program.  Am I doing something wrong with my pointers, or using malloc() improperly?

Here is the relevant part of my program:

```<code>/****************************************************************************
* Initialises the system to a safe empty state.
****************************************************************************/
void systemInit(GJCType* menu)
{
   if (menu == NULL) {
      fprintf(stderr, "can't initialize system with a null menu pointer.\n");
      exit(EXIT_FAILURE);
   }
   menu->headCategory = NULL;
   menu->numCategories = 0;
}

/****************************************************************************
* Loads all data into the system.
****************************************************************************/
int loadData(GJCType* menu, char* menuFile, char* submenuFile)
{
   FILE *fp;
   size_t len;
   char *line;
   char *buffer;
   CategoryTypePtr category_p;
   ItemTypePtr item_p;
   char *catId;

   if (menu == NULL)
      return FALSE;

   fp = fopen(menuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", menuFile);
      return FALSE;
    }

   buffer = malloc(MAX_BUFFER_SIZE);
   len = MAX_BUFFER_SIZE;
   catId = malloc(ID_LEN + 1);

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      category_p = malloc(sizeof(CategoryTypePtr));

      if (!tokenizeCategory(line, category_p)) {
         fprintf(stderr, "can't tokenize category:> %s\n", line);
         free(category_p);
         category_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      pushCategory(menu, category_p);
      free(category_p);
      category_p = NULL;
   }

   fp = fopen(submenuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", submenuFile);
      return FALSE;
    }

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      item_p = malloc(sizeof(ItemTypePtr));

      if (!tokenizeItem(line, item_p, catId)) {
         fprintf(stderr, "can't tokenize item:> %s\n", line);
         free(item_p);
         item_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      category_p = findCategory(menu, catId);
      pushItem(category_p, item_p);
      free(item_p);
      item_p = NULL;
   }

   free(buffer);
   free(catId);
   return TRUE;
}

void pushItem(CategoryTypePtr category, ItemTypePtr item)
{
   ItemTypePtr current;
   ItemTypePtr new;

   if ((new = malloc(sizeof(ItemTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new item pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *item;

   if (category->headItem == NULL) {
      category->headItem = new;
   } else {
      current = category->headItem;
      while (current->nextItem != NULL) {
         current = current->nextItem;
      }
      current->nextItem = new;

   }
   category->numItems++;
}

void pushCategory(GJCType* menu, CategoryTypePtr category)
{
   CategoryTypePtr current;
   CategoryTypePtr new;

   if ((new = malloc(sizeof(CategoryTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new category pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *category;

   if (menu->headCategory == NULL) {
      menu->headCategory = new;
   } else {
      current = menu->headCategory;
      while (current->nextCategory != NULL) {
         current = current->nextCategory;
      }
      current->nextCategory = new;
   }
   menu->numCategories++;
}

CategoryTypePtr findCategory(GJCType* menu, char* id)
{
   CategoryTypePtr current;

   current = menu->headCategory;
   while (current != NULL) {
      if (!strcmp(current->categoryID, id))
         return current;
      current = current->nextCategory;
   }
   return NULL;
}

/* This function takes the character delimited string and converts it into
 * a category structure at the location of the category pointer supplied.
 */
int tokenizeCategory(char *data, CategoryTypePtr category)
{
   char* buffer;

   if (category == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(category->categoryID, strtok(buffer, "|\n"));
   category->drinkType = *(strtok(NULL, "|\n"));
   strcpy(category->categoryName, strtok(NULL, "|\n"));
   strcpy(category->categoryDescription, strtok(NULL, "|\n"));
   category->numItems = 0;
   category->nextCategory = NULL;
   category->headItem = NULL;
   free(buffer);
   return TRUE;
}

/* This function takes the character delimited string and converts it into
 * an item structure at the location of the item pointer supplied.
 */
int tokenizeItem(char *data, ItemTypePtr item, char* categoryId)
{
   char* buffer;
   int i;

   if (item == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(item->itemID, strtok(buffer, "|\n"));
   strcpy(categoryId, strtok(NULL, "|\n"));
   strcat(categoryId, "\0");
   strcpy(item->itemName, strtok(NULL, "|\n"));
   for (i = 0; i < NUM_PRICES; i++)
      sscanf(strtok(NULL, "|\n"),"%d.%d",&(item->prices[i].dollars),&(item->prices[i].cents));
   strcpy(item->itemDescription, strtok(NULL, "|\n"));
   item->nextItem = NULL;
   free(buffer);
   return TRUE;
}
</code>```

Header definitions:

```<code>/* System-wide constants. */
#define ID_LEN 5
#define MIN_NAME_LEN 1
#define MAX_NAME_LEN 25
#define MIN_DESC_LEN 1
#define MAX_DESC_LEN 250
#define NUM_PRICES 3
#define HOT 'H'
#define COLD 'C'
#define FALSE 0
#define TRUE 1
#define MAX_BUFFER_SIZE 1024

typedef struct category* CategoryTypePtr;
typedef struct item* ItemTypePtr;

/* Structure definitions. */
typedef struct price
{
   unsigned dollars;
   unsigned cents;
} PriceType;

typedef struct item
{
   char itemID[ID_LEN + 1];
   char itemName[MAX_NAME_LEN + 1];
   PriceType prices[NUM_PRICES];
   char itemDescription[MAX_DESC_LEN + 1];
   ItemTypePtr nextItem;
} ItemType;

typedef struct category
{
   char categoryID[ID_LEN + 1];
   char categoryName[MAX_NAME_LEN + 1];
   char drinkType;      /* (H)ot or (C)old. */
   char categoryDescription[MAX_DESC_LEN + 1];
   CategoryTypePtr nextCategory;
   ItemTypePtr headItem;
   unsigned numItems;
} CategoryType;

typedef struct gjc
{
   CategoryTypePtr headCategory;
   unsigned numCategories;
} GJCType;
</code>```

答: To debug this kind of issues, I can only suggest to use valgrind : it will provide you very valuable help on buffer overflow, out of bound writing, memory loss. It's installed in the developper package.</p>

Body:
I have been working on a college C assignment, and have been trying to make sense of a bug I seem to be having with my code. Basically, it seems like something is wrong with my pointers (and or memory allocation).

This assignment is primarily about linked lists, so the structs contain pointers to the next element in the list. Obviously, to traverse the list until I find that the current element has a NULL pointer to the next element (and then I change that to be the pointer to the 'new' element I want to add.

The problem I have though, is for some reason my code seems to be completely screwing with my memory pointers, because they're getting garbled somehow.  They seem fine for moment but very soon go rubbish.

Here is what my watches in XCode's debugger are showing me:

The first circle shows me the values as the first element in the list, which as far as I can tell are initially set correctly, and should be "C0001\0". The second circle shows the current->nextCategory pointer which should be NULL (0x0) but instead show that weird memory address (look at the size of it!). I assume that these problems are related, but as I am new to C, I don't know how or why.

In either case, when I check current->nextCategory != NULL in my while statement, it throws EXC_BAD_ACCESS:

I've spent the past few hours pulling my hair out becasue I cannot work out what the heck is happening to my program.  Am I doing something wrong with my pointers, or using malloc() improperly?

Here is the relevant part of my program:

/****************************************************************************
* Initialises the system to a safe empty state.
****************************************************************************/
void systemInit(GJCType* menu)
{
   if (menu == NULL) {
      fprintf(stderr, "can't initialize system with a null menu pointer.\n");
      exit(EXIT_FAILURE);
   }
   menu->headCategory = NULL;
   menu->numCategories = 0;
}

/****************************************************************************
* Loads all data into the system.
****************************************************************************/
int loadData(GJCType* menu, char* menuFile, char* submenuFile)
{
   FILE *fp;
   size_t len;
   char *line;
   char *buffer;
   CategoryTypePtr category_p;
   ItemTypePtr item_p;
   char *catId;

   if (menu == NULL)
      return FALSE;

   fp = fopen(menuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", menuFile);
      return FALSE;
    }

   buffer = malloc(MAX_BUFFER_SIZE);
   len = MAX_BUFFER_SIZE;
   catId = malloc(ID_LEN + 1);

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      category_p = malloc(sizeof(CategoryTypePtr));

      if (!tokenizeCategory(line, category_p)) {
         fprintf(stderr, "can't tokenize category:> %s\n", line);
         free(category_p);
         category_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      pushCategory(menu, category_p);
      free(category_p);
      category_p = NULL;
   }

   fp = fopen(submenuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", submenuFile);
      return FALSE;
    }

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      item_p = malloc(sizeof(ItemTypePtr));

      if (!tokenizeItem(line, item_p, catId)) {
         fprintf(stderr, "can't tokenize item:> %s\n", line);
         free(item_p);
         item_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      category_p = findCategory(menu, catId);
      pushItem(category_p, item_p);
      free(item_p);
      item_p = NULL;
   }

   free(buffer);
   free(catId);
   return TRUE;
}

void pushItem(CategoryTypePtr category, ItemTypePtr item)
{
   ItemTypePtr current;
   ItemTypePtr new;

   if ((new = malloc(sizeof(ItemTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new item pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *item;

   if (category->headItem == NULL) {
      category->headItem = new;
   } else {
      current = category->headItem;
      while (current->nextItem != NULL) {
         current = current->nextItem;
      }
      current->nextItem = new;

   }
   category->numItems++;
}

void pushCategory(GJCType* menu, CategoryTypePtr category)
{
   CategoryTypePtr current;
   CategoryTypePtr new;

   if ((new = malloc(sizeof(CategoryTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new category pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *category;

   if (menu->headCategory == NULL) {
      menu->headCategory = new;
   } else {
      current = menu->headCategory;
      while (current->nextCategory != NULL) {
         current = current->nextCategory;
      }
      current->nextCategory = new;
   }
   menu->numCategories++;
}

CategoryTypePtr findCategory(GJCType* menu, char* id)
{
   CategoryTypePtr current;

   current = menu->headCategory;
   while (current != NULL) {
      if (!strcmp(current->categoryID, id))
         return current;
      current = current->nextCategory;
   }
   return NULL;
}

/* This function takes the character delimited string and converts it into
 * a category structure at the location of the category pointer supplied.
 */
int tokenizeCategory(char *data, CategoryTypePtr category)
{
   char* buffer;

   if (category == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(category->categoryID, strtok(buffer, "|\n"));
   category->drinkType = *(strtok(NULL, "|\n"));
   strcpy(category->categoryName, strtok(NULL, "|\n"));
   strcpy(category->categoryDescription, strtok(NULL, "|\n"));
   category->numItems = 0;
   category->nextCategory = NULL;
   category->headItem = NULL;
   free(buffer);
   return TRUE;
}

/* This function takes the character delimited string and converts it into
 * an item structure at the location of the item pointer supplied.
 */
int tokenizeItem(char *data, ItemTypePtr item, char* categoryId)
{
   char* buffer;
   int i;

   if (item == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(item->itemID, strtok(buffer, "|\n"));
   strcpy(categoryId, strtok(NULL, "|\n"));
   strcat(categoryId, "\0");
   strcpy(item->itemName, strtok(NULL, "|\n"));
   for (i = 0; i < NUM_PRICES; i++)
      sscanf(strtok(NULL, "|\n"),"%d.%d",&(item->prices[i].dollars),&(item->prices[i].cents));
   strcpy(item->itemDescription, strtok(NULL, "|\n"));
   item->nextItem = NULL;
   free(buffer);
   return TRUE;
}

Header definitions:

/* System-wide constants. */
#define ID_LEN 5
#define MIN_NAME_LEN 1
#define MAX_NAME_LEN 25
#define MIN_DESC_LEN 1
#define MAX_DESC_LEN 250
#define NUM_PRICES 3
#define HOT 'H'
#define COLD 'C'
#define FALSE 0
#define TRUE 1
#define MAX_BUFFER_SIZE 1024

typedef struct category* CategoryTypePtr;
typedef struct item* ItemTypePtr;

/* Structure definitions. */
typedef struct price
{
   unsigned dollars;
   unsigned cents;
} PriceType;

typedef struct item
{
   char itemID[ID_LEN + 1];
   char itemName[MAX_NAME_LEN + 1];
   PriceType prices[NUM_PRICES];
   char itemDescription[MAX_DESC_LEN + 1];
   ItemTypePtr nextItem;
} ItemType;

typedef struct category
{
   char categoryID[ID_LEN + 1];
   char categoryName[MAX_NAME_LEN + 1];
   char drinkType;      /* (H)ot or (C)old. */
   char categoryDescription[MAX_DESC_LEN + 1];
   CategoryTypePtr nextCategory;
   ItemTypePtr headItem;
   unsigned numItems;
} CategoryType;

typedef struct gjc
{
   CategoryTypePtr headCategory;
   unsigned numCategories;
} GJCType;


问:
Order of traversal given by std::filesystem directory_iterator
When iterating through a directory using std::filesystem::directory_iterator, are there any guarantees regarding the order of traversal?

答:
The order is unspecified per [fs.class.directory.iterator]/8

The order of directory entries obtained by dereferencing successive increments of a directory_iterator is unspecified.


问:
Spring Boot Admin - Basic Auth
I'm setting up basic auth in my sb-admin and client, but the client can't register (401 unauthorized). Everything works without auth.

SB-Admin configuration:

application.properties

```<code>    server.port=8080

    spring.application.name=SB Admin
    spring.boot.admin.ui.title=SB Admin

    spring.security.user.name=admin
    spring.security.user.password=admin
</code>```

build.gradle

```<code>    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'de.codecentric:spring-boot-admin-starter-server'
</code>```

Client configuration:

application.properties

```<code>    server.port=9000
    management.endpoints.web.exposure.include=*
    management.security.enabled=false

    spring.boot.admin.client.enabled=true
    spring.boot.admin.client.url=http://localhost:8080
    spring.boot.admin.client.username=admin
    spring.boot.admin.client.password=admin
</code>```

build.gradle

```<code>    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'de.codecentric:spring-boot-admin-starter-client'
</code>```

Security Config

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final String adminContextPath;
    private final AdminServerProperties adminServer;

    public SecurityConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
        this.adminServer = adminServerProperties;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(this.adminServer.path("/"));

        http.authorizeRequests((authorizeRequests) -> authorizeRequests.antMatchers(this.adminServer.path("/assets/**"))
                .permitAll().antMatchers(this.adminServer.path("/login")).permitAll().anyRequest().authenticated())
                .formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login"))
                        .successHandler(successHandler).and())
                .logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")))
                .httpBasic(Customizer.withDefaults())
                .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                        .ignoringRequestMatchers(
                                new AntPathRequestMatcher(this.adminServer.path("/instances"),
                                        HttpMethod.POST.toString()),
                                new AntPathRequestMatcher(this.adminServer.path("/instances/*"),
                                        HttpMethod.DELETE.toString()),
                                new AntPathRequestMatcher(this.adminServer.path("/actuator/**"))))
                .rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");
    }

}
</code>```

Does anybody can help me please?

答:
It's not enough just to add the spring security starter. You have to add a configuration class annotated with @EnableWebSecurity. Typically it'd be something like the following class, where you could configure things that are related to security of your app.

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/css/**", "/index").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}
</code>```

Title: Spring Boot Admin - Basic Auth

Body:
I'm setting up basic auth in my sb-admin and client, but the client can't register (401 unauthorized). Everything works without auth.

SB-Admin configuration:

application.properties

    server.port=8080

    spring.application.name=SB Admin
    spring.boot.admin.ui.title=SB Admin

    spring.security.user.name=admin
    spring.security.user.password=admin

build.gradle

    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'de.codecentric:spring-boot-admin-starter-server'

Client configuration:

application.properties

    server.port=9000
    management.endpoints.web.exposure.include=*
    management.security.enabled=false

    spring.boot.admin.client.enabled=true
    spring.boot.admin.client.url=http://localhost:8080
    spring.boot.admin.client.username=admin
    spring.boot.admin.client.password=admin

build.gradle

    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'de.codecentric:spring-boot-admin-starter-client'

Security Config

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final String adminContextPath;
    private final AdminServerProperties adminServer;

    public SecurityConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
        this.adminServer = adminServerProperties;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(this.adminServer.path("/"));

        http.authorizeRequests((authorizeRequests) -> authorizeRequests.antMatchers(this.adminServer.path("/assets/**"))
                .permitAll().antMatchers(this.adminServer.path("/login")).permitAll().anyRequest().authenticated())
                .formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login"))
                        .successHandler(successHandler).and())
                .logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")))
                .httpBasic(Customizer.withDefaults())
                .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                        .ignoringRequestMatchers(
                                new AntPathRequestMatcher(this.adminServer.path("/instances"),
                                        HttpMethod.POST.toString()),
                                new AntPathRequestMatcher(this.adminServer.path("/instances/*"),
                                        HttpMethod.DELETE.toString()),
                                new AntPathRequestMatcher(this.adminServer.path("/actuator/**"))))
                .rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");
    }

}

Does anybody can help me please?

Body:
It's not enough just to add the spring security starter. You have to add a configuration class annotated with @EnableWebSecurity. Typically it'd be something like the following class, where you could configure things that are related to security of your app.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/css/**", "/index").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}


问:
SQL Select row between two conditional rows
```<code>id  vehicle   speed
1   ABC-12     1.2
2   ABC-34     7.3
3   ABC-56     6.3
4   ABC-78     0
5   ABC-90     5.1
6   ABC-91     0
7   ABC-92     5.1
8   ABC-93     0
9   ABC-94     0
</code>```

I have a table with structure like this, I want to select all vehicles whose speed = 0 but vehicle before that && after that must have speed > 0

Like in this above example answer should be

```<code>id  vehicle   speed
4   ABC-78     0
6   ABC-91     0
</code>```

I am not sure it's possible or not

答:
As a note, you can do this with just one window function:</p>

```<code>select t.*
from (select t.*,
             sum(case when speed > 0 then 1 else 0 end) over
                 (order by id
                  rows between 1 preceding and 1 following
                 )
                ) as cnt
      from t
     ) t
where speed = 0 and cnt = 2;
</code>```

Body:
id  vehicle   speed
1   ABC-12     1.2
2   ABC-34     7.3
3   ABC-56     6.3
4   ABC-78     0
5   ABC-90     5.1
6   ABC-91     0
7   ABC-92     5.1
8   ABC-93     0
9   ABC-94     0

I have a table with structure like this, I want to select all vehicles whose speed = 0 but vehicle before that && after that must have speed > 0

Like in this above example answer should be

id  vehicle   speed
4   ABC-78     0
6   ABC-91     0

I am not sure it's possible or not

Body:
As a note, you can do this with just one window function:

select t.*
from (select t.*,
             sum(case when speed > 0 then 1 else 0 end) over
                 (order by id
                  rows between 1 preceding and 1 following
                 )
                ) as cnt
      from t
     ) t
where speed = 0 and cnt = 2;


问:
Setup crafter cms studio for access via apache web server proxy and ajp connector
I need to setup crafter cms studio within the authoring part to be able to access from remote host (e.g. VPS). I'm using Tomcat ajp connector via Apache web server proxy.
I've tried do it like adding the virtual host:

<VirtualHost *:80>
    ServerName studio

 DocumentRoot /home/web-apps/crafter/bin/apache-tomcat/webapps/studio

    RewriteEngine On
    ProxyPreserveHost On

    # Send requests to Engine's Tomcat
    ProxyPass / ajp://localhost:8009/
    ProxyPassReverse / ajp://localhost:8009/

    # This is where errors related to this virtual host are stored
    ErrorLog logs/mysite-error.log
    # This is where access logs are stored
    CustomLog logs/mysite-access.log combined
  </VirtualHost>```

But not really succeeded. I can see only the default page which always tells me: "Crafter CMS has no site configured for this domain. Please configure the site you want to show or select a site on the authoring environment." when I'm requesting it like http://my_remote_host_ip/studio

Anyone has ever challended problem like this?

答:
What you have looks right. Perhaps you can try:

clearing your cookies for my_remote_host_ip

clearing your browser cache

removing DocumentRoot directive (not really needed in this particular case)

This works for me:

```<code><VirtualHost *:80>
    ServerName myserver

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

    ErrorLog ${APACHE_LOG_DIR}/authoring-error.log
    CustomLog ${APACHE_LOG_DIR}/authoring-access.log combined

</VirtualHost>
<VirtualHost *:443>
    ServerName myserver

        SSLEngine On
        SSLCertificateFile /etc/apache2/ssl/my.crt
        SSLCertificateKeyFile /etc/apache2/ssl/my.key
        SSLCertificateChainFile /etc/apache2/ssl/their.crt

    ProxyPreserveHost On

    # Studio
        ProxyPass / ajp://localhost:8009/
        ProxyPassReverse / ajp://localhost:8009/

    ErrorLog ${APACHE_LOG_DIR}/authoring-error.log
    CustomLog ${APACHE_LOG_DIR}/authoring-access.log combined

</VirtualHost>
</code>```

Another approach is to try the community edition on AWS and see if that works with your browser. Then you can look at how that's configured and copy the config: https://aws.amazon.com/marketplace/pp/B08374YPTP?qid=1581949339014&sr=0-2&ref_=srh_res_product_title

Body:
I need to setup crafter cms studio within the authoring part to be able to access from remote host (e.g. VPS). I'm using Tomcat ajp connector via Apache web server proxy.
I've tried do it like adding the virtual host:

<VirtualHost *:80>
    ServerName studio

 DocumentRoot /home/web-apps/crafter/bin/apache-tomcat/webapps/studio

    RewriteEngine On
    ProxyPreserveHost On

    # Send requests to Engine's Tomcat
    ProxyPass / ajp://localhost:8009/
    ProxyPassReverse / ajp://localhost:8009/

    # This is where errors related to this virtual host are stored
    ErrorLog logs/mysite-error.log
    # This is where access logs are stored
    CustomLog logs/mysite-access.log combined
  </VirtualHost>

But not really succeeded. I can see only the default page which always tells me: "Crafter CMS has no site configured for this domain. Please configure the site you want to show or select a site on the authoring environment." when I'm requesting it like http://my_remote_host_ip/studio

Anyone has ever challended problem like this?

Body:
What you have looks right. Perhaps you can try:

clearing your cookies for my_remote_host_ip

clearing your browser cache

removing DocumentRoot directive (not really needed in this particular case)

This works for me:

<VirtualHost *:80>
    ServerName myserver

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

    ErrorLog ${APACHE_LOG_DIR}/authoring-error.log
    CustomLog ${APACHE_LOG_DIR}/authoring-access.log combined

</VirtualHost>
<VirtualHost *:443>
    ServerName myserver

        SSLEngine On
        SSLCertificateFile /etc/apache2/ssl/my.crt
        SSLCertificateKeyFile /etc/apache2/ssl/my.key
        SSLCertificateChainFile /etc/apache2/ssl/their.crt

    ProxyPreserveHost On

    # Studio
        ProxyPass / ajp://localhost:8009/
        ProxyPassReverse / ajp://localhost:8009/

    ErrorLog ${APACHE_LOG_DIR}/authoring-error.log
    CustomLog ${APACHE_LOG_DIR}/authoring-access.log combined

</VirtualHost>

Another approach is to try the community edition on AWS and see if that works with your browser. Then you can look at how that's configured and copy the config: https://aws.amazon.com/marketplace/pp/B08374YPTP?qid=1581949339014&sr=0-2&ref_=srh_res_product_title


问:
Delete an entire string from mySql table containing random characters
I'm trying to delete stings from a DB table that contain random characters ...

The string looks like this:

```<code><h1 class="visible-xs">Chocolates</h1>
</code>```

e.g.

```<code><h1 class="visible-xs">UNKNOWN</h1>
</code>```

There are thousands of entries like this but the word 'Chocolate' is different in each case.

So basically I want to delete this string from the table field ...

e.g.

```<code>UPDATE products SET products = REPLACE ( post_content, '**********', '' );
</code>```

where the asterisks donate the string to be deleted.

Please help, I've searched everywhere but I'm a complete noob to this regex stuf!

答:
I you are running MySQL 8.0, you can use regexp_replace():

```<code>update posts
set products = regexp_replace(
    post_content,
    '<h1 class="visible-xs">[^<]+</h1>',
    '<h1 class="visible-xs"></h1>'
)
</code>```

This assumes that the string to remove does not contain character '<'.

Body:
I'm trying to delete stings from a DB table that contain random characters ...

The string looks like this:

Chocolates

e.g.

UNKNOWN

There are thousands of entries like this but the word 'Chocolate' is different in each case.

So basically I want to delete this string from the table field ...

e.g.

UPDATE products SET products = REPLACE ( post_content, '**********', '' );

where the asterisks donate the string to be deleted.

Please help, I've searched everywhere but I'm a complete noob to this regex stuf!

Body:
I you are running MySQL 8.0, you can use regexp_replace():

update posts
set products = regexp_replace(
    post_content,
    '<h1 class="visible-xs">[^<]+</h1>',
    '<h1 class="visible-xs"></h1>'
)

This assumes that the string to remove does not contain character '<'.


问:
C# Assembly Injection Check
I'm creating an assembly in C# for MS SQL 2005. This assembly creates a stored procedure and runs a dynamic query based on parameters passed into the stored procedure.

Is there a simple function in C# to prevent SQL injection?

For example

```<code>string myQuery = "SELECT * FROM dbo.MyTable WHERE lastName = '" + injectionCheck(arg1) + "'";
</code>```

This question was answered for the standard query... but in situations where there is no way around building a truely dynamic query what can I use in C# for injection checking?

For example, these probably wont work:

using @dbName;

SELECT * FROM @table

OPEN SYMMETRIC KEY @keyName

etc

答:
Use parameters ....

(This has been posted often already)

```<code>string myQuery = "SELECT * FROM myTable WHERE lastname = @p_name";

SqlCommand cmd = new SqlCommand();
cmd.CommandText = myQuery;
cmd.Parameters.Add ("@p_name", SqlDbType.Varchar).Value = "melp";
</code>```

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Title: C# Assembly Injection Check

Body:
I'm creating an assembly in C# for MS SQL 2005. This assembly creates a stored procedure and runs a dynamic query based on parameters passed into the stored procedure.

Is there a simple function in C# to prevent SQL injection?

For example

string myQuery = "SELECT * FROM dbo.MyTable WHERE lastName = '" + injectionCheck(arg1) + "'";

This question was answered for the standard query... but in situations where there is no way around building a truely dynamic query what can I use in C# for injection checking?

For example, these probably wont work:

using @dbName;

SELECT * FROM @table

OPEN SYMMETRIC KEY @keyName

etc

LastEditorDisplayName: Cade Roux

Body:
Use parameters ....

(This has been posted often already)

string myQuery = "SELECT * FROM myTable WHERE lastname = @p_name";

SqlCommand cmd = new SqlCommand();
cmd.CommandText = myQuery;
cmd.Parameters.Add ("@p_name", SqlDbType.Varchar).Value = "melp";

OwnerDisplayName: Frederik Gheysels


问:
Rhodes : Error!!! Wrong Android API version
I just did un-installation of instant_rhodes-2.4.1.exe and install instant_rhodes-3.0.0.exe to Windows 7

Now when I

```<code>rhodes app HelloWorld
cd HelloWorld
rake run:android
</code>```

it show me Error!!! Wrong Android API version

how do I correct this problem?

答:
refer to http://groups.google.com/group/rhomobile/browse_thread/thread/da61c4036cb7435b#

"For the moment rhodes do not support Android 3.1 SDK (r12). Please download Android 3.0 SDK."

Body:
I just did un-installation of instant_rhodes-2.4.1.exe and install instant_rhodes-3.0.0.exe to Windows 7

Now when I

rhodes app HelloWorld
cd HelloWorld
rake run:android

it show me Error!!! Wrong Android API version

how do I correct this problem?


问:
Javascript function syntax with tripple =>
Below is a code snippet which I came across in one of the blog for redux.

This snippet explains redux-thunk. But I am trying to make sense out of the weird syntax

return ({dispatch, getState}) => next => action =>{}

I tried a google search with this syntax but did not get much help. I am not understanding how next and action objects are getting their values. Can someone please help me understand what's going on here?

答:
Chaining of functions in this way is usually to enable a user to bind arguments to a final function in a controlled fashion, rather than having to supply them all in one go.

In effect it is an API design choice for a piece of functionality.

```<code>({dispatch, getState}) => next => action => {}
</code>```

...is equivalent to:

```<code>function({dispatch, getState}) { // destructure two properties into arguments
    return function(next) {
        return function(action) {
            // this function has access to `dispatch`, `getState`, `next` & `action`
        }
    }
}
</code>```

Note that the "binding" of the arguments to the inner functions occurs through a feature of JavaScript called closures. Full explanation of closures in JavaScript here.

Body:
Chaining of functions in this way is usually to enable a user to bind arguments to a final function in a controlled fashion, rather than having to supply them all in one go.

In effect it is an API design choice for a piece of functionality.

({dispatch, getState}) => next => action => {}

...is equivalent to:

function({dispatch, getState}) { // destructure two properties into arguments
    return function(next) {
        return function(action) {
            // this function has access to `dispatch`, `getState`, `next` & `action`
        }
    }
}

Note that the "binding" of the arguments to the inner functions occurs through a feature of JavaScript called closures. Full explanation of closures in JavaScript here.


问:
What does the ?. syntax mean in JavaScript?
I came across this C# like code in a React project. I couldn't confirm if this syntax correct or not. I didn't find any recent ES version release to support this syntax. In current scenario I'm not authorized to execute and check this code.

I tried testing this syntax in browse console and encountered error:

```<code>{cart?.widgets?.items.map(widget => (
        <div className="billing-details__box" key={widget.id}>
          <p className="m-0">{widget.name}</p>
          <p className="my-0">{widget.value} $</p>
        </div>
 ))}
</code>```

My concern with above code is whether cart?.widgets?.items will raise any error or not.

答:
It will be compiled by Babel and it will work.
https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining</p>

Body:
I came across this C# like code in a React project. I couldn't confirm if this syntax correct or not. I didn't find any recent ES version release to support this syntax. In current scenario I'm not authorized to execute and check this code.

I tried testing this syntax in browse console and encountered error:

{cart?.widgets?.items.map(widget => (

{widget.name}

{widget.value} $

 ))}

My concern with above code is whether cart?.widgets?.items will raise any error or not.


问:
How do I store the location of an object in C#
I wish to store the longitude and Latitude of an object in C# and I am wondering what could be a good way to do that. I can imagine I can simply initialize a double for longitude and latitude. In Android, there is a Location class that can be used to save the longitude and latitude of an object but I do not seem to find any like that for C#. What do you suggest I can use?</p>

答:
There are a couple of options here:

GeographyPoint - Represents a geography point.

Namespace information

OData stands for the Open Data Protocol. It was initiated by Microsoft and is now an ISO approved and OASIS standard. OData enables the creation and consumption of REST APIs, which allow resources, identified using URLs and defined in a data model, to be published and edited by Web clients using simple HTTP requests.

So it's mostly used for RestApis

DBGeography - Represents data in a geodetic (round earth) coordinate system.

One very handy feature of the System.Data.Spatial namespace is the DbGeography class that allows you to work with either points on a "map" or shapes/polygons.

GeoCoordinate - Represents a geographical location that is determined by latitude and longitude coordinates. May also include altitude, accuracy, speed, and course information.

Namespace information

The System.Device.Location namespace allows application developers to easily access the computer's location by using a single API. Location information may come from multiple providers, such as GPS, Wi-Fi triangulation, and cell phone tower triangulation. The System.Device.Location classes provide a single API to encapsulate the multiple location providers on a computer and support seamless prioritization and transitioning between them. As a result, application developers who use this API do not need to tailor applications to specific hardware configurations.


问:
Changing output directory of library created through pybind11_add_module
I am using CMake to build some python bindings for my code using Pybind11. It is working well, but they get compiled in the main build directory. I would like them to be built on build\python directory. I am trying the following:

```<code>pybind11_add_module(myModule src/main.cpp)
set_target_properties(myModule PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/python")
</code>```

But it is not working as intended, myModule is still built on the build directory as if the set_target_properties was not being called.

In the official pybind11_add_module documentation it is written:

This function behaves very much like CMake’s builtin add_library (in fact, it’s a wrapper function around that command). It will add a library target called  to be built from the listed source files. In addition, it will take care of all the Python-specific compiler and linker flags as well as the OS- and Python-version-specific file extension. The produced target  can be further manipulated with regular CMake commands.

So I assumed that set_target_properties could be used to indicate a different output directory after it, is this not the case? If not, how can this be done?

Thank you in advance!

答:
pybind11 module is a library of either a SHARED or MODULE type.

Build directory for SHARED libraries is specified via LIBRARY_OUTPUT_DIRECTORY on all platforms except for Windows (and its dll's).

Build directory for MODULE libraries is specified via LIBRARY_OUTPUT_DIRECTORY on all platforms without exception.

Detailed description of types for output artifacts in CMake and corresponded OUTPUT variables can be found in the documentation.

Body:
I am using CMake to build some python bindings for my code using Pybind11. It is working well, but they get compiled in the main build directory. I would like them to be built on build\python directory. I am trying the following:

pybind11_add_module(myModule src/main.cpp)
set_target_properties(myModule PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/python")

But it is not working as intended, myModule is still built on the build directory as if the set_target_properties was not being called.

In the official pybind11_add_module documentation it is written:

This function behaves very much like CMake’s builtin add_library (in fact, it’s a wrapper function around that command). It will add a library target called  to be built from the listed source files. In addition, it will take care of all the Python-specific compiler and linker flags as well as the OS- and Python-version-specific file extension. The produced target  can be further manipulated with regular CMake commands.

So I assumed that set_target_properties could be used to indicate a different output directory after it, is this not the case? If not, how can this be done?

Thank you in advance!


问:
EmbeddedKafkaRule have no brokerListProperty method
I'm trying to figure out Spring Kafka. While following reference I found error in this example. There is no brokerListProperty() method in EmbeddedKafkaRule class. How should I refactor the code to make it work?

Code from link above:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
public class MyApplicationTests {

    @ClassRule
    public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1,
        false, "someTopic")
            .brokerListProperty("spring.kafka.bootstrap-servers");
    }

    @Autowired
    private KafkaTemplate<String, String> template;

    @Test
    public void test() {
        ...
    }

}
</code>```

答:
Together with the @SpringBootTest consider to use an @EmbeddedKafka instead.
That one has a property like:

```<code>/**
 * The property name to set with the bootstrap server addresses instead of the default
 * {@value org.springframework.kafka.test.EmbeddedKafkaBroker#SPRING_EMBEDDED_KAFKA_BROKERS}.
 * @return the property name.
 * @since 2.3
 * @see org.springframework.kafka.test.EmbeddedKafkaBroker#brokerListProperty(String)
 */
String bootstrapServersProperty() default "";
</code>```

The goal for  an EmbeddedKafkaRule, when we don't use Spring in tests at all.
And I agree that we are missing a propagation property from that EmbeddedKafkaRule into a brokerListProperty(). Please, feel free to raise a GH issue and contribute a fix on the matter.

Meanwhile you can workaround it like this:

```<code>@ClassRule
public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1, false, "someTopic");

@BeforeAll
pubic static void setup() {
    broker.getEmbeddedKafka().brokerListProperty("spring.kafka.bootstrap-servers");
}
</code>```

Body:
I'm trying to figure out Spring Kafka. While following reference I found error in this example. There is no brokerListProperty() method in EmbeddedKafkaRule class. How should I refactor the code to make it work?

Code from link above:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyApplicationTests {

    @ClassRule
    public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1,
        false, "someTopic")
            .brokerListProperty("spring.kafka.bootstrap-servers");
    }

    @Autowired
    private KafkaTemplate<String, String> template;

    @Test
    public void test() {
        ...
    }

}

Body:
Together with the @SpringBootTest consider to use an @EmbeddedKafka instead.
That one has a property like:

/**
 * The property name to set with the bootstrap server addresses instead of the default
 * {@value org.springframework.kafka.test.EmbeddedKafkaBroker#SPRING_EMBEDDED_KAFKA_BROKERS}.
 * @return the property name.
 * @since 2.3
 * @see org.springframework.kafka.test.EmbeddedKafkaBroker#brokerListProperty(String)
 */
String bootstrapServersProperty() default "";

The goal for  an EmbeddedKafkaRule, when we don't use Spring in tests at all.
And I agree that we are missing a propagation property from that EmbeddedKafkaRule into a brokerListProperty(). Please, feel free to raise a GH issue and contribute a fix on the matter.

Meanwhile you can workaround it like this:

@ClassRule
public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1, false, "someTopic");

@BeforeAll
pubic static void setup() {
    broker.getEmbeddedKafka().brokerListProperty("spring.kafka.bootstrap-servers");
}


问:
Array Should Only Contains Values From Other Array
I Have Two Arrays.

```<code>$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png");
</code>```

I need a function to achieve a specific goal.
The Conditions are,
1. uploaded_array can only contain elements from allowed_array.
2. it is okay for uploaded_array to not contain all the elements present in allowed_array but
the uploaded_array should not contain any element which is not present in the allowed_array.
3. it is also okay for uploaded_array to have duplicates element as long as the element is present in allowed_array too.

I am just storing the uploaded images file type into uploaded_array and then i have defined allowed_array to set acceptable file type formats.

Thanks for the answers.

Found one solution by myself. just eliminated duplicates from the first array and compared the two arrays for the difference and then count the difference. if the count is more then 0 it means the first array had an element which is not present in the second array.

```<code>$uploaded_array = array_unique(array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html"));
$allowed_array = array("image/jpeg", "image/gif", "image/png");
$acceptable_format=count(array_diff($uploaded_array,$allowed_array));

if($acceptable_format==0) {
//all files are acceptable
} else {
//some files are not in valid format
}
</code>```

答:
what about in_array+foreach?</p>

```<code>$index = 0;
foreach($uploaded_array as $key => $val) {
    if(in_array($val, $allowed_array)) {
        $aa[$index++] = $val;
    }
}
</code>```

Body:
I Have Two Arrays.

$uploaded_array = array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html");
$allowed_array = array("image/jpeg", "image/gif", "image/png");

I need a function to achieve a specific goal.
The Conditions are,
1. uploaded_array can only contain elements from allowed_array.
2. it is okay for uploaded_array to not contain all the elements present in allowed_array but
the uploaded_array should not contain any element which is not present in the allowed_array.
3. it is also okay for uploaded_array to have duplicates element as long as the element is present in allowed_array too.

I am just storing the uploaded images file type into uploaded_array and then i have defined allowed_array to set acceptable file type formats.

Thanks for the answers.

Found one solution by myself. just eliminated duplicates from the first array and compared the two arrays for the difference and then count the difference. if the count is more then 0 it means the first array had an element which is not present in the second array.

$uploaded_array = array_unique(array("image/jpeg", "image/jpeg", "image/gif", "image/png", "text/html"));
$allowed_array = array("image/jpeg", "image/gif", "image/png");
$acceptable_format=count(array_diff($uploaded_array,$allowed_array));

if($acceptable_format==0) {
//all files are acceptable
} else {
//some files are not in valid format
}

Body:
what about in_array+foreach?

$index = 0;
foreach($uploaded_array as $key => $val) {
    if(in_array($val, $allowed_array)) {
        $aa[$index++] = $val;
    }
}


问:
CodeIgniter is caching view variable even if I explicitly set it again
I'm using the CodeIgniter PHP framework. I have a simple form that has an $editcode hidden variable that gets sent on form submit. The form submits data to a form processing function which then redisplays the view with the form again, however with the $editcode$ variable changed to a new value.

The problem is that no matter what I do, the value of $editcode remains the same as the original value even after the form is submitted and the view redrawn with a new $editcode variable.

Extract from my view showing how $editcode is included and submitted.

```<code>echo form_open('/add', $formattributes);
echo form_hidden('editcode', set_value('editcode', $editcode));
echo form_submit('submit','Submit!','id="submit"');
</code>```

The add() function code (the $refreshed_editcode is positively different from the original $editcode that got generated).

```<code>...
$data['editcode'] = $refreshed_editcode;
$this->load->view('includes/template', $data);
</code>```

When the view gets redrawn by the add() function, the $editcode value should be $refreshed_editcode, but instead it's still the original value.

I know CodeIgniter does some caching of variables for nested views, however in this case I am explicitly resending new values for the $editcode variable. What gives?

答: Try getting rid of the call to set_value. Since the form field is hidden, it really shouldn't give you much benefit anyway, and I suspect that is where the "caching" is happening (If I'm not mistaken that function is part of the form_helpers file and it actually is designed to cache to help re-populate data, but it has been a while since I've used it).</p>

Body:
I'm using the CodeIgniter PHP framework. I have a simple form that has an $editcode hidden variable that gets sent on form submit. The form submits data to a form processing function which then redisplays the view with the form again, however with the $editcode$ variable changed to a new value.

The problem is that no matter what I do, the value of $editcode remains the same as the original value even after the form is submitted and the view redrawn with a new $editcode variable.

Extract from my view showing how $editcode is included and submitted.

echo form_open('/add', $formattributes);
echo form_hidden('editcode', set_value('editcode', $editcode));
echo form_submit('submit','Submit!','id="submit"');

The add() function code (the $refreshed_editcode is positively different from the original $editcode that got generated).

...
$data['editcode'] = $refreshed_editcode;
$this->load->view('includes/template', $data);

When the view gets redrawn by the add() function, the $editcode value should be $refreshed_editcode, but instead it's still the original value.

I know CodeIgniter does some caching of variables for nested views, however in this case I am explicitly resending new values for the $editcode variable. What gives?


问:
Doing SFTP operations over sudo in remote machine with Paramiko
How do I use Paramiko and sudo to run chmod 775?

Code snippet:

```<code>    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    r_pass = getpass.getpass(prompt='Remote password? ')
    ssh_client.connect(r_ip, username=r_name, password=r_pass)
    ftp = ssh_client.open_sftp()
    for fn in files:
        print("sending {} of {}".format(count, len(files)))
        ftp.put(fn, posixpath.join(r_path_mark, fn))
        ftp.chmod(r_path_mark+fn, 0o775)
</code>```

The very last ftp.chmod command results in a "permission denied".

答:
Thanks everyone who replied. I did review everyone's feedback. All are good but for our solution, it didnt do it. Thanks also to @cricket_007. My TL suggested I use Ansible as well.

I did get it work. The trick was to call another script wherein the called script resides locally in the remote machine and therefore sudo stuff isn't an issue.

Flow is as follows:

App server (script 'A' is invoked by user)

App server (script A does its routine and then using subprocess.call it calls script 'B' also residing in the same App server)

App server (script 'B' has some magical open source code that I didnt write.. but it invokes a script 'C' residing in a remote server)

Remote server (script 'C' is able to run everything as sudo su - locally. No special coding needed as its local to the machine << and that was my original problem to begin with)

All good << Just tested the end to end deployment this morning.

Body:
How do I use Paramiko and sudo to run chmod 775?

Code snippet:

    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    r_pass = getpass.getpass(prompt='Remote password? ')
    ssh_client.connect(r_ip, username=r_name, password=r_pass)
    ftp = ssh_client.open_sftp()
    for fn in files:
        print("sending {} of {}".format(count, len(files)))
        ftp.put(fn, posixpath.join(r_path_mark, fn))
        ftp.chmod(r_path_mark+fn, 0o775)

The very last ftp.chmod command results in a "permission denied".


问:
Restructure Date in R
I have dataset like:

```<code> CODE    NAME    DATE      HOUR
  1       Ab    01-01-19     1
  1       Ab    02-01-19     2
  1       Ab    03-01-19     3
  1       Ab    04-01-19     4
  2       Xy    01-JAN-19    1
  2       Xy    02-JAN-19    2
  2       Xy    03-JAN-19    3
  2       Xy    04-JAN-19    4
</code>```

Actual data set is much bigger. I want to convert all the DATE's in 01-JAN-19 format.
I tried with:

```<code>a <- as.Date(df$DATE, format = "%d-%b-%y")
b <- as.Date(df$DATE, format = "%d-%m-%y")
a[is.na(a)] <- b[!is.na(b)]
df$ <- a
</code>```

But it's taking time & giving result in 2019-01-01 format. Even I tried with:

```<code>df$DATE <- format(as.Date(df$DATE, format = c("%d-%b-%y", "%d-%m-%y")), "%d-%b-%y")
</code>```

It's giving the desired result but it's filling alternate NA values in DATE column like:

```<code> CODE    NAME    DATE      HOUR
  1       Ab    01-JAN-19    1
  1       Ab    NA           2
  1       Ab    03-JAN-19    3
  1       Ab    NA           4
  2       Xy    NA           1
  2       Xy    02-JAN-19    2
  2       Xy    NA           3
  2       Xy    04-JAN-19    4
</code>```

I think it's because of format = c("%d-%b-%y", "%d-%m-%y"). How can I convert all DATE's into 01-JAN-19 format.

答:
1) Using the input data shown reproducibly in the Note at the end, in toDate use the tryFormats argument of as.Date.  as.Date assumes all entries have the same format so lapply over the input to apply it individually to each element and then concatenate the resulting list back to a Date vector.  Now use toDate to convert DATE to Date class and then format it and convert to upper case. No packages are used.

```<code>toDate <- function(x, formats = c("%d-%m-%y", "%d-%b-%y")) {
  do.call("c", lapply(x, as.Date, tryFormats = formats))
}

transform(df, DATE = toupper(format(toDate(DATE), "%d-%b-%Y")))
</code>```

2) Another approach is to just convert those entries not already in the desired format.  Again, no packages are used.

```<code>ok <- grepl("[A-Z]", df$DATE)
transform(df, DATE =
  replace(DATE, !ok, toupper(format(as.Date(DATE[!ok], "%d-%m-%y"), "%d-%b-%y")))
</code>```

Note

```<code>Lines <- "CODE    NAME    DATE      HOUR
  1       Ab    01-01-19     1
  1       Ab    02-01-19     2
  1       Ab    03-01-19     3
  1       Ab    04-01-19     4
  2       Xy    01-JAN-19    1
  2       Xy    02-JAN-19    2
  2       Xy    03-JAN-19    3
  2       Xy    04-JAN-19    4"
df <- read.table(text = Lines, header = TRUE, as.is = TRUE)
</code>```

Title: Restructure Date in R

Body:
I have dataset like:

 CODE    NAME    DATE      HOUR
  1       Ab    01-01-19     1
  1       Ab    02-01-19     2
  1       Ab    03-01-19     3
  1       Ab    04-01-19     4
  2       Xy    01-JAN-19    1
  2       Xy    02-JAN-19    2
  2       Xy    03-JAN-19    3
  2       Xy    04-JAN-19    4

Actual data set is much bigger. I want to convert all the DATE's in 01-JAN-19 format.
I tried with:

a <- as.Date(df$DATE, format = "%d-%b-%y")
b <- as.Date(df$DATE, format = "%d-%m-%y")
a[is.na(a)] <- b[!is.na(b)]
df$ <- a

But it's taking time & giving result in 2019-01-01 format. Even I tried with:

df$DATE <- format(as.Date(df$DATE, format = c("%d-%b-%y", "%d-%m-%y")), "%d-%b-%y")

It's giving the desired result but it's filling alternate NA values in DATE column like:

 CODE    NAME    DATE      HOUR
  1       Ab    01-JAN-19    1
  1       Ab    NA           2
  1       Ab    03-JAN-19    3
  1       Ab    NA           4
  2       Xy    NA           1
  2       Xy    02-JAN-19    2
  2       Xy    NA           3
  2       Xy    04-JAN-19    4

I think it's because of format = c("%d-%b-%y", "%d-%m-%y"). How can I convert all DATE's into 01-JAN-19 format.

Body:
1) Using the input data shown reproducibly in the Note at the end, in toDate use the tryFormats argument of as.Date.  as.Date assumes all entries have the same format so lapply over the input to apply it individually to each element and then concatenate the resulting list back to a Date vector.  Now use toDate to convert DATE to Date class and then format it and convert to upper case. No packages are used.

toDate <- function(x, formats = c("%d-%m-%y", "%d-%b-%y")) {
  do.call("c", lapply(x, as.Date, tryFormats = formats))
}

transform(df, DATE = toupper(format(toDate(DATE), "%d-%b-%Y")))

2) Another approach is to just convert those entries not already in the desired format.  Again, no packages are used.

ok <- grepl("[A-Z]", df$DATE)
transform(df, DATE =
  replace(DATE, !ok, toupper(format(as.Date(DATE[!ok], "%d-%m-%y"), "%d-%b-%y")))

Note

Lines <- "CODE    NAME    DATE      HOUR
  1       Ab    01-01-19     1
  1       Ab    02-01-19     2
  1       Ab    03-01-19     3
  1       Ab    04-01-19     4
  2       Xy    01-JAN-19    1
  2       Xy    02-JAN-19    2
  2       Xy    03-JAN-19    3
  2       Xy    04-JAN-19    4"
df <- read.table(text = Lines, header = TRUE, as.is = TRUE)


问:
Why LRU caches use doubly link list and not singly link list?
I have been trying to understand why LRU caches use doubly link list and not singly link list?

If i go by the time complexities they both have same for insertion , updation and deletion.
Here is the Cheat sheet

Is it because the two ways pointers in DLL is used for easier move of nodes to rear or front ??

答:
To remove a targeted node from a linked list, you need to modify the other nodes that point to it.

In a doubly-linked list, the targeted node has pointers to these other nodes, so it's easy to find them.

In a single-linked list, the targeted node does not have a pointer to the other node that points to it.  You still need to modify that node, though, so you'd have to search for it.


问:
Laravel handle user redirection in trait based on role
I am using Laravel Auth and Socialite package for social login. I also have different user roles and redirecting them on separate pages based on roles.

Handling redirection for Auth logged in user from LoginController > authenticated() method.

LoginController

```<code>public function authenticated(Request $request, $user)
{
    if (auth()->check()) {
        if (in_array($user->role, $this->getAdminRoles())) {
            return redirect(route('admin.dashboard'));
        }
    }
}
</code>```

It is working correctly and redirecting the user based on their role.  However, that only works if they login in the traditional way.

If the user login using any social channel, the redirection doesn't work. I realize that the Social Login redirection Handel from its handler method. For that, I have a trait as below. So I can use it on RegisterController to avoid code duplication.

SocialAuthHandler Trait

```<code>namespace App\Traits;

use App\SocialProvider;
use App\User;
use DateTime;
use Exception;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

use function is_null;
use function preg_replace;
use function redirect;
use function strtolower;

trait SocialAuthHandler
{
    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @param $provider
     *
     * @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @param $provider
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function handleProviderCallback($provider)
    {
        try {
            $socialUser = Socialite::driver($provider)->user();
        } catch (Exception $e) {
            return redirect('/');
        }

        //
        $socialProvider = SocialProvider::where('provider_id', $socialUser->getId())->first();

        if (!$socialProvider) {
            $username = $socialUser->getNickname();
            $name     = $socialUser->getName();

            if (!isset($userNickname) || is_null($userNickname)) {
                if (isset($name) && !is_null($name)) {
                    $username = strtolower(preg_replace('/\s+/', '', $name));
                } else {
                    $timeStamp = new DateTime('now');
                    $username  = $timeStamp->format('U');
                }
            }

            //create user
            $user = User::firstOrCreate(
                ['email' => $socialUser->getEmail()],
                ['username' => $username]
            );

            // mark email is verified
            // for social logged in users
            $user->markEmailAsVerified();

            $user->socialProviders()->create(
                [
                    'provider_id' => $socialUser->getId(),
                    'provider'    => $provider,
                ]
            );
        } else {
            $user = $socialProvider->user;
        }

        // log in user
        Auth::login($user, TRUE);

        return redirect($this->redirectTo);
    }
}
</code>```

Question: is how can I handle redirection on the social handler so the user will redirect based on their role. If the admin then admin/dashboard or if the user then home?

Well, most likely this might not happen on the first time user login as the default role will be user but later whenever they log in after assigned different role

答:
In your SocialAuthHandler trait, you are simply redirecting to the redirectTo property without checking for the user's role. You could achieve the same behaviour by calling the authenticated method.

Replace:

return redirect($this->redirectTo);
```

<p>By:</p>

<pre class="lang-php prettyprint-override"><code>return $this->authenticated(request(), $user) ?: redirect($this->redirectTo);
</code>```

Body:
I am using Laravel Auth and Socialite package for social login. I also have different user roles and redirecting them on separate pages based on roles.

Handling redirection for Auth logged in user from LoginController > authenticated() method.

LoginController

public function authenticated(Request $request, $user)
{
    if (auth()->check()) {
        if (in_array($user->role, $this->getAdminRoles())) {
            return redirect(route('admin.dashboard'));
        }
    }
}

It is working correctly and redirecting the user based on their role.  However, that only works if they login in the traditional way.

If the user login using any social channel, the redirection doesn't work. I realize that the Social Login redirection Handel from its handler method. For that, I have a trait as below. So I can use it on RegisterController to avoid code duplication.

SocialAuthHandler Trait

namespace App\Traits;

use App\SocialProvider;
use App\User;
use DateTime;
use Exception;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

use function is_null;
use function preg_replace;
use function redirect;
use function strtolower;

trait SocialAuthHandler
{
    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @param $provider
     *
     * @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @param $provider
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function handleProviderCallback($provider)
    {
        try {
            $socialUser = Socialite::driver($provider)->user();
        } catch (Exception $e) {
            return redirect('/');
        }

        //
        $socialProvider = SocialProvider::where('provider_id', $socialUser->getId())->first();

        if (!$socialProvider) {
            $username = $socialUser->getNickname();
            $name     = $socialUser->getName();

            if (!isset($userNickname) || is_null($userNickname)) {
                if (isset($name) && !is_null($name)) {
                    $username = strtolower(preg_replace('/\s+/', '', $name));
                } else {
                    $timeStamp = new DateTime('now');
                    $username  = $timeStamp->format('U');
                }
            }

            //create user
            $user = User::firstOrCreate(
                ['email' => $socialUser->getEmail()],
                ['username' => $username]
            );

            // mark email is verified
            // for social logged in users
            $user->markEmailAsVerified();

            $user->socialProviders()->create(
                [
                    'provider_id' => $socialUser->getId(),
                    'provider'    => $provider,
                ]
            );
        } else {
            $user = $socialProvider->user;
        }

        // log in user
        Auth::login($user, TRUE);

        return redirect($this->redirectTo);
    }
}

Question: is how can I handle redirection on the social handler so the user will redirect based on their role. If the admin then admin/dashboard or if the user then home?

Well, most likely this might not happen on the first time user login as the default role will be user but later whenever they log in after assigned different role

Body:
In your SocialAuthHandler trait, you are simply redirecting to the redirectTo property without checking for the user's role. You could achieve the same behaviour by calling the authenticated method.

Replace:

return redirect($this->redirectTo);

By:

return $this->authenticated(request(), $user) ?: redirect($this->redirectTo);


问:
SQL query to JPA specification
I have this simplified JPA entities

```<code>@Entity
@Table(name = "students")
public class Student {
    @Id
    private Integer id;

    private String name;

    //getters, setters
}

@Entity
@Table(name = "averages")
public class Averages {
    @Id
    private Integer id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "student_id", referencedColumnName = "id")
    private Student student;

    private float value;

    //getters, setters
}
</code>```

How I can write this query using JPA Specification and CriteriaBuilder?

```<code>SELECT students.id
FROM students,
     averages
WHERE averages.student_id = students.id
GROUP BY students.id
HAVING AVG(averages.value) > 6
</code>```

答:
It should be something like:

```<code>select student.id
from Averages average
join average.student student
group by student.id
having avg(average.value)>6
</code>```

i have no way of testing this

Edit: this is using EntityManager#createQuery(String)

Title: SQL query to JPA specification

Body:
I have this simplified JPA entities

@Entity
@Table(name = "students")
public class Student {
    @Id
    private Integer id;

    private String name;

    //getters, setters
}

@Entity
@Table(name = "averages")
public class Averages {
    @Id
    private Integer id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "student_id", referencedColumnName = "id")
    private Student student;

    private float value;

    //getters, setters
}

How I can write this query using JPA Specification and CriteriaBuilder?

SELECT students.id
FROM students,
     averages
WHERE averages.student_id = students.id
GROUP BY students.id
HAVING AVG(averages.value) > 6

Body:
It should be something like:

select student.id
from Averages average
join average.student student
group by student.id
having avg(average.value)>6

i have no way of testing this

Edit: this is using EntityManager#createQuery(String)


问:
how to access apn service
i am new to the field, i dontkno0w what exactly is apn service in iphone. How can we access it. what code we have to write in server to connect with the device. please help me out
thanks in advance</p>

答: I would suggest starting with the Apple Push Notification Service Guide, which is a great overview (both on the client and server side).</p>

Title: how to access apn service


问:
Dynamically adding new fabric canvases
I am working on a project that requires creating multiple canvas elements (separate bars each representing one distinct gradient). I would like to do this dynamically with fabric.js, eg:

```<code> function add_gradient(color_stops){
     // Add a new rectangular canvas with fill representing specified gradient
     var grad_box = document.getElementById("divWithCanvases");

     var newCanvas = document.createElement("canvas");
     grad_box.appendChild(newCanvas);

     var gradCanvas = fabric.Canvas(newCanvas, {width: 500, height:50});
     var ctx = gradCanvas.getContext('2d');
     // Do stuff to canvas...
 }
</code>```

However, the call to fabric.Canvas fails with an error "this.initialize is undefined". (fabric.js line 1627, version 1.4.13)

How can I either:

Generate a new fabric canvas based on an HTML element (instead of the string id), or,

Append an auto-generated new canvas element to the DOM? (the form fabric.Canvas() without arguments will make... something... but it can't be used with appendChild)

According to the fabric.js documentation, the fabric.Canvas constructor accepts either an HTMLElement, or a string element id. I can only make it work with the string.

答:
I was getting the above error because of

Make sure your html element should be canvas

```<code><canvas id="canvas"> </canvas>
</code>```

Title: Dynamically adding new fabric canvases

Body:
I am working on a project that requires creating multiple canvas elements (separate bars each representing one distinct gradient). I would like to do this dynamically with fabric.js, eg:

 function add_gradient(color_stops){
     // Add a new rectangular canvas with fill representing specified gradient
     var grad_box = document.getElementById("divWithCanvases");

     var newCanvas = document.createElement("canvas");
     grad_box.appendChild(newCanvas);

     var gradCanvas = fabric.Canvas(newCanvas, {width: 500, height:50});
     var ctx = gradCanvas.getContext('2d');
     // Do stuff to canvas...
 }

However, the call to fabric.Canvas fails with an error "this.initialize is undefined". (fabric.js line 1627, version 1.4.13)

How can I either:

Generate a new fabric canvas based on an HTML element (instead of the string id), or,

Append an auto-generated new canvas element to the DOM? (the form fabric.Canvas() without arguments will make... something... but it can't be used with appendChild)

According to the fabric.js documentation, the fabric.Canvas constructor accepts either an HTMLElement, or a string element id. I can only make it work with the string.

Body:
I was getting the above error because of <div id="canvas"> </div>

Make sure your html element should be canvas

<canvas id="canvas"> </canvas>


问:
Azure ASE AutoScale is slow
Seems like although, auto-scaling is possible in an ASE however it needs to have resources provisioned first which is extremely slow (e.g. For Scale Out : 1 hr per worker, For Scale UP : # of workers x 1 hr). This makes auto-scale an almost non-viable option.

Is there something that I am missing or is there a way to this faster ?

Here the motivation to auto-scale is cost and hence using the auto-scale feature when the resources are already provisioned (and are being paid) for isn't feasible.

答:
Thanks for asking question! To elaborate on this. Yes, you are correct ASE support autoscaling. You may autoscale individual worker pools based on metrics or on schedule. Also, you can configure an autoscale profile and set limits on your scale. Once you have defined a profile, you can add autoscale rules to scale up or down the number of instances in the worker pool within the bounds defined by the profile.

You may refer to below link might be helpful:

https://learn.microsoft.com/en-us/azure/app-service/environment/app-service-environment-auto-scale

Title: Azure ASE AutoScale is slow


问:
Vertical line within bars of a stacked bar chart using recharts or highcharts
How do I add a line like the one in first bar. It will be on percentage basis i.e. full width of the bar is 100%. Any clue will be helpful. My current chart is based on the code from this simple example
I'm OK to switch to highcharts if it works with that.

答:
You can easily draw those line by using the Highcharts library.

To do it you will need to define those line as a new series, where you will need to define x and y values to fit the line on the chart.

Demo: https://jsfiddle.net/BlackLabel/v3gmph9w/

```<code>series: [{
    name: 'John',
    data: [5, 3, 4, 7, 2]
}, {
    name: 'Jane',
    data: [2, 2, 3, 2, 1]
}, {
    name: 'Joe',
    data: [3, 4, 4, 2, 5]
}, {
        type: 'line',
    enableMouseTracking: false,
    data: [{x:0, y: 3}, {x: 0, y: 5}]
}]
</code>```

API: https://api.highcharts.com/highcharts/series.line.data

Body:
You can easily draw those line by using the Highcharts library.

To do it you will need to define those line as a new series, where you will need to define x and y values to fit the line on the chart.

Demo: https://jsfiddle.net/BlackLabel/v3gmph9w/

series: [{
    name: 'John',
    data: [5, 3, 4, 7, 2]
}, {
    name: 'Jane',
    data: [2, 2, 3, 2, 1]
}, {
    name: 'Joe',
    data: [3, 4, 4, 2, 5]
}, {
        type: 'line',
    enableMouseTracking: false,
    data: [{x:0, y: 3}, {x: 0, y: 5}]
}]

API: https://api.highcharts.com/highcharts/series.line.data


问:
pandas copy value from one column to another if condition is met
I have a dataframe:

```<code>df =
col1  col2  col3
1      2     3
1      4     6
3      7     2
</code>```

I want to edit df, such that when the value of col1 is smaller than 2 , take the value from col3.

So I will get:

```<code>new_df =
col1  col2  col3
3      2     3
6      4     6
3      7     2
</code>```

I tried to use assign and df.loc but it didn't work.

What is the best way to do so?

答:
You could look at using the apply function.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html

```<code>df['col1'] = df.apply(lambda c: c['col3'] if c['col1'] < 2 else c['col1'], axis=1)
</code>```

Edit: Sorry, I see from your mock outcome you are referring to col2 rather than an int of 2. Eric Yang's answer will solve your problem.

Body:
I have a dataframe:

df =
col1  col2  col3
1      2     3
1      4     6
3      7     2

I want to edit df, such that when the value of col1 is smaller than 2 , take the value from col3.

So I will get:

new_df =
col1  col2  col3
3      2     3
6      4     6
3      7     2

I tried to use assign and df.loc but it didn't work.

What is the best way to do so?

Body:
You could look at using the apply function.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html

df['col1'] = df.apply(lambda c: c['col3'] if c['col1'] < 2 else c['col1'], axis=1)

Edit: Sorry, I see from your mock outcome you are referring to col2 rather than an int of 2. Eric Yang's answer will solve your problem.


问:
Angular Form Custom Validators
I'm currently using Angular 8 and I have an issue with custom validator. The only validator that works is Validators.minLength(3). noEmptyStringValidator doesn't work, even though I can print 'here' into validator function. Could you help me?

The context is the following:

no-empty-string.validator.ts

```<code>import { AbstractControl } from '@angular/forms';

export function noEmptyStringValidator(control: AbstractControl): { [key: string]: any } | null {
    console.log('here');

    return control.value && control.value.trim().length > 0 ? { noEmptyString: { valid: true } } : null;
}
</code>```

myComponent.component.ts

```<code>...
topicLabelControl = new FormControl();
...
this.topicLabelControl.setValidators([ Validators.minLength(3), noEmptyStringValidator ]);
...
console.log(this.topicLabelControl.valid);
</code>```

myComponent.component.html

```<code><mat-form-field appearance="outline"
      (keydown.enter)="handleEnterKey()">
      <input type="text"
        matInput
        [formControl]="topicLabelControl"
        [matAutocomplete]="auto" />
      <mat-autocomplete #auto="matAutocomplete">...
      </mat-autocomplete>
    </mat-form-field>
</code>```

答:
Your logic seems to be inverted: if the input is valid the validator should return null, if invalid an object whose key identifies the error. (The value can be anything, and can be used to report any additional information):

return control.value && control.value.trim().length > 0 ? null : { noEmptyString: true };
```

Title: Angular Form Custom Validators

Body:
I'm currently using Angular 8 and I have an issue with custom validator. The only validator that works is Validators.minLength(3). noEmptyStringValidator doesn't work, even though I can print 'here' into validator function. Could you help me?

The context is the following:

no-empty-string.validator.ts

import { AbstractControl } from '@angular/forms';

export function noEmptyStringValidator(control: AbstractControl): { [key: string]: any } | null {
    console.log('here');

    return control.value && control.value.trim().length > 0 ? { noEmptyString: { valid: true } } : null;
}

myComponent.component.ts

...
topicLabelControl = new FormControl();
...
this.topicLabelControl.setValidators([ Validators.minLength(3), noEmptyStringValidator ]);
...
console.log(this.topicLabelControl.valid);

myComponent.component.html

<mat-form-field appearance="outline"
      (keydown.enter)="handleEnterKey()">
      <input type="text"
        matInput
        [formControl]="topicLabelControl"
        [matAutocomplete]="auto" />
      <mat-autocomplete #auto="matAutocomplete">...
      </mat-autocomplete>
    </mat-form-field>