问:
FCM: invalid parameter, token reason for iOS
I'm integrating FCM into my iOS app. I'm receiving this error when sending token to my backend server:

Invalid parameter: Token Reason: iOS device tokens must be no more than 400 hexadecimal characters

And in my code, I'm sending FCM registration token to the server. Is this correct? or should I send device token instead? If so, what's the use of this FCM registration token for?

Need help on this.

```<code>- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
//Get FCM registration token
[[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,
                                                    NSError * _Nullable error) {
    if (error != nil) {
        NSLog(@"Error fetching remote instance ID: %@", error);
    } else {
        NSLog(@"Remote instance ID token: %@", result.token);

        [UserDefaultUtility setDeviceToken:result.token];
    }
}];

}

#pragma mark - FCM delegate
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
// Note: This callback is fired at each app startup and whenever a new token is generated.

NSLog(@"FCM registration token: %@", fcmToken);
[UserDefaultUtility setDeviceToken:fcmToken];

}
</code>```

I'm doing this on simulator, does it affect it?

答:
This is likely an error with your backend.

The FCM Token is generated by Firebase, and Firebase alone handles the mappings between the FCM token and the iOS Device Token. Thus, when you use FCM, you only care about the FCM token so that is definitely what you should be sending. However, it seems that your backend, for some reason, is expecting an actual iOS Device token.

So to fix this error, you have to change your backend code (which you haven't provided so I can't help with), so that it is not expecting an actual iOS  Device Token, but instead expects an FCM token.

Then, to "use FCM", you'd change your backend to stop directly interacting with Apple's push notification servers (or whatever other service you currently used that needed the actual iOS Device Token), and start interacting with the FCM APIs instead, using any of the methods listed in the docs. The FCM APIs would use the FCM Token to identify which device to send push notifications to.

Body:
I'm integrating FCM into my iOS app. I'm receiving this error when sending token to my backend server:

Invalid parameter: Token Reason: iOS device tokens must be no more than 400 hexadecimal characters

And in my code, I'm sending FCM registration token to the server. Is this correct? or should I send device token instead? If so, what's the use of this FCM registration token for?

Need help on this.

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
//Get FCM registration token
[[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,
                                                    NSError * _Nullable error) {
    if (error != nil) {
        NSLog(@"Error fetching remote instance ID: %@", error);
    } else {
        NSLog(@"Remote instance ID token: %@", result.token);

        [UserDefaultUtility setDeviceToken:result.token];
    }
}];

}

#pragma mark - FCM delegate
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
// Note: This callback is fired at each app startup and whenever a new token is generated.

NSLog(@"FCM registration token: %@", fcmToken);
[UserDefaultUtility setDeviceToken:fcmToken];

}

I'm doing this on simulator, does it affect it?


来源: stackexchange

问:
Resource with a single attribute. Sign that something smells?
I have a book model and a notes model. Each book can have many notes.

```<code># note.rb
id | book_id | content | page_number | author_id |
</code>```

I want to run a lot of queries like

Get all the notes for page 43 of a certain book

Show all the noted pages of a certain book

These types of queries seem to favor making a separate noted_pages model so that a book can have many noted_pages and each noted_page can have many notes. This is fine but my noted_pages table would effectively just have an id column and a page_number column which doesn't sit right with me.

Is there a more standard way to implement this kind of setup or is my thinking ok?

答:
Both of these can be simple ARel queries, no scope is required

The latter one is a simple check of the existence of the notes collection:

```<code>@book.notes.empty? #if there are no notes, it'll return true and vice versa
</code>```

To get the book notes for a certain page:

```<code>@book.notes.where(["page_number = ?", page_number]) #where page_number is a variable, possibly a parameter
</code>```

However, I do think you need to think through how you're going to model your data. Marcel has a good point.

ContentLicense: CC BY-SA 3.0

Body:
I have a book model and a notes model. Each book can have many notes.

# note.rb
id | book_id | content | page_number | author_id |

I want to run a lot of queries like

Get all the notes for page 43 of a certain book

Show all the noted pages of a certain book

These types of queries seem to favor making a separate noted_pages model so that a book can have many noted_pages and each noted_page can have many notes. This is fine but my noted_pages table would effectively just have an id column and a page_number column which doesn't sit right with me.

Is there a more standard way to implement this kind of setup or is my thinking ok?

Body:
Both of these can be simple ARel queries, no scope is required

The latter one is a simple check of the existence of the notes collection:

@book.notes.empty? #if there are no notes, it'll return true and vice versa

To get the book notes for a certain page:

@book.notes.where(["page_number = ?", page_number]) #where page_number is a variable, possibly a parameter

However, I do think you need to think through how you're going to model your data. Marcel has a good point.


问:
How to validate select option for a Materialize dropdown?
I've got a basic select box using materializecss.

```<code><select id="type" name="type" required="required" class="validate">
    <option value="" disabled="true" selected="selected">Choose your option</option>
    <option value="general">General</option>
    <option value="tech">Tech</option>
    <option value="person">Personnel</option>
    <option value="resource">Resourcing</option>
</select>
<label data-error="Select an option">Type of Question</label>
</code>```

I want the user to select an option before being able to submit the form.

How can I get it to display the data-error for the label if user doesn't select an option?

答:
this worked better for me and JavaScript was not neccesary, just some simple CSS:</p>

```<code>select[required]:focus{
    outline: none !important;
}

select[required]{
    display: block;
    padding: 0;
    position: absolute;
    background: transparent;
    color: transparent;
    border: none;
    top: 0;
}
</code>```

Body:
I've got a basic select box using materializecss.

<select id="type" name="type" required="required" class="validate">
    <option value="" disabled="true" selected="selected">Choose your option</option>
    <option value="general">General</option>
    <option value="tech">Tech</option>
    <option value="person">Personnel</option>
    <option value="resource">Resourcing</option>
</select>
Type of Question

I want the user to select an option before being able to submit the form.

How can I get it to display the data-error for the label if user doesn't select an option?

Body:
this worked better for me and JavaScript was not neccesary, just some simple CSS:

select[required]:focus{
    outline: none !important;
}

select[required]{
    display: block;
    padding: 0;
    position: absolute;
    background: transparent;
    color: transparent;
    border: none;
    top: 0;
}

ContentLicense: CC BY-SA 4.0


问:
Liquid syntax error: Unexpected character during "sort"
I have this piece of code that executes a sort for this kind of structure:

```<code>items:
 0:
  date: '2018-01-02'
 1:
  date: '2019-02-02'
 2:
  date: '2016-03-04'

</code>```

Sort:

```<code>{% assign sorted = items.sort {|x,y| y[1].date <=> x[1].date} %}
</code>```

Based on: https://stackoverflow.com/a/5710429/2797942

When I run jekyll serve it returns Liquid Warning: Liquid syntax error (line 18): Unexpected character { in "{{items.sort {|x,y| y[1].date <=> x[1].date} }}

I'm quite new to Ruby and Jekyll, can someone help me out?

答:
Jekyll templates can't accept full Ruby. You can output a context variable, optionally modified by a Liquid filter; invoking sort method and passing a Ruby block is out of the question. Try instead:

```<code>{{ items | sort: "date" | reverse }}
</code>```

Body:
I have this piece of code that executes a sort for this kind of structure:

items:
 0:
  date: '2018-01-02'
 1:
  date: '2019-02-02'
 2:
  date: '2016-03-04'

Sort:

{% assign sorted = items.sort {|x,y| y[1].date <=> x[1].date} %}

Based on: https://stackoverflow.com/a/5710429/2797942

When I run jekyll serve it returns Liquid Warning: Liquid syntax error (line 18): Unexpected character { in "{{items.sort {|x,y| y[1].date <=> x[1].date} }}

I'm quite new to Ruby and Jekyll, can someone help me out?

Body:
Jekyll templates can't accept full Ruby. You can output a context variable, optionally modified by a Liquid filter; invoking sort method and passing a Ruby block is out of the question. Try instead:

{{ items | sort: "date" | reverse }}


问:
linking two plots to one drop down menu in Shiny
I am working on a shiny app and I have two plots that I would like to link to one selectInput. So the user selection will update both graphs.

Is there a way to achieve this?

my code

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

#ui
shinyUI(
  pageWithSidebar(
    headerPanel("NYC Flights Delays 2013"),
    sidebarPanel(
      selectInput("select", "Select a month",
                  choices = list("2013","January" ,"February",
                                 "March","April",
                                 "May", "June",
                                 "July","August",
                                 "Septemeber","October",
                                 "November","December")
      )),

    mainPanel(
      plotlyOutput("monthlyavg",width="900",height = "400px")
    )
    ))

#server
function(input, output){
  output$monthlyavg<-renderPlotly({
    if (input$select =="January") {
      #calculate avg delay for departures and arrivals each month
        average_delay_month<-flight%>%
        group_by(flight_month)%>%
        summarise(Average_Departure_Delay=mean(dep_delay[dep_delay>0]),Average_Arrival_Delay=mean(arr_delay[arr_delay>0]))
      #filtering according to month
      average_delay_month<-subset(average_delay_month,flight_month=="January")

      #average delay by month(January)
      c<-average_delay_month %>%gather("metrics", "value", -flight_month)%>%
        ggplot(aes(flight_month, value, group= metrics, fill = metrics)) +
        geom_bar(stat = "identity", width=.5, position = "dodge")+
        labs(title="Average Delay by Month", x="Flight Month",y="Average Delay in Minutes")
      print(c)

      #--January--#
      #--All Months Flight count--#
      flight$flight_month<-factor(flight$flight_month, levels=c("January", "February", "March", "April", "May",
                                                                "June","July","August",'September',"October","November","December"))
      #count number of flights per month
      flight_month_count<-setNames(aggregate(year~flight_month,data=flight,FUN=length),
                                   c('Month','Flight_Count'))
      flight_month_count<-subset(flight_month_count,Month=="January")
      #flight month_count_graph
      p<-ggplot(data=flight_month_count)+
        geom_bar(stat="identity",fill="#008080",aes(Month,Flight_Count),width=0.5)+
        labs(title="Total Number of Flights per Month",x="Flight Month",y="Number of Flights")
      print(p)
      }
</code>```

I tried adding the two graphs (c) and (p) under one renderPlotly but it doesn't seem to do the trick.

Thanks

答:
I tried adding the two graphs (c) and (p) under one renderPlotly but it doesn't seem to do the trick.

I would advise against this.

Option 1. Use two renderPlotly calls, with both depending on the same input$select

Option 2: Create a mydata <- reactive({...}) object with your data processing steps within. Then in your two separate renderPlotly calls, reference mydata(). This will be updated anytime a new selection in made.

Body:
I am working on a shiny app and I have two plots that I would like to link to one selectInput. So the user selection will update both graphs.

Is there a way to achieve this?

my code

library(shiny)
library(plotly)
library(dplyr)
library(tidyr)

#ui
shinyUI(
  pageWithSidebar(
    headerPanel("NYC Flights Delays 2013"),
    sidebarPanel(
      selectInput("select", "Select a month",
                  choices = list("2013","January" ,"February",
                                 "March","April",
                                 "May", "June",
                                 "July","August",
                                 "Septemeber","October",
                                 "November","December")
      )),

    mainPanel(
      plotlyOutput("monthlyavg",width="900",height = "400px")
    )
    ))

#server
function(input, output){
  output$monthlyavg<-renderPlotly({
    if (input$select =="January") {
      #calculate avg delay for departures and arrivals each month
        average_delay_month<-flight%>%
        group_by(flight_month)%>%
        summarise(Average_Departure_Delay=mean(dep_delay[dep_delay>0]),Average_Arrival_Delay=mean(arr_delay[arr_delay>0]))
      #filtering according to month
      average_delay_month<-subset(average_delay_month,flight_month=="January")

      #average delay by month(January)
      c<-average_delay_month %>%gather("metrics", "value", -flight_month)%>%
        ggplot(aes(flight_month, value, group= metrics, fill = metrics)) +
        geom_bar(stat = "identity", width=.5, position = "dodge")+
        labs(title="Average Delay by Month", x="Flight Month",y="Average Delay in Minutes")
      print(c)

      #--January--#
      #--All Months Flight count--#
      flight$flight_month<-factor(flight$flight_month, levels=c("January", "February", "March", "April", "May",
                                                                "June","July","August",'September',"October","November","December"))
      #count number of flights per month
      flight_month_count<-setNames(aggregate(year~flight_month,data=flight,FUN=length),
                                   c('Month','Flight_Count'))
      flight_month_count<-subset(flight_month_count,Month=="January")
      #flight month_count_graph
      p<-ggplot(data=flight_month_count)+
        geom_bar(stat="identity",fill="#008080",aes(Month,Flight_Count),width=0.5)+
        labs(title="Total Number of Flights per Month",x="Flight Month",y="Number of Flights")
      print(p)
      }

I tried adding the two graphs (c) and (p) under one renderPlotly but it doesn't seem to do the trick.

Thanks


问:
How much request is free with geocoding api?
I want to get the address from latitude/longitude using Google Geocoding API. For that, I want to know, how many no of hit can be done with a free account?

Bellow link showing the 2,500 requests per 24 hour period free.

Google Geocoding API, free?

Kindly clear me, it is still free hit exist with Google Geocoding API or not.
If no, then how many hits are free with this API?

答:
Upon setting up your billing account, you will be entitled to have one time $300 free credit (Usable for any Google Cloud Platform products) and a monthly recurring $200 free credit (Exclusive for Google Maps API only), the Geocoding API is currently priced at 0.005 USD, with that said, you may have the following requests as follows:

300 USD / 0.005 USD = 60,000 requests

200 USD / 0.005 = 40,000 requests

If you haven't used your one time $300 free credit, then you may have 100,000 geocoding requests for the first month, then for the succeeding months, you may have 40,000 geocoding requests that will be covered by the monthly recurring $200 free credit.

You may learn more about the pricing by visiting the pricing sheet

You may also use the Pricing Calculator if you'd wish to compute for other SKUs as well, note that this also take your free credit(monthly recurring $200 only) into account.


问:
Enforcing a Squash merge on Azure DevOps Pull Request using GitPullRequestCompletionOptions
I am attempting to use the Azure DevOps Services REST API to set the PR Completion Options to enforce a squash merge on a Pull Request.

Note: I can't set a branch policy to enforce a squash merge as I am testing certain conditions to see if a squash merge is required or not and attempting to enforce a squash as if the branch policy is set for that PR only.

When I make the following call:

```<code>PATCH https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullrequests/{pullRequestId}?api-version=5.0

{
  "completionOptions": {
    "squashMerge": true
  }
}
</code>```

The response shows the value is set

Yet when attempting to complete the request, I would expect the "Squash changes when merging" checkbox to be ticked and disabled.

If I leave the form as-is and complete the merge, no squash is performed.

If I set bypassPolicy to true, I still see no difference in completion options.

So in summary, I know that the call is successful as the response is coming back with the options set, but the changes don't seem to be coming through to the Pull Request in Azure DevOps.

答:
You could use a policy that enforces this.

If you go to branches in DevOps, select your branch -> policies you can allow only squash merges:

This should make all pull requests into the branch bound by the policy to be done using squash merge.

Here's how it works for Set auto-complete:

Body:
I am attempting to use the Azure DevOps Services REST API to set the PR Completion Options to enforce a squash merge on a Pull Request.

Note: I can't set a branch policy to enforce a squash merge as I am testing certain conditions to see if a squash merge is required or not and attempting to enforce a squash as if the branch policy is set for that PR only.

When I make the following call:

PATCH https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullrequests/{pullRequestId}?api-version=5.0

{
  "completionOptions": {
    "squashMerge": true
  }
}

The response shows the value is set

Yet when attempting to complete the request, I would expect the "Squash changes when merging" checkbox to be ticked and disabled.

If I leave the form as-is and complete the merge, no squash is performed.

If I set bypassPolicy to true, I still see no difference in completion options.

So in summary, I know that the call is successful as the response is coming back with the options set, but the changes don't seem to be coming through to the Pull Request in Azure DevOps.


问:
UITabBar isTranslucent adds an additional UITabBar?
I'm experiencing something very strange. If the property of my UITTabBar isTranslucent is set to false, it adds this weird double like (or a view? I don't know what it is really) above of the UITabBar.

```<code>tabBarController?.tabBar.isTranslucent = false
</code>```

If this property is set to true, the problem disappears. And it makes no sense.

This is the effect I see if it's set to false

答:
You haven't given a lot of context here, but I was faced with a similar problem and found a solution.

It's actually not the toolbar becoming higher, but the view above it not extending all of the way down to the tab bar. Now I don't know if you are using Storyboards or doing this programatically. In the child view of the UITabBarController you need to set Extend Edges -> Under Opaque Bars in the Storyboard or the property extendedLayoutIncludesOpaqueBars if you are doing it in code.

If you build this up with the storyboard, you can actually see the extra gap if you use an Opaque Tab Bar for your simulated metric on the Bottom Bar.

Body:
I'm experiencing something very strange. If the property of my UITTabBar isTranslucent is set to false, it adds this weird double like (or a view? I don't know what it is really) above of the UITabBar.

tabBarController?.tabBar.isTranslucent = false

If this property is set to true, the problem disappears. And it makes no sense.

This is the effect I see if it's set to false


问:
How to update module on generating services in angular8 in angular cli?
I am trying to generate the services and update app modules in cli.
My question is in angular 5.2 and angular-cli-1.7.2 i was using

```<code>ng g service test -m app.module
</code>```

But in angular 8 and angular-cli 8 I checked the documentation there is no option for the app module update from cli.
I can do it manually in app.module. But though to double check is there any option in cli.
Thank you in advance.

答:
It has been removed since angular 6, as the recommended way now is via providing a singleton service. https://angular.io/guide/singleton-services</p>

```<code>@Injectable({
  providedIn: 'root',
})
</code>```

Body:
I am trying to generate the services and update app modules in cli.
My question is in angular 5.2 and angular-cli-1.7.2 i was using

ng g service test -m app.module

But in angular 8 and angular-cli 8 I checked the documentation there is no option for the app module update from cli.
I can do it manually in app.module. But though to double check is there any option in cli.
Thank you in advance.

Body:
It has been removed since angular 6, as the recommended way now is via providing a singleton service. https://angular.io/guide/singleton-services

@Injectable({
  providedIn: 'root',
})


问:
How to change an IP address in a PCAP file to a string
I need to archive and share some PCAP files with people who don't know what the various IP addresses in the pcap refer to.

So I want to find a way to edit the PCAP files and change IP addresses so they appear as the fqdn or a random string in wireshark. e.g. "server.a.some.domain" or "serverA" instead of 192.168.x.x. That way people will understand the traffic flow without having to ask what each IP is.

I can achieve this in wireshark manually with the Name Resolution function, but I want to automate changing the PCAP files before I share them.

I tried bittwiste and tcprewrite but they seem to only support changing an IP address to another IP address, not a string.

e.g. this works

```<code>$ bittwiste -I a.pcap.file.pcap -O test.pcap -T ip -s 192.168.0.0,192.168.0.2
input file: a.pcap.file.pcap
output file: test.pcap

1771 packets (665162 bytes) written
</code>```

but this doesn't

```<code>$ bittwiste -I a.pcap.file.pcap -O test.pcap -T ip -s 192.168.0.0,serverA
bittwiste: invalid source IP address
</code>```

Anyone know if this is possible and how to do it?

thanks

答:
This is not as trivial as it seems. The names you want to replace are only inside the application data, i.e. typically in DNS requests and responses, as part of the TLS handshake (SNI in ClientHello, CN/SAN in server certificate), in the Host field of a HTTP request header ...

While you might try to simply string-replace all such names with something else this would break the sequence numbers in the TCP connections unless you replace it with something of exactly the same length. Even then it would make the TCP checksums invalid, would make signatures on the certificates invalid, ... and in case of DNS a simple string replace would not even find all the names since they might be encoded in DNS and are not just inside the DNS packets as a plain string.

Body:
I need to archive and share some PCAP files with people who don't know what the various IP addresses in the pcap refer to.

So I want to find a way to edit the PCAP files and change IP addresses so they appear as the fqdn or a random string in wireshark. e.g. "server.a.some.domain" or "serverA" instead of 192.168.x.x. That way people will understand the traffic flow without having to ask what each IP is.

I can achieve this in wireshark manually with the Name Resolution function, but I want to automate changing the PCAP files before I share them.

I tried bittwiste and tcprewrite but they seem to only support changing an IP address to another IP address, not a string.

e.g. this works

$ bittwiste -I a.pcap.file.pcap -O test.pcap -T ip -s 192.168.0.0,192.168.0.2
input file: a.pcap.file.pcap
output file: test.pcap

1771 packets (665162 bytes) written

but this doesn't

$ bittwiste -I a.pcap.file.pcap -O test.pcap -T ip -s 192.168.0.0,serverA
bittwiste: invalid source IP address

Anyone know if this is possible and how to do it?

thanks


问:
How to wrap or truncate long strings in a Material-UI ExpansionPanelSummary
I want to create an ExpansionPanel where the summary might be a quite long string of unbroken characters (i.e. no hyphens, no spaces).

When I tried it out, the ExpansionPanelSummary component displays poorly on a narrow width display - it overwrites the button and overflows off-screen.

Here is my example, forked from the ExpansionPanel Material-UI demo, shrink the width of the output frame and you can see the email addresses don't wrap and look ugly: https://codesandbox.io/s/wqm5k3vmyw

I've tried using nowrap on the Typography to get it to clip (my preferred solution):

```<code><ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
  <Typography nowrap className={classes.heading}>
    areallyreallylongaddress@email.example.com
  </Typography>
</ExpansionPanelSummary>
</code>```

I've also tried adding a style overflowWrap: "break-word" to force it to wrap anywhere, not just on hyphens or whitespace.

The best I've been able to do is to get the text to not overflow outside the expansion panel itself by adding style={{ textOverflow: "ellipsis", overflow: "hidden" }} to the ExpansionPanel (see the second example from the linked example).

Ideally, I'd like it to function by truncating from the right of the context, showing an ellipsis and not overwriting the expand icon.

How can I do that with ExpansionPanel?

Failing that, how can I just force it to word-wrap?

I'm using material-UI v3.4.0 and the problem is visible on Chrome and Firefox.

答:
Suggest that you wrap your Typography element with a div that is styled with textOverflow: "ellipsis", for example:</p>

```<code><div style={{overflow: "hidden", textOverflow: "ellipsis", width: '11rem'}}>
  <Typography nowrap className={classes.heading}>
    areallyreallylongaddress@email.example.com
  </Typography>
</div>
</code>```

Body:
I want to create an ExpansionPanel where the summary might be a quite long string of unbroken characters (i.e. no hyphens, no spaces).

When I tried it out, the ExpansionPanelSummary component displays poorly on a narrow width display - it overwrites the button and overflows off-screen.

Here is my example, forked from the ExpansionPanel Material-UI demo, shrink the width of the output frame and you can see the email addresses don't wrap and look ugly: https://codesandbox.io/s/wqm5k3vmyw

I've tried using nowrap on the Typography to get it to clip (my preferred solution):

<ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
  <Typography nowrap className={classes.heading}>
    areallyreallylongaddress@email.example.com
  </Typography>
</ExpansionPanelSummary>

I've also tried adding a style overflowWrap: "break-word" to force it to wrap anywhere, not just on hyphens or whitespace.

The best I've been able to do is to get the text to not overflow outside the expansion panel itself by adding style={{ textOverflow: "ellipsis", overflow: "hidden" }} to the ExpansionPanel (see the second example from the linked example).

Ideally, I'd like it to function by truncating from the right of the context, showing an ellipsis and not overwriting the expand icon.

How can I do that with ExpansionPanel?

Failing that, how can I just force it to word-wrap?

I'm using material-UI v3.4.0 and the problem is visible on Chrome and Firefox.

Body:
Suggest that you wrap your Typography element with a div that is styled with textOverflow: "ellipsis", for example:

<div style={{overflow: "hidden", textOverflow: "ellipsis", width: '11rem'}}>
  <Typography nowrap className={classes.heading}>
    areallyreallylongaddress@email.example.com
  </Typography>
</div>


问:
How to generate Azure Active Directory (AAD) authentication token for Graph API without interactive login screen for console/native application?
How to generate Azure Active Directory (AAD) authentication token for Graph API without interactive login screen for console/native application?

Details:
I am using Graph API to read emails with Azure Active Directory (AAD) with ‘’Delegated’’ permissions.

”Application” permission allows a user to read other mailboxes and there is no admin consent for this approach due to security concerns, so I am using ‘’Delegated’’ permissions.

My console/native application is registered to AAD.

Since AAD generates OAuth Authentication token for a specific account using:
1.  Client ID
2.  Tenant ID
3.  Client Secret (Key/password for the application)
4.  Login credentials of a specific account.

I can generate a token using an interactive login screen.

However, I want a mechanism where I can generate AAD token for Graph API (resource) without an interactive login screen within code using C# or.NET

答:
It worked for me with the below code. I am able to recieve the token now with the user credentials and can read the mailbox.</p>

```<code>private static async Task<string> GetToken()
    {
        string authority = "https://login.microsoftonline.com/{tenantId}";
        string resource = "https://graph.microsoft.com";
        string userName = "xxxxxxxxx";
        string password = "xxxxxxx";
        string clientId = "Your Client ID (GUID)";

        UserPasswordCredential userPasswordCredential = new UserPasswordCredential(userName, password);

        AuthenticationContext authenticationContext = new AuthenticationContext(authority);
        var result = AuthenticationContextIntegratedAuthExtensions.AcquireTokenAsync(authenticationContext, resource, clientId, userPasswordCredential).Result;

        return result.AccessToken;
    }
</code>```

Body:
It worked for me with the below code. I am able to recieve the token now with the user credentials and can read the mailbox.

private static async Task<string> GetToken()
    {
        string authority = "https://login.microsoftonline.com/{tenantId}";
        string resource = "https://graph.microsoft.com";
        string userName = "xxxxxxxxx";
        string password = "xxxxxxx";
        string clientId = "Your Client ID (GUID)";

        UserPasswordCredential userPasswordCredential = new UserPasswordCredential(userName, password);

        AuthenticationContext authenticationContext = new AuthenticationContext(authority);
        var result = AuthenticationContextIntegratedAuthExtensions.AcquireTokenAsync(authenticationContext, resource, clientId, userPasswordCredential).Result;

        return result.AccessToken;
    }


问:
Fluent Configuration, ignore property based on decorated attribute
I have a need to ignore properties based on attribute.

Below you will see some code (a small extract of my project) and you will get a feel for what I am trying to accomplish.

What I am struggling with is to add this rule to my bhibernate configureation, ie, if a property has a [IgnoreProperty] attribute flientnhibernate should not include it in the schema being generated.

I would like to have this as generic as possible so I do not have to create a class map for every entity.

Is there any way to include this sort of functionality directly into the Configuration? if so, I would really appreciate an example

```<code>public class Person
{
    public virtual string Name { get; set; }
    public virtual string Surname { get; set; }

    [IgnoreProperty]
    public string FullName
    {
        get { return string.Format("{0} {1}", this.Name, this.Surname); }
    }
}

public class IgnorePropertyAttribute : Attribute
{
}

public class SessionManager
{
    private static ISessionFactory GetFactory()
    {
        return
        Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.UsingFile(Path.Combine(@"C:\temp","MyDatabaseName.db")))
            .Mappings(
            m =>
            m.AutoMappings.Add(AutoMap.AssemblyOf<Person>(t => t.Namespace.StartsWith(typeof(Person).Namespace))))
            .ExposeConfiguration(BuildSchema)
            .BuildSessionFactory();
    }
}
</code>```

答:
The following code will prevent the column from generating in your database. Don't forget to add the configuration to your mapping.</p>

```<code>public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Member member)
    {
        if (member.MemberInfo.GetCustomAttributes(typeof(IgnorePropertyAttribute), true).Length > 0)
        {
            return false;
        }
        return base.ShouldMap(member);
    }
}
</code>```

Body:
I have a need to ignore properties based on attribute.

Below you will see some code (a small extract of my project) and you will get a feel for what I am trying to accomplish.

What I am struggling with is to add this rule to my bhibernate configureation, ie, if a property has a [IgnoreProperty] attribute flientnhibernate should not include it in the schema being generated.

I would like to have this as generic as possible so I do not have to create a class map for every entity.

Is there any way to include this sort of functionality directly into the Configuration? if so, I would really appreciate an example

public class Person
{
    public virtual string Name { get; set; }
    public virtual string Surname { get; set; }

    [IgnoreProperty]
    public string FullName
    {
        get { return string.Format("{0} {1}", this.Name, this.Surname); }
    }
}

public class IgnorePropertyAttribute : Attribute
{
}

public class SessionManager
{
    private static ISessionFactory GetFactory()
    {
        return
        Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.UsingFile(Path.Combine(@"C:\temp","MyDatabaseName.db")))
            .Mappings(
            m =>
            m.AutoMappings.Add(AutoMap.AssemblyOf<Person>(t => t.Namespace.StartsWith(typeof(Person).Namespace))))
            .ExposeConfiguration(BuildSchema)
            .BuildSessionFactory();
    }
}

Body:
The following code will prevent the column from generating in your database. Don't forget to add the configuration to your mapping.

public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Member member)
    {
        if (member.MemberInfo.GetCustomAttributes(typeof(IgnorePropertyAttribute), true).Length > 0)
        {
            return false;
        }
        return base.ShouldMap(member);
    }
}


问:
Laravel Auth::guard('employee')->attempt not working
For my website I want to have 2 guards: employee and customer. When I login or register, I always get 302. When I do the login of an employee:

```<code>Auth::guard('employee')->attempt(['username' => $request->username, 'password' => $request->password])
</code>```

I get false. I have checked $request and the values are right. When I do the same thing without the guard, I get an error that he can't find username in users. So he uses the guard to search in the right column but still, he doesn't find it there. The values of username and password are in the database. But, when I seeded it, it wasn't hashed because I'm just a student and it's all in test environment. Could that be a problem? I haven't posted here the middleware and all that stuff because when I do dd() of the line code above, I get "false" so is there a problem that the atttempt or does it really need middleware this line of code?

My employee model looks like this:

```<code>class Employee extends Authenticatable {

use Notifiable;

protected $guard = 'employee';

protected $fillable = [
    'name', 'username', 'password',
];

protected $hidden = [
    'password', 'remember_token',
]; }
</code>```

The auth.php (short version)

```<code>'guards' => [
    'employee' => [
        'driver' => 'session',
        'provider' => 'employees',
    ],
    'customer' => [
        'driver' => 'session',
        'provider' => 'customers',
    ]
],
 'providers' => [
    'employees' => [
        'driver' => 'eloquent',
        'model' => App\Employee::class,
    ],
    'customers' => [
        'driver' => 'eloquent',
        'model' => App\Customer::class,
    ],
</code>```

My loginController

```<code>public function __construct()
{
    $this->middleware('guest')->except('logout');
    $this->middleware('guest:employee')->except('logout');
    $this->middleware('guest:customer')->except('logout');
}

public function adminLogin(Request $request)
{
    $this->validate($request, [
        'username' => 'required',
        'password' => 'required|min:6'
    ]);

    if (Auth::guard('employee')->attempt(['username' => $request->username, 'password' => $request->password])) {
        return redirect()->intended('/employee/overview');
    }

    return back()->withInput($request->only('username'));
}
</code>```

I know that the question is asked a lot but I have searched a lot didn't find the solution and asked my web teacher but he also didn't find the problem. I could maybe use somethings with roles but I find it stupid that I cannot to it. I just want to learn to use guards correctly.

Thank you in advance!

答:
In login controller change your code as per below:</p>

```<code>public function adminLogin(Request $request)
{
    $this->validate($request, [
        'username' => 'required',
        'password' => 'required|min:6'
    ]);

    if (Auth::guard('employee')->attempt(['username' => $request->input('username'), 'password' => $request->input('password')])) {
        return redirect()->intended('/employee/overview');
    }

    return back()->withInput($request->only('username'));
}
</code>```

Body:
For my website I want to have 2 guards: employee and customer. When I login or register, I always get 302. When I do the login of an employee:

Auth::guard('employee')->attempt(['username' => $request->username, 'password' => $request->password])

I get false. I have checked $request and the values are right. When I do the same thing without the guard, I get an error that he can't find username in users. So he uses the guard to search in the right column but still, he doesn't find it there. The values of username and password are in the database. But, when I seeded it, it wasn't hashed because I'm just a student and it's all in test environment. Could that be a problem? I haven't posted here the middleware and all that stuff because when I do dd() of the line code above, I get "false" so is there a problem that the atttempt or does it really need middleware this line of code?

My employee model looks like this:

class Employee extends Authenticatable {

use Notifiable;

protected $guard = 'employee';

protected $fillable = [
    'name', 'username', 'password',
];

protected $hidden = [
    'password', 'remember_token',
]; }

The auth.php (short version)

'guards' => [
    'employee' => [
        'driver' => 'session',
        'provider' => 'employees',
    ],
    'customer' => [
        'driver' => 'session',
        'provider' => 'customers',
    ]
],
 'providers' => [
    'employees' => [
        'driver' => 'eloquent',
        'model' => App\Employee::class,
    ],
    'customers' => [
        'driver' => 'eloquent',
        'model' => App\Customer::class,
    ],

My loginController

public function __construct()
{
    $this->middleware('guest')->except('logout');
    $this->middleware('guest:employee')->except('logout');
    $this->middleware('guest:customer')->except('logout');
}

public function adminLogin(Request $request)
{
    $this->validate($request, [
        'username' => 'required',
        'password' => 'required|min:6'
    ]);

    if (Auth::guard('employee')->attempt(['username' => $request->username, 'password' => $request->password])) {
        return redirect()->intended('/employee/overview');
    }

    return back()->withInput($request->only('username'));
}

I know that the question is asked a lot but I have searched a lot didn't find the solution and asked my web teacher but he also didn't find the problem. I could maybe use somethings with roles but I find it stupid that I cannot to it. I just want to learn to use guards correctly.

Thank you in advance!

Body:
In login controller change your code as per below:

public function adminLogin(Request $request)
{
    $this->validate($request, [
        'username' => 'required',
        'password' => 'required|min:6'
    ]);

    if (Auth::guard('employee')->attempt(['username' => $request->input('username'), 'password' => $request->input('password')])) {
        return redirect()->intended('/employee/overview');
    }

    return back()->withInput($request->only('username'));
}


问:
Python OpenCV: Image Denoising for Text Recognition
I have this set of images I want to de-noise in order to run OCR on it:

I am trying to read the 7810 from the image.

I have tried

```<code>cv2.threshold(img, 128, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
cv2.fastNlMeansDenoising(img,None,60,10,20)
</code>```

and some morphological expressions but none seem to work to clear this image sufficiently.

Any recommendations on how to filter this image sufficiently that I could run OCR or some ML detection scripts on this like pytesseract?

答:
You could begin by using a Median filter to remove the salt & pepper noise:

```<code>cv2.medianBlur(source, 3)
</code>```

Then try out the Otsu thresholding as you have done. This might not end up being the solution, but it makes it easier for the text detection algorithm to work on the image

Body:
I have this set of images I want to de-noise in order to run OCR on it:

I am trying to read the 7810 from the image.

I have tried

cv2.threshold(img, 128, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
cv2.fastNlMeansDenoising(img,None,60,10,20)

and some morphological expressions but none seem to work to clear this image sufficiently.

Any recommendations on how to filter this image sufficiently that I could run OCR or some ML detection scripts on this like pytesseract?

Body:
You could begin by using a Median filter to remove the salt & pepper noise:

cv2.medianBlur(source, 3)

Then try out the Otsu thresholding as you have done. This might not end up being the solution, but it makes it easier for the text detection algorithm to work on the image


问:
Run Stored Procedure in SQL Developer?
I am trying to run a stored procedure that has multiple in and out parameters. The procedure can only be viewed in my Connections panel by navigating

```<code>Other Users | <user> | Packages | <package> | <procedure>
</code>```

If I right click , the menu items are "Order Members By..." and "Create Unit Test" (greyed out). The ability to "Run" the procedure does not seem possible when it's accessed by user.

I have been trying to find an example of how to create an anonymous block so that I can run the procedure as a SQL file, but haven't found anything that works.

Does anyone know how I can execute this procedure from SQL Developer? I am using Version 2.1.1.64.

EDIT 1:

The procedure I want to call has this signature:

```<code>user.package.procedure(
   p_1 IN  NUMBER,
   p_2 IN  NUMBER,
   p_3 OUT VARCHAR2,
   p_4 OUT VARCHAR2,
   p_5 OUT VARCHAR2,
   p_6 OUT NUMBER)
</code>```

If I write my anonymous block like this:

```<code>DECLARE
   out1 VARCHAR2(100);
   out2 VARCHAR2(100);
   out3 VARCHAR2(100);
   out4 NUMBER(100);
BEGIN
   EXECUTE user.package.procedure (33,89, :out1, :out2, :out3, :out4);
END;
</code>```

I get the error:

```<code>Bind Varialbe "out1" is NOT DECLCARED
anonymous block completed
</code>```

I've tried initializing the out* variables:

```<code>   out1 VARCHAR2(100) := '';
</code>```

but get the same error:

EDIT 2:

Based on Alex's answer, I tried removing the colons from in front of the params and get this:

```<code>Error starting at line 1 in command:
DECLARE
   out1 VARCHAR2(100);
   out2 VARCHAR2(100);
   out3 VARCHAR2(100);
   out4 NUMBER(100);
BEGIN
   EXECUTE user.package.procedure (33,89, out1, out2, out3, out4);
END;
Error report:
ORA-06550: line 13, column 17:
PLS-00103: Encountered the symbol "USER" when expecting one of the following:

   := . ( @ % ; immediate
The symbol ":=" was substituted for "USER" to continue.
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:
</code>```

答:
```<code>--for setting buffer size needed most of time to avoid `anonymous block completed` message
set serveroutput on size 30000;

-- declaration block in case output need to catch
DECLARE
--declaration for in and out parameter
  V_OUT_1 NUMBER;
  V_OUT_2 VARCHAR2(200);
BEGIN

--your stored procedure name
   schema.package.procedure(
  --declaration for in and out parameter
    V_OUT_1 => V_OUT_1,
    V_OUT_2 => V_OUT_2
  );
  V_OUT_1 := V_OUT_1;
  V_OUT_2 := V_OUT_2;
  -- console output, no need to open DBMS OUTPUT seperatly
  -- also no need to print each output on seperat line
  DBMS_OUTPUT.PUT_LINE('Ouput => ' || V_OUT_1 || ': ' || V_OUT_2);
END;
</code>```

Title: Run Stored Procedure in SQL Developer?

Body:
I am trying to run a stored procedure that has multiple in and out parameters. The procedure can only be viewed in my Connections panel by navigating

Other Users | <user> | Packages | <package> | <procedure>

If I right click , the menu items are "Order Members By..." and "Create Unit Test" (greyed out). The ability to "Run" the procedure does not seem possible when it's accessed by user.

I have been trying to find an example of how to create an anonymous block so that I can run the procedure as a SQL file, but haven't found anything that works.

Does anyone know how I can execute this procedure from SQL Developer? I am using Version 2.1.1.64.

EDIT 1:

The procedure I want to call has this signature:

user.package.procedure(
   p_1 IN  NUMBER,
   p_2 IN  NUMBER,
   p_3 OUT VARCHAR2,
   p_4 OUT VARCHAR2,
   p_5 OUT VARCHAR2,
   p_6 OUT NUMBER)

If I write my anonymous block like this:

DECLARE
   out1 VARCHAR2(100);
   out2 VARCHAR2(100);
   out3 VARCHAR2(100);
   out4 NUMBER(100);
BEGIN
   EXECUTE user.package.procedure (33,89, :out1, :out2, :out3, :out4);
END;

I get the error:

Bind Varialbe "out1" is NOT DECLCARED
anonymous block completed

I've tried initializing the out* variables:

   out1 VARCHAR2(100) := '';

but get the same error:

EDIT 2:

Based on Alex's answer, I tried removing the colons from in front of the params and get this:

Error starting at line 1 in command:
DECLARE
   out1 VARCHAR2(100);
   out2 VARCHAR2(100);
   out3 VARCHAR2(100);
   out4 NUMBER(100);
BEGIN
   EXECUTE user.package.procedure (33,89, out1, out2, out3, out4);
END;
Error report:
ORA-06550: line 13, column 17:
PLS-00103: Encountered the symbol "USER" when expecting one of the following:

   := . ( @ % ; immediate
The symbol ":=" was substituted for "USER" to continue.
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:


问:
RegEx for capturing numbers in parentheses
Example

```<code>Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]
</code>```

I want to get 15.7 from Alarm Level 1 and -12.7 from Alarm Level 2.  I tried to use \((.*?)\) but it get both D1 and 15.7 in Alarm Level 1.

答:
Here we can try to just collect the digits using a simple capturing group:

```<code>\(([0-9-.]+)\)
</code>```

TEST

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"\(([0-9\-\.]+)\)";
        string input = @"Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}
</code>```

const regex = /\(([0-9-.]+)\)/gm;
const str = `Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

Body:
Example

Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]

I want to get 15.7 from Alarm Level 1 and -12.7 from Alarm Level 2.  I tried to use \((.*?)\) but it get both D1 and 15.7 in Alarm Level 1.

Body:
Here we can try to just collect the digits using a simple capturing group:

\(([0-9-.]+)\)

TEST

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"\(([0-9\-\.]+)\)";
        string input = @"Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

const regex = /\(([0-9-.]+)\)/gm;
const str = `Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

DEMO

RegEx Circuit

jex.im visualizes regular expressions:


问:
How can I create a Fluent NHibernate Convention that ignores properties that don't have setters
I'm looking for a FluentNH (Fluent NHibernate) convention or configuration that ignores all properties that have no setter:

It would still map these:

```<code>public class foo{
  public virtual int bar {get; private set;}
}
</code>```

And omit these:

```<code>public class foo{
  public virtual int fizz{get;private set;}
  public virtual int bar{get {return fizz;}} //<-------
}
</code>```

答:
Another way is to use an attribute.</p>

```<code>public class MyEntity
{
    [NotMapped]
    public bool A => true;
}

public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Member member)
    {
        if (member.MemberInfo.GetCustomAttributes(typeof(NotMappedAttribute), true).Length > 0)
        {
            return false;
        }
        return base.ShouldMap(member);
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm looking for a FluentNH (Fluent NHibernate) convention or configuration that ignores all properties that have no setter:

It would still map these:

public class foo{
  public virtual int bar {get; private set;}
}

And omit these:

public class foo{
  public virtual int fizz{get;private set;}
  public virtual int bar{get {return fizz;}} //<-------
}

Body:
Another way is to use an attribute.

public class MyEntity
{
    [NotMapped]
    public bool A => true;
}

public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Member member)
    {
        if (member.MemberInfo.GetCustomAttributes(typeof(NotMappedAttribute), true).Length > 0)
        {
            return false;
        }
        return base.ShouldMap(member);
    }
}


问:
Mounting Volume Using Docker - No Files Being Added
I am trying to mount a volume using docker command on WSL (Bash). But the files and folders I need to mount do not show up to Docker, hence, when I run the docker command it says file not found.

I am trying to simply use the Alpine Container to see if I can make it work. But it also fails to recognize all the files/folders I have on the dir I run it on.

The following command:

docker run --rm -v /c/Users/alexandrec/Desktop/AWS_Layers/pandas:/data alpine ls /data

Returns:

test

And this command:

/mnt/c/Users/alexandrec/Desktop/AWS_Layers/pandas$ ls -la

Returns:

```<code>-total 2238
-drwxrwxrwx 0 root root 512 May 29 15:22 .
-drwxrwxrwx 0 root root 512 May 29 14:56 ..
-rwxrwxrwx 1 root root 254 May 28 16:52 get_layer_packages.sh
-rwxrwxrwx 1 root root  85 May 29 11:31 my_module.py
-drwxrwxrwx 0 root root 512 May 29 15:22 New folder
-drwxrwxrwx 0 root root 512 May 28 16:49 python
-rwxrwxrwx 1 root root  28 May 28 14:56 requirements.txt
-drwxrwxrwx 0 root root 512 May 29 14:56 test
-drwxrwxrwx 0 root root 512 May 28 20:30 var
</code>```

Somehow most folders/files in the DIR do not get mounted only test.

Eventually I want to be able to run this:

docker run --rm -v "$PWD":/var/task lambci/lambda:python3.6 my_module.my_handler

Which currently returns:

```<code>START RequestId: d3df9063-56ea-4c56-b097-2932c633d74f Version: $LATEST
Unable to import module 'my_module': No module named 'my_module'
END RequestId: d3df9063-56ea-4c56-b097-2932c633d74f
REPORT RequestId: d3df9063-56ea-4c56-b097-2932c633d74f Duration: 0 ms Billed Duration: 100 ms Memory Size: 1536 MB Max Memory Used: 19 MB

{"errorMessage": "Unable to import module 'my_module'"}
</code>```

I just don't seem to figure out if this is a permission problem or something related to Windows/Docker/Linux interactions.

The following link shows my bash terminal commands: https://imgur.com/4tqpdaR

答:
Okay, it was due to the Windows Credentials, they needed to be updated. In the Docker App,
Settings -> Shared Drives -> Reset Credentials

Run as Administrator just to make sure.

Body:
I am trying to mount a volume using docker command on WSL (Bash). But the files and folders I need to mount do not show up to Docker, hence, when I run the docker command it says file not found.

I am trying to simply use the Alpine Container to see if I can make it work. But it also fails to recognize all the files/folders I have on the dir I run it on.

The following command:

docker run --rm -v /c/Users/alexandrec/Desktop/AWS_Layers/pandas:/data alpine ls /data

Returns:

test

And this command:

/mnt/c/Users/alexandrec/Desktop/AWS_Layers/pandas$ ls -la

Returns:

-total 2238
-drwxrwxrwx 0 root root 512 May 29 15:22 .
-drwxrwxrwx 0 root root 512 May 29 14:56 ..
-rwxrwxrwx 1 root root 254 May 28 16:52 get_layer_packages.sh
-rwxrwxrwx 1 root root  85 May 29 11:31 my_module.py
-drwxrwxrwx 0 root root 512 May 29 15:22 New folder
-drwxrwxrwx 0 root root 512 May 28 16:49 python
-rwxrwxrwx 1 root root  28 May 28 14:56 requirements.txt
-drwxrwxrwx 0 root root 512 May 29 14:56 test
-drwxrwxrwx 0 root root 512 May 28 20:30 var

Somehow most folders/files in the DIR do not get mounted only test.

Eventually I want to be able to run this:

docker run --rm -v "$PWD":/var/task lambci/lambda:python3.6 my_module.my_handler

Which currently returns:

START RequestId: d3df9063-56ea-4c56-b097-2932c633d74f Version: $LATEST
Unable to import module 'my_module': No module named 'my_module'
END RequestId: d3df9063-56ea-4c56-b097-2932c633d74f
REPORT RequestId: d3df9063-56ea-4c56-b097-2932c633d74f Duration: 0 ms Billed Duration: 100 ms Memory Size: 1536 MB Max Memory Used: 19 MB

{"errorMessage": "Unable to import module 'my_module'"}

I just don't seem to figure out if this is a permission problem or something related to Windows/Docker/Linux interactions.

The following link shows my bash terminal commands: https://imgur.com/4tqpdaR


问:
Problem with custom control that depends on several other dlls
I have created a custom button (you know, with all that eye-candy stuff etc). That control is based on several other dlls because i want to make set of controls that have the same base (i had already created progressbar, label and button).

But there's a problem - when i import reference to my button to some other project (so i can use my button as a regular button) i have to manually import all those dlls my button depends on! Is there a way to automatically import all needed dlls (references) whenever i import my button?
You know - when i drag my control from toolbox on to form, I want that C# automatically loads ALL dlls that added control depends on. Is there a way to do it?

答:
Right click the reference -> Properties -> set Copy Local = True

If even with this, the dlls is not being copied, them you're probably referencing them in the GAC. You'll have to remove those GAC references...

See http://msdn.microsoft.com/en-us/library/wkze6zky(v=vs.80).aspx


问:
Do I need to use Shared Preferences if I want to retrieve data of the user after the user login?
I am currently learning to develop a mobile application using Android Studio. I have successfully done for the login activity. I would like to know whether I have to use Shared Preferences if I want to retrieve the data of the user after they login ?</p>

答:
To store user data, the best way is to set them in a user model like below:

```<code>public class User {

private int user_isd;
private long post_count;
private long follower_count;
private long following_count;
private String user_email;
private String user_tag;
private String user_register_type;
private String user_mobile;
private String user_picture;
private String user_name;
private String user_bio;
private String user_gender;
private String user_latitude;
private String user_longitude;
private String user_location_name;
private String user_skills;
private int is_follow;
private String token;
private boolean isLoggedIn;

public User() {
}

public String getUser_email() {
    return user_email;
}

public void setUser_email(String user_email) {
    this.user_email = user_email;
}

public String getUser_tag() {
    return user_tag;
}

public void setUser_tag(String user_tag) {
    this.user_tag = user_tag;
}

public String getUser_mobile() {
    return user_mobile;
}

public void setUser_mobile(String user_mobile) {
    this.user_mobile = user_mobile;
}

public String getUser_name() {
    return user_name;
}

public void setUser_name(String user_name) {
    this.user_name = user_name;
}

public String getUser_bio() {
    return user_bio;
}

public void setUser_bio(String user_bio) {
    this.user_bio = user_bio;
}

public String getUser_gender() {
    return user_gender;
}

public void setUser_gender(String user_gender) {
    this.user_gender = user_gender;
}

public int getUser_isd() {
    return user_isd;
}

public void setUser_isd(int user_isd) {
    this.user_isd = user_isd;
}

public String getToken() {
    return token;
}

public void setToken(String token) {
    this.token = token;
}

public int getIs_follow() {
    return is_follow;
}

public void setIs_follow(int is_follow) {
    this.is_follow = is_follow;
}

public String getUser_picture() {
    return user_picture;
}

public void setUser_picture(String user_picture) {
    this.user_picture = user_picture;
}

public String getUser_latitude() {
    return user_latitude;
}

public void setUser_latitude(String user_latitude) {
    this.user_latitude = user_latitude;
}

public String getUser_longitude() {
    return user_longitude;
}

public void setUser_longitude(String user_longitude) {
    this.user_longitude = user_longitude;
}

public String getUser_location_name() {
    return user_location_name;
}

public void setUser_location_name(String user_location_name) {
    this.user_location_name = user_location_name;
}

public String getUser_skills() {
    return user_skills;
}

public void setUser_skills(String user_skills) {
    this.user_skills = user_skills;
}

public long getPost_count() {
    return post_count;
}

public void setPost_count(long post_count) {
    this.post_count = post_count;
}

public long getFollower_count() {
    return follower_count;
}

public void setFollower_count(long follower_count) {
    this.follower_count = follower_count;
}

public long getFollowing_count() {
    return following_count;
}

public void setFollowing_count(long following_count) {
    this.following_count = following_count;
}

public String getUser_register_type() {
    return user_register_type;
}

public void setUser_register_type(String user_register_type) {
    this.user_register_type = user_register_type;
}

public boolean isLoggedIn() {
    return isLoggedIn;
}

public void setLoggedIn(boolean loggedIn) {
    isLoggedIn = loggedIn;
}

@Override
public String toString() {
    return "ClassPojo [user_email = " + user_email + ", user_tag = " + user_tag + ", user_isd = " + user_isd + ", user_mobile = " + user_mobile + ", user_picture = " + user_picture + ", following_count = " + following_count + ", user_name = " + user_name + ", user_bio = " + user_bio + ", user_gender = " + user_gender + ", post_count = " + post_count + ", follower_count = " + follower_count + "]";
}
</code>```

}

Then you can store that model in Sqlite Database Table or you can use a Room ORM Database also.
Shared Preference is used to store single values. But in case you have multiple values for user, you need to store that in database.

Body:
To store user data, the best way is to set them in a user model like below:

public class User {

private int user_isd;
private long post_count;
private long follower_count;
private long following_count;
private String user_email;
private String user_tag;
private String user_register_type;
private String user_mobile;
private String user_picture;
private String user_name;
private String user_bio;
private String user_gender;
private String user_latitude;
private String user_longitude;
private String user_location_name;
private String user_skills;
private int is_follow;
private String token;
private boolean isLoggedIn;

public User() {
}

public String getUser_email() {
    return user_email;
}

public void setUser_email(String user_email) {
    this.user_email = user_email;
}

public String getUser_tag() {
    return user_tag;
}

public void setUser_tag(String user_tag) {
    this.user_tag = user_tag;
}

public String getUser_mobile() {
    return user_mobile;
}

public void setUser_mobile(String user_mobile) {
    this.user_mobile = user_mobile;
}

public String getUser_name() {
    return user_name;
}

public void setUser_name(String user_name) {
    this.user_name = user_name;
}

public String getUser_bio() {
    return user_bio;
}

public void setUser_bio(String user_bio) {
    this.user_bio = user_bio;
}

public String getUser_gender() {
    return user_gender;
}

public void setUser_gender(String user_gender) {
    this.user_gender = user_gender;
}

public int getUser_isd() {
    return user_isd;
}

public void setUser_isd(int user_isd) {
    this.user_isd = user_isd;
}

public String getToken() {
    return token;
}

public void setToken(String token) {
    this.token = token;
}

public int getIs_follow() {
    return is_follow;
}

public void setIs_follow(int is_follow) {
    this.is_follow = is_follow;
}

public String getUser_picture() {
    return user_picture;
}

public void setUser_picture(String user_picture) {
    this.user_picture = user_picture;
}

public String getUser_latitude() {
    return user_latitude;
}

public void setUser_latitude(String user_latitude) {
    this.user_latitude = user_latitude;
}

public String getUser_longitude() {
    return user_longitude;
}

public void setUser_longitude(String user_longitude) {
    this.user_longitude = user_longitude;
}

public String getUser_location_name() {
    return user_location_name;
}

public void setUser_location_name(String user_location_name) {
    this.user_location_name = user_location_name;
}

public String getUser_skills() {
    return user_skills;
}

public void setUser_skills(String user_skills) {
    this.user_skills = user_skills;
}

public long getPost_count() {
    return post_count;
}

public void setPost_count(long post_count) {
    this.post_count = post_count;
}

public long getFollower_count() {
    return follower_count;
}

public void setFollower_count(long follower_count) {
    this.follower_count = follower_count;
}

public long getFollowing_count() {
    return following_count;
}

public void setFollowing_count(long following_count) {
    this.following_count = following_count;
}

public String getUser_register_type() {
    return user_register_type;
}

public void setUser_register_type(String user_register_type) {
    this.user_register_type = user_register_type;
}

public boolean isLoggedIn() {
    return isLoggedIn;
}

public void setLoggedIn(boolean loggedIn) {
    isLoggedIn = loggedIn;
}

@Override
public String toString() {
    return "ClassPojo [user_email = " + user_email + ", user_tag = " + user_tag + ", user_isd = " + user_isd + ", user_mobile = " + user_mobile + ", user_picture = " + user_picture + ", following_count = " + following_count + ", user_name = " + user_name + ", user_bio = " + user_bio + ", user_gender = " + user_gender + ", post_count = " + post_count + ", follower_count = " + follower_count + "]";
}

}

Then you can store that model in Sqlite Database Table or you can use a Room ORM Database also.
Shared Preference is used to store single values. But in case you have multiple values for user, you need to store that in database.


问:
How to configure a static IP address, netmask, gateway programmatically on Android 3.x or 4.x
I have checked in Stack Overflow question API for configuring static IP addresses in an Android application.

It works until Android 2.3. However, there is no luck on a higher API level. For example,
I put the setting

```<code>android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_USE_STATIC_IP, "1");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_IP, "192.168.0.100");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_NETMASK, "255.255.255.0");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_DNS1, "192.168.0.254");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_GATEWAY, "192.168.0.254");
</code>```

But I go back to check by:

```<code>Setting --> Wi-Fi --> Long Press Access Point SSID --> Modify Network --> check Show advanced options
</code>```

The IP Settings field is still stated DHCP but not Static.

It is true that I can use android.provider.Settings.System.getString() to get back what I set. It prove that the setting is saved somewhere but the system just ignore it.

The system uses the setting other than android.provider.Settings.System on Android 3.x and 4.x as the setting is set per Access Point SSID. Can I modify the setting on one SSID just like how it works on Android 2.3?

答:
@Yeung, everyone

As far as I understand, Android would start dhclient immediately after connecting to an SSID.

So the code suggested, would apply static configuration only after Android had already obtained an IP address (dhcp success), right?

This is what is happening in my experiments on Pie. I try to apply static configuration by listening to WifiManager.NETWORK_STATE_CHANGED_ACTION

```<code>intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
...........
...........
if ( action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION) )
{
    NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
    if (info.isConnectedOrConnecting())
    {
        //apply static IP to current wifi connnections as per above code
    }
}
</code>```

Body:
I have checked in Stack Overflow question API for configuring static IP addresses in an Android application.

It works until Android 2.3. However, there is no luck on a higher API level. For example,
I put the setting

android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_USE_STATIC_IP, "1");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_IP, "192.168.0.100");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_NETMASK, "255.255.255.0");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_DNS1, "192.168.0.254");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_GATEWAY, "192.168.0.254");

But I go back to check by:

Setting --> Wi-Fi --> Long Press Access Point SSID --> Modify Network --> check Show advanced options

The IP Settings field is still stated DHCP but not Static.

It is true that I can use android.provider.Settings.System.getString() to get back what I set. It prove that the setting is saved somewhere but the system just ignore it.

The system uses the setting other than android.provider.Settings.System on Android 3.x and 4.x as the setting is set per Access Point SSID. Can I modify the setting on one SSID just like how it works on Android 2.3?

Body:
@Yeung, everyone

As far as I understand, Android would start dhclient immediately after connecting to an SSID.

So the code suggested, would apply static configuration only after Android had already obtained an IP address (dhcp success), right?

This is what is happening in my experiments on Pie. I try to apply static configuration by listening to WifiManager.NETWORK_STATE_CHANGED_ACTION

intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
...........
...........
if ( action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION) )
{
    NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
    if (info.isConnectedOrConnecting())
    {
        //apply static IP to current wifi connnections as per above code
    }
}


问:
Googlemaps V2: Add an info window on GeoJsonPolygon
I am using geojson files to draw polygon on the map on Android. Now I wanna add info windows on top of this polygons.  I try to use GeoJsonPolygonStyle from
GeoJsonlayer -> getFeature() method to style these polygon with info window.

But It doesnt give me any options like setTitle() and setSnippet() like it offers for GeoJsonPointStyle . Any help is appreciated .

答:
what about setting an setOnPolygonClickListener?

```<code>getMap().setOnPolygonClickListener(new GoogleMap.OnPolygonClickListener() {
    public void onPolygonClick(Polygon polygon) {
    //show the a pop-up containing information
    }
}
});
</code>```

Body:
what about setting an setOnPolygonClickListener?

getMap().setOnPolygonClickListener(new GoogleMap.OnPolygonClickListener() {
    public void onPolygonClick(Polygon polygon) {
    //show the a pop-up containing information
    }
}
});


问:
Transpose all rows in one column of dataframe to multiple columns based on certain conditions
I would like to convert one column of data to multiple columns in dataframe based on certain values/conditions.

Please find the code to generate the input dataframe

```<code>df1 = pd.DataFrame({'VARIABLE':['studyid',1,'age_interview', 65,'Gender','1.Male',
                            '2.Female',
                            'Ethnicity','1.Chinese','2.Indian','3.Malay']})
</code>```

The data looks like as shown below

Please note that I may not know the column names in advance. But it usually follows this format. What I have shown above is a sample data and real data might have around 600-700 columns and data arranged in this fashion

What I would like to do is convert values which start with non-digits(characters) as new columns in dataframe. It can be a new dataframe.

I attempted to write a for loop but failed to due to the below error. Can you please help me achieve this outcome.

```<code>for i in range(3,len(df1)):
#str(df1['VARIABLE'][i].contains('^\d'))
    if (df1['VARIABLE'][i].astype(str).contains('^\d') == True):
</code>```

Through the above loop, I was trying to check whether first char is a digit, if yes, then retain it as a value (ex: 1,2,3 etc) and if it's a character (ex:gender, ethnicity etc), then create a new column. But guess this is an incorrect and lengthy approach

For example, in the above example, the columns would be studyid,age_interview,Gender,Ethnicity.

The final output would look like this

Can you please let me know if there is an elegant approach to do this?

答:
Use itertools.groupby and then construct pd.DataFrame:

```<code>import pandas as pd
import itertools

l = ['studyid',1,'age_interview', 65,'Gender','1.Male',
                            '2.Female',
                            'Ethnicity','1.Chinese','2.Indian','3.Malay']
l = list(map(str, l))
grouped = [list(g) for k, g in itertools.groupby(l, key=lambda x:x[0].isnumeric())]
d = {k[0]: v for k,v in zip(grouped[::2],grouped[1::2])}

pd.DataFrame.from_dict(d, orient='index').T
</code>```

Output:

```<code>     Gender studyid age_interview  Ethnicity
0    1.Male       1            65  1.Chinese
1  2.Female    None          None   2.Indian
2      None    None          None    3.Malay
</code>```

Body:
I would like to convert one column of data to multiple columns in dataframe based on certain values/conditions.

Please find the code to generate the input dataframe

df1 = pd.DataFrame({'VARIABLE':['studyid',1,'age_interview', 65,'Gender','1.Male',
                            '2.Female',
                            'Ethnicity','1.Chinese','2.Indian','3.Malay']})

The data looks like as shown below

Please note that I may not know the column names in advance. But it usually follows this format. What I have shown above is a sample data and real data might have around 600-700 columns and data arranged in this fashion

What I would like to do is convert values which start with non-digits(characters) as new columns in dataframe. It can be a new dataframe.

I attempted to write a for loop but failed to due to the below error. Can you please help me achieve this outcome.

for i in range(3,len(df1)):
#str(df1['VARIABLE'][i].contains('^\d'))
    if (df1['VARIABLE'][i].astype(str).contains('^\d') == True):

Through the above loop, I was trying to check whether first char is a digit, if yes, then retain it as a value (ex: 1,2,3 etc) and if it's a character (ex:gender, ethnicity etc), then create a new column. But guess this is an incorrect and lengthy approach

For example, in the above example, the columns would be studyid,age_interview,Gender,Ethnicity.

The final output would look like this

Can you please let me know if there is an elegant approach to do this?

Body:
Use itertools.groupby and then construct pd.DataFrame:

import pandas as pd
import itertools

l = ['studyid',1,'age_interview', 65,'Gender','1.Male',
                            '2.Female',
                            'Ethnicity','1.Chinese','2.Indian','3.Malay']
l = list(map(str, l))
grouped = [list(g) for k, g in itertools.groupby(l, key=lambda x:x[0].isnumeric())]
d = {k[0]: v for k,v in zip(grouped[::2],grouped[1::2])}

pd.DataFrame.from_dict(d, orient='index').T

Output:

     Gender studyid age_interview  Ethnicity
0    1.Male       1            65  1.Chinese
1  2.Female    None          None   2.Indian
2      None    None          None    3.Malay


问:
.net string class alternative
Since I am planning an application that will hold MANY of its data in memory, I would like to have some kind of 'compact' string class, at least one which will contain string in format not larger than zero terminated ASCII version of the string.

Do you know of any such string class implementation - it should have some utility functions like the original string class.

EDIT:

I need to sort the strings and be able to scan through them, just to mention few of the operations that I will use.

Ideally, it would be source compatible with System.String, so basic search&replace action would optimize application memory footprint.

NUMBERS:

I could have 100k record of each record having up to 10 string having 30-60 characters.  So:

100000x10x60=60000000=57mega characters.  Why not have 60 megs of ram used for that instead of 120 megs of ram?  Operations will be faster, everything will be tighter.

Trees will be used for searching, but won't be helpful in regex scans that I plan to have.

答:
I've actually had a similar problem, but with somewhat different problem parameters.
My application deals with 2 types of strings - relatively short ones measuring 60-100 chars and longer ones with 100-1000 bytes (averages around 300).

My use case also has to support unicode text, but a relatively small percentage of the strings actually have non-english chars.

In my use case i was exposing each String property as a native String, but the underlying data structure was a byte[] holding unicode bytes.

My use case also requires searching and sorting through these strings, getting substrings and other common string operations. My dataset measures in the millions.

The basic implementation looks something like this:

```<code>byte[] _myProperty;

public String MyProperty
{

   get
   {
        if (_myProperty== null)
            return null;

        return Encoding.UTF8.GetString(value);
   }

   set
   {
        _myProperty = Encoding.UTF8.GetBytes(value);

   }

}
</code>```

The performance hit for these conversions, even when you search and sort was relatively small (was about 10-15%).

This was fine for a while, but i wanted to reduce the overhead further.
The next step was to create a merged array for all the strings in a given object (an object would hold either 1 short and 1 long string, or 4 short and 1 long string).
so there would be one byte[] for each object, and only require 1 byte for each of the strings (save their lengths which are always < 256). even if your strings can be longer then 256, and int is still cheaper then the 12-16 byte overhead for the byte[].

This reduced much of the byte[] overhead, and added a little complexity but no additional impact to performance (the encoding pass is relatively expensive compared with the array copy involved).

this implementation looks something like this:

```<code>byte _property1;
byte _property2;
byte _proeprty3;

private byte[] _data;

byte[] data;
//i actually used an Enum to indicate which property, but i am sure you get the idea
private int GetStartIndex(int propertyIndex)
{

   int result = 0;
   switch(propertyIndex)
   {
       //the fallthrough is on purpose
       case 2:
          result+=property2;
       case 1:
          result+=property1;

   }

   return result;
}

private int GetLength(int propertyIndex)
{
   switch (propertyIndex)
   {
     case 0:
        return _property1;
     case 1:
        return _property2;
     case 2:
        return _property3;
   }
    return -1;
}

private String GetString(int propertyIndex)
{
   int startIndex = GetStartIndex(propertyIndex);
   int length = GetLength(propertyIndex);
   byte[] result = new byte[length];
   Array.Copy(data,startIndex,result,0,length);

   return Encoding.UTF8.GetString(result);

}
</code>```

so the getter looks like this:

```<code>public String Property1
{
   get{ return GetString(0);}
}
</code>```

The setter is in the same spirit - copy the original data into two arrays (between 0 start to startIndex, and between startIndex+length to length) , and create a new array with the 3 arrays (dataAtStart+NewData+EndData) and set the length of the array to the appropriate local variable.

I was still not happy with the memory saved and the very hard labor of the manual implementation for each property, so i built an in-memory compress paging system that uses the amazingly fast QuickLZ to compress a full page.
This gave me a lot of control over the time-memory tradeoff (which is essentially the size of the page).

The compression rate for my use-case (compared with the more efficient byte[] store) approaches 50% (!). I used a page size of approx 10 strings per page and grouped similar properties together (which tend to have similar data).
This added an additional overhead of 10-20% (on top of the encoding/decoding pass which is still required). The paging mechanism caches recently accessed pages up to a configurable size.
Even without compression this implementation allows you to set a fixed factor on the overhead for each page.
The major downside of my current implementation of the page cache is that with compression it is not thread-safe (without it there is no such problem).

If you're interested in the compressed paging mechanism let me know (I've been looking for an excuse to open source it).

Title: .net string class alternative

Body:
I've actually had a similar problem, but with somewhat different problem parameters.
My application deals with 2 types of strings - relatively short ones measuring 60-100 chars and longer ones with 100-1000 bytes (averages around 300).

My use case also has to support unicode text, but a relatively small percentage of the strings actually have non-english chars.

In my use case i was exposing each String property as a native String, but the underlying data structure was a byte[] holding unicode bytes.

My use case also requires searching and sorting through these strings, getting substrings and other common string operations. My dataset measures in the millions.

The basic implementation looks something like this:

byte[] _myProperty;

public String MyProperty
{

   get
   {
        if (_myProperty== null)
            return null;

        return Encoding.UTF8.GetString(value);
   }

   set
   {
        _myProperty = Encoding.UTF8.GetBytes(value);

   }

}

The performance hit for these conversions, even when you search and sort was relatively small (was about 10-15%).

This was fine for a while, but i wanted to reduce the overhead further.
The next step was to create a merged array for all the strings in a given object (an object would hold either 1 short and 1 long string, or 4 short and 1 long string).
so there would be one byte[] for each object, and only require 1 byte for each of the strings (save their lengths which are always < 256). even if your strings can be longer then 256, and int is still cheaper then the 12-16 byte overhead for the byte[].

This reduced much of the byte[] overhead, and added a little complexity but no additional impact to performance (the encoding pass is relatively expensive compared with the array copy involved).

this implementation looks something like this:

byte _property1;
byte _property2;
byte _proeprty3;

private byte[] _data;

byte[] data;
//i actually used an Enum to indicate which property, but i am sure you get the idea
private int GetStartIndex(int propertyIndex)
{

   int result = 0;
   switch(propertyIndex)
   {
       //the fallthrough is on purpose
       case 2:
          result+=property2;
       case 1:
          result+=property1;

   }

   return result;
}

private int GetLength(int propertyIndex)
{
   switch (propertyIndex)
   {
     case 0:
        return _property1;
     case 1:
        return _property2;
     case 2:
        return _property3;
   }
    return -1;
}

private String GetString(int propertyIndex)
{
   int startIndex = GetStartIndex(propertyIndex);
   int length = GetLength(propertyIndex);
   byte[] result = new byte[length];
   Array.Copy(data,startIndex,result,0,length);

   return Encoding.UTF8.GetString(result);

}

so the getter looks like this:

public String Property1
{
   get{ return GetString(0);}
}

The setter is in the same spirit - copy the original data into two arrays (between 0 start to startIndex, and between startIndex+length to length) , and create a new array with the 3 arrays (dataAtStart+NewData+EndData) and set the length of the array to the appropriate local variable.

I was still not happy with the memory saved and the very hard labor of the manual implementation for each property, so i built an in-memory compress paging system that uses the amazingly fast QuickLZ to compress a full page.
This gave me a lot of control over the time-memory tradeoff (which is essentially the size of the page).

The compression rate for my use-case (compared with the more efficient byte[] store) approaches 50% (!). I used a page size of approx 10 strings per page and grouped similar properties together (which tend to have similar data).
This added an additional overhead of 10-20% (on top of the encoding/decoding pass which is still required). The paging mechanism caches recently accessed pages up to a configurable size.
Even without compression this implementation allows you to set a fixed factor on the overhead for each page.
The major downside of my current implementation of the page cache is that with compression it is not thread-safe (without it there is no such problem).

If you're interested in the compressed paging mechanism let me know (I've been looking for an excuse to open source it).


问:
How to pass parameters in headers
I need to call an API from my Angular Node application.For that i have to pass username and password along with header request.How to pass parameters?
I tried below code

From Angular service,

```<code>checkUserApi(url: string): Observable<any> {
   const headers = new HttpHeaders()
    .set('Authorization', 'my-auth-token')
    .set('Content-Type', 'application/json')
    .set('userName','prismtest')
    .set('password','12345678');
   return this.http.post('/upload/checkUserApi/', { headers })
  .map((response: Response) => {
    console.log(response);
   return response;
   })
}
</code>```

In Node,

```<code>router.post('/checkUserApi',function(req,res,next){
var proxyUrl = 'http://cors-anywhere.herokuapp.com/';

Request.post({
  "headers": { "userName": "prismtest","password":"12345678" },
  "url": proxyUrl+"https://example.com",
  "body": {}
  }, (error, response, body) => {

  if(error) {
   return console.log(error);
  }
   res.send(response);
  });
  });
</code>```

答:
You can pass the form parameters as the second attribute to post request:</p>

```<code>checkUserApi(url: string): Observable<any> {
   const headers = new HttpHeaders()
      .set('Authorization', 'my-auth-token')
      .set('Content-Type', 'application/json');

      return this.http.post('/upload/checkUserApi/', {username: 'prismtest', password: '123'}, { headers })
         .map((response: Response) => {
           console.log(response);
           return response;
          })
 }
</code>```

Title: How to pass parameters in headers

Body:
I need to call an API from my Angular Node application.For that i have to pass username and password along with header request.How to pass parameters?
I tried below code

From Angular service,

checkUserApi(url: string): Observable<any> {
   const headers = new HttpHeaders()
    .set('Authorization', 'my-auth-token')
    .set('Content-Type', 'application/json')
    .set('userName','prismtest')
    .set('password','12345678');
   return this.http.post('/upload/checkUserApi/', { headers })
  .map((response: Response) => {
    console.log(response);
   return response;
   })
}

In Node,

router.post('/checkUserApi',function(req,res,next){
var proxyUrl = 'http://cors-anywhere.herokuapp.com/';

Request.post({
  "headers": { "userName": "prismtest","password":"12345678" },
  "url": proxyUrl+"https://example.com",
  "body": {}
  }, (error, response, body) => {

  if(error) {
   return console.log(error);
  }
   res.send(response);
  });
  });

Body:
You can pass the form parameters as the second attribute to post request:

checkUserApi(url: string): Observable<any> {
   const headers = new HttpHeaders()
      .set('Authorization', 'my-auth-token')
      .set('Content-Type', 'application/json');

      return this.http.post('/upload/checkUserApi/', {username: 'prismtest', password: '123'}, { headers })
         .map((response: Response) => {
           console.log(response);
           return response;
          })
 }


问:
git commit error: version inconsistency between python 2 and python 3.7
I am using Python 3.7 for my project. Then when I tried to do

```<code>edamame$ git commit --amend --no-edit
</code>```

I got the follow error (git status works fine though):

```<code>Your PYTHONPATH points to a site-packages dir for Python 3.x but you are running Python 2.x!
     PYTHONPATH is currently: "/Users/edamame/tools/sim/scripting/:/usr/local/lib/python3.7/:/usr/local/lib/python3.7/site-packages/"
     You should `unset PYTHONPATH` to fix this.
</code>```

I tried the below but no luck:

```<code>edamame$ pip3 install git

Collecting git
  Could not find a version that satisfies the requirement git (from versions: )
No matching distribution found for git
</code>```

So I have to set the PYTHONPATH each time manually like below, which is very inconvenient. Any advise? Thanks!

```<code>edamame$ export PYTHONPATH=
</code>```

答:
If you are using Bash shell, you can add export PYTHONPATH= to your ~/.bashrc then reload ~/.bashrc with the following command:

$ source ~/.bashrc
```

That way you won't have to enter export PYTHONPATH= each time manually.

Body:
I am using Python 3.7 for my project. Then when I tried to do

edamame$ git commit --amend --no-edit

I got the follow error (git status works fine though):

Your PYTHONPATH points to a site-packages dir for Python 3.x but you are running Python 2.x!
     PYTHONPATH is currently: "/Users/edamame/tools/sim/scripting/:/usr/local/lib/python3.7/:/usr/local/lib/python3.7/site-packages/"
     You should `unset PYTHONPATH` to fix this.

I tried the below but no luck:

edamame$ pip3 install git

Collecting git
  Could not find a version that satisfies the requirement git (from versions: )
No matching distribution found for git

So I have to set the PYTHONPATH each time manually like below, which is very inconvenient. Any advise? Thanks!

edamame$ export PYTHONPATH=

Body:
If you are using Bash shell, you can add export PYTHONPATH= to your ~/.bashrc then reload ~/.bashrc with the following command:

$ source ~/.bashrc

That way you won't have to enter export PYTHONPATH= each time manually.


问:
Generate dictionaries by permutations/combinations starting from a base dictionary, and associate the result with True/False base on key values
I have a structure similar to dictionaries:

```<code>c  = {

'usize': { '500': False, '100': True}

'isize':  { '200': False, '800':False, '900':True}

'path':  {'/tmp': False, '/var':True, '/tp12':False;}

}
</code>```

I need to combine all the values, create an array of new dictionary and associate a dictionary with a Bollean values based on keys. Can be use something else than dictionaries.

Example:

```<code>c1 = {

'usize': 500,
'isize': 200,
'path': '/tmp' }

Associated value, False and False and False = False

c2 = {

'usize': 100,
'isize': 900,
'path': '/var' }

Associated value, True  and True and True = True

c2 = {

'usize': 500,
'isize': 900,
'path': '/var' }

Associated value, False  and True and True = False
</code>```

答:
One suggestion I might have is to make a combined dictionary where you chain nested keys together with a delimiter, (I chose : any other delimiter can be used as well)

So the original dictionary changes to

```<code>{'usize:500': False, 'usize:100': True,
'isize:200': False, 'isize:800': False, 'isize:900': True,
'path:/tmp': False, 'path:/var': True, 'path:/tp12': False}
</code>```

via the code

```<code>res = {'{}:{}'.format(key1,key2):value for key1,value1 in c.items() for key2, value in value1.items() }
print(res)
</code>```

We can then easily use the res dictionary to compute the boolean values for c1,c2... after iterating over with key,value pairs of c1,c2.. etc

```<code>c1_val = all(res['{}:{}'.format(k,v)] for k,v in c1.items())
print(c1_val)

c2_val = all(res['{}:{}'.format(k,v)] for k,v in c2.items())
print(c2_val)

c3_val = all(res['{}:{}'.format(k,v)] for k,v in c3.items())
print(c3_val)
</code>```

And the output will be

```<code>False
True
False
</code>```

Body:
I have a structure similar to dictionaries:

c  = {

'usize': { '500': False, '100': True}

'isize':  { '200': False, '800':False, '900':True}

'path':  {'/tmp': False, '/var':True, '/tp12':False;}

}

I need to combine all the values, create an array of new dictionary and associate a dictionary with a Bollean values based on keys. Can be use something else than dictionaries.

Example:

c1 = {

'usize': 500,
'isize': 200,
'path': '/tmp' }

Associated value, False and False and False = False

c2 = {

'usize': 100,
'isize': 900,
'path': '/var' }

Associated value, True  and True and True = True

c2 = {

'usize': 500,
'isize': 900,
'path': '/var' }

Associated value, False  and True and True = False

Body:
One suggestion I might have is to make a combined dictionary where you chain nested keys together with a delimiter, (I chose : any other delimiter can be used as well)

So the original dictionary changes to

{'usize:500': False, 'usize:100': True,
'isize:200': False, 'isize:800': False, 'isize:900': True,
'path:/tmp': False, 'path:/var': True, 'path:/tp12': False}

via the code

res = {'{}:{}'.format(key1,key2):value for key1,value1 in c.items() for key2, value in value1.items() }
print(res)

We can then easily use the res dictionary to compute the boolean values for c1,c2... after iterating over with key,value pairs of c1,c2.. etc

c1_val = all(res['{}:{}'.format(k,v)] for k,v in c1.items())
print(c1_val)

c2_val = all(res['{}:{}'.format(k,v)] for k,v in c2.items())
print(c2_val)

c3_val = all(res['{}:{}'.format(k,v)] for k,v in c3.items())
print(c3_val)

And the output will be

False
True
False


问:
Extracting JSON arrays and inserting them as separate rows in a new database
I have a database which uses JSON to store values.

```<code>CREATE TABLE JSON(name TEXT, value TEXT);
</code>```

I am trying to convert this into a native format.

```<code>CREATE TABLE NATIVE(name TEXT, KEY1, KEY2, KEY3);
</code>```

The JSON format looks like this:

```<code>[
    {"key1":value1, "key2":value2, "key3":value3},
    {"key1":value4, "key2":value5, "key3":value6},
    ....
]
</code>```

For the above example, I am trying to come up with a query using INSERT INTO NATIVE (name, KEY1, KEY2, KEY3) SELECT <something> FROM JSON to produce this table:

```<code>+------+---------+--------+--------+
| TEXT | KEY1    | KEY2   | KEY3   |
+------+---------+--------+--------+
| TEXT | VALUE1  | VALUE2 | VALUE3 |
| TEXT | VALUE4  | VALUE5 | VALUE3 |
...
+------+---------+--------+--------+
</code>```

I have been using JSON1 for other tables which use simple objects.  So for instance when I have values which are objects and not arrays of objects I can use json_extract for each field.

For an array I think I am supposed to use json_each but I am having a hard time figuring out how to apply it to this specific problem.

答:
We can try using the JSON_EXTRACT function from the json1 extension library, along with an INSERT INTO ... SELECT:

```<code>INSERT INTO NATIVE(name TEXT, KEY1, KEY2, KEY3)
SELECT
    name,
    JSON_EXTRACT(value, '$.key1'),
    JSON_EXTRACT(value, '$.key2'),
    JSON_EXTRACT(value, '$.key3')
FROM JSON;
</code>```

This assumes that it is the value column in JSON which contains the raw JSON.  If not, then replace value in the above query by whatever column contains the JSON content.

Body:
I have a database which uses JSON to store values.

CREATE TABLE JSON(name TEXT, value TEXT);

I am trying to convert this into a native format.

CREATE TABLE NATIVE(name TEXT, KEY1, KEY2, KEY3);

The JSON format looks like this:

[
    {"key1":value1, "key2":value2, "key3":value3},
    {"key1":value4, "key2":value5, "key3":value6},
    ....
]

For the above example, I am trying to come up with a query using INSERT INTO NATIVE (name, KEY1, KEY2, KEY3) SELECT <something> FROM JSON to produce this table:

+------+---------+--------+--------+
| TEXT | KEY1    | KEY2   | KEY3   |
+------+---------+--------+--------+
| TEXT | VALUE1  | VALUE2 | VALUE3 |
| TEXT | VALUE4  | VALUE5 | VALUE3 |
...
+------+---------+--------+--------+

I have been using JSON1 for other tables which use simple objects.  So for instance when I have values which are objects and not arrays of objects I can use json_extract for each field.

For an array I think I am supposed to use json_each but I am having a hard time figuring out how to apply it to this specific problem.

Body:
We can try using the JSON_EXTRACT function from the json1 extension library, along with an INSERT INTO ... SELECT:

INSERT INTO NATIVE(name TEXT, KEY1, KEY2, KEY3)
SELECT
    name,
    JSON_EXTRACT(value, '$.key1'),
    JSON_EXTRACT(value, '$.key2'),
    JSON_EXTRACT(value, '$.key3')
FROM JSON;

This assumes that it is the value column in JSON which contains the raw JSON.  If not, then replace value in the above query by whatever column contains the JSON content.


问:
Custom NSLocalizedString?
Is it possible to use the NSLocalizedString infrastructure (based on localizable.strings) with a custom-defined "localization"?

The thing is, there are some languages that have different wordings for males and females. I want to ask the user's gender on first launch and then use the appropriate phrases. Of course, both are based on the same language. I can do it with my own code but I'd rather do it the easy way if possible.

答: For couple of years Xcode has LOCALIZED_STRING_MACRO_NAMES, so you can put your custom NSLocalizedString alternative macro names if they follow same parameters structure and Xcode will correctly export/import them, similar to genstrings answer

Title: Custom NSLocalizedString?