问:
ReferenceError: window is not defined import css
Tried to import css in react js applciation but it throws below error

this is a dashboard application where node js at server side and react js in client side

webpack.base.js

```<code>  module.exports = {
    //Running babel to every file
    module: {
        rules: [
            {
                test: /\.js?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                options: {
                    presets: [
                        'react',
                        'stage-0',
                        ['env', { targets: { browsers: ['last 2 versions'] } }]
                    ]
                }
            }, {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            }, {
                test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
                loader: 'url-loader?limit=100000'
            }

        ]
    }//end module
}
</code>```

style.css

```<code>.segment {
    border-top:14px solid #14a767;
    border-bottom: 3px solid #14a767;
    margin: 2px 2px 2px 140px;
    width: 80%
 }
</code>```

Home.js (component)

```<code>import '../../css/style.css'
        return window && document && document.all && !window.atob;
        ^
</code>```

ReferenceError: window is not defined

答:
Actual problem was i have used semantic UI react node module , and that have own style on each component. So that's y it didnt allow me to create a css with class styles,.,. so instead of class style , i have used ID and it's working cool .,

My exact problem is this one ::: custom className semantic ui react

Body:
Tried to import css in react js applciation but it throws below error

this is a dashboard application where node js at server side and react js in client side

webpack.base.js

  module.exports = {
    //Running babel to every file
    module: {
        rules: [
            {
                test: /\.js?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                options: {
                    presets: [
                        'react',
                        'stage-0',
                        ['env', { targets: { browsers: ['last 2 versions'] } }]
                    ]
                }
            }, {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            }, {
                test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
                loader: 'url-loader?limit=100000'
            }

        ]
    }//end module
}

style.css

.segment {
    border-top:14px solid #14a767;
    border-bottom: 3px solid #14a767;
    margin: 2px 2px 2px 140px;
    width: 80%
 }

Home.js (component)

import '../../css/style.css'
        return window && document && document.all && !window.atob;
        ^

ReferenceError: window is not defined


来源: stackexchange

问:
htaccess redirect https www AND http www to https non-www subdirectory
I'm having trouble redirecting with my htaccess file.

What I'm trying to redirect:

```<code>https://www.example.com
https://example.com
http://www.example.com
http://example.com
</code>```

to

```<code>https://example.com/subdirectory and keep the url https://example.com
</code>```

This is what I have so far:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^ example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www. example.com$
RewriteCond %{REQUEST_URI} !folder/
RewriteRule (.*) /subdirectory/$1 [L]
</code>```

but it doesn't redirect https://www.example.com to https://example.com

What am I missing?

答:
Remove

```<code>RewriteCond %{HTTP_HOST} ^ example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www. example.com$
</code>```

and replace with

```<code>#Redirect www and http
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having trouble redirecting with my htaccess file.

What I'm trying to redirect:

https://www.example.com
https://example.com
http://www.example.com
http://example.com

to

https://example.com/subdirectory and keep the url https://example.com

This is what I have so far:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^ example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www. example.com$
RewriteCond %{REQUEST_URI} !folder/
RewriteRule (.*) /subdirectory/$1 [L]

but it doesn't redirect https://www.example.com to https://example.com

What am I missing?

Body:
Remove

RewriteCond %{HTTP_HOST} ^ example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www. example.com$

and replace with

#Redirect www and http
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]


问:
What is the best approach to clone objects properties when using map()?
I want to add a new property (contactDetails.countryName) and assign a value to a nested object stored in an array called users using the function map().

I've recently learned that I should use the spread operator (...) and then create / assign the new property in order to avoid mutating my original array of objects so I've developed 2 different implementations for this but I'm not really confident I'm following the best practices to accomplish I want to regarding the semantic and performance.

What would be the best approach to accomplish what I want to do in your opinion?

```<code>const countries = [
  { id: 3, countryName : "UK" },
  { id: 4, countryName : "Spain" },
  { id: 6, countryName : "Germany"}
];

const users = [
  { id : 1,
    name: "Douglas Camp",
    dateOfBirth: "23-06-1984",
    contactDetails:
      {
        country: 3,
        phone: "7373724997"
      }
  },
  {
    id : 2,
    name: "Martin Stein",
    dateOfBirth: "19-08-1992",
    contactDetails:
      {
        country: 6,
        phone: "3334343434"
      }
  },
];

const usersData = users.map(user=> {

// Version 1 : using spreading operator twice

const newUser = {
    ...user,
    contactDetails: {
      ...user.contactDetails,
      countryName: countries.find(c=> c.id == user.contactDetails.country).countryName
    }
  };
  return newUser;
});

// Version 2: copying the original object property and using spread operator only for cloning the nested object properties

const newUser = {
    id: user.id,
    name: user.name,
    dateOfBirth: user.dateOfBirth,
    contactDetails: {
      ...user.contactDetails,
      countryName: countries.find(c=> c.id == user.contactDetails.country).countryName
    }
  };

console.log(users);
console.log(usersData);
</code>```

答:
Here is an approach you can consider:

First of all I would Array.reduce the countries to a Map so you can get them via key/value or in this case by countries.get(key) and avoid filtering that array every time.

You can map through the users and for each one create a new object. In this case I call them accounts.

You can also consider using Object.assign

Note that both ... operator and Object.assign are shallow clone approaches. They do not recursively clone the nested objects/children. For that you can use JSON.stringify and JSON.parse etc.

let countries = [
  { id: 3, countryName : "UK" },
  { id: 4, countryName : "Spain" },
  { id: 6, countryName : "Germany"}
].reduce((r,{id, countryName}) => (r.set(id, countryName), r), new Map()) // reduce with Map

let users = [ { id : 1, name: "Douglas Camp", dateOfBirth: "23-06-1984", contactDetails: { country: 3, phone: "7373724997" } }, { id : 2, name: "Martin Stein", dateOfBirth: "19-08-1992", contactDetails: { country: 6, phone: "3334343434" } }, ];

let accounts = users.map(user => Object.assign({}, user, {  // <-- map through
  contactDetails: {
   ...user.contactDetails,
   countryName: countries.get(user.contactDetails.country)  // <-- get by key
  }
}))

users[0].id = 2  // <-- modify users
users[0].contactDetails.phone = "00000"

console.log(users, accounts) // <-- no changes to accounts```

Notice when we update the users[0].id and users[0].contactDetails.phone the accounts values did not update.

Body:
I want to add a new property (contactDetails.countryName) and assign a value to a nested object stored in an array called users using the function map().

I've recently learned that I should use the spread operator (...) and then create / assign the new property in order to avoid mutating my original array of objects so I've developed 2 different implementations for this but I'm not really confident I'm following the best practices to accomplish I want to regarding the semantic and performance.

What would be the best approach to accomplish what I want to do in your opinion?

const countries = [
  { id: 3, countryName : "UK" },
  { id: 4, countryName : "Spain" },
  { id: 6, countryName : "Germany"}
];

const users = [
  { id : 1,
    name: "Douglas Camp",
    dateOfBirth: "23-06-1984",
    contactDetails:
      {
        country: 3,
        phone: "7373724997"
      }
  },
  {
    id : 2,
    name: "Martin Stein",
    dateOfBirth: "19-08-1992",
    contactDetails:
      {
        country: 6,
        phone: "3334343434"
      }
  },
];

const usersData = users.map(user=> {

// Version 1 : using spreading operator twice

const newUser = {
    ...user,
    contactDetails: {
      ...user.contactDetails,
      countryName: countries.find(c=> c.id == user.contactDetails.country).countryName
    }
  };
  return newUser;
});

// Version 2: copying the original object property and using spread operator only for cloning the nested object properties

const newUser = {
    id: user.id,
    name: user.name,
    dateOfBirth: user.dateOfBirth,
    contactDetails: {
      ...user.contactDetails,
      countryName: countries.find(c=> c.id == user.contactDetails.country).countryName
    }
  };

console.log(users);
console.log(usersData);

Body:
Here is an approach you can consider:

First of all I would Array.reduce the countries to a Map so you can get them via key/value or in this case by countries.get(key) and avoid filtering that array every time.

You can map through the users and for each one create a new object. In this case I call them accounts.

You can also consider using Object.assign

Note that both ... operator and Object.assign are shallow clone approaches. They do not recursively clone the nested objects/children. For that you can use JSON.stringify and JSON.parse etc.

let countries = [
  { id: 3, countryName : "UK" },
  { id: 4, countryName : "Spain" },
  { id: 6, countryName : "Germany"}
].reduce((r,{id, countryName}) => (r.set(id, countryName), r), new Map()) // reduce with Map

let users = [ { id : 1, name: "Douglas Camp", dateOfBirth: "23-06-1984", contactDetails: { country: 3, phone: "7373724997" } }, { id : 2, name: "Martin Stein", dateOfBirth: "19-08-1992", contactDetails: { country: 6, phone: "3334343434" } }, ];

let accounts = users.map(user => Object.assign({}, user, {  // <-- map through
  contactDetails: {
   ...user.contactDetails,
   countryName: countries.get(user.contactDetails.country)  // <-- get by key
  }
}))

users[0].id = 2  // <-- modify users
users[0].contactDetails.phone = "00000"

console.log(users, accounts) // <-- no changes to accounts

Notice when we update the users[0].id and users[0].contactDetails.phone the accounts values did not update.


问:
Escape fullstop before slash in URL string
I've found an oddity I'm trying to get around with C# sanitizing / interfering with a specified URL, and giving a 404 as a result.

It happens where there's a forward slash after a full-stop - C# and Visual Studio are determined to remove the fullstop.

For Visual Studio, this is the Control-click from a string linking to the mal-formed URL

In compiled C# the string is transformed, even before getting to new URI().

The link is:

http://www.mattmulholland.co.nz/Matt_Mulholland/Matt_Mulholland_-_Official_Website._Boom./rss.xml

(It's the './' at the end that causes the issue)

I've tried escaping both the fullstop + slash in ASCII, and the 'dontEscape' option in the Uri() constructor, but no luck so far...

And other thoughts as to how I can get this string to allow the correct URL?

Thanks.

答:
This is what i use:

```<code>    // call this line only once in application lifetime (when app starts)
    ApplyFixEndDotUrl();

    // --------------------------
    Uri testUrl = new Uri("http://www.mattmulholland.co.nz/Matt_Mulholland/Matt_Mulholland_-_Official_Website._Boom./rss.xml");
    string strUrl = testUrl.ToString();

    // --------------------------
    // -> using System.Reflection;

    public static void ApplyFixEndDotUrl()
    {
        MethodInfo getSyntax = typeof(UriParser).GetMethod("GetSyntax", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
        FieldInfo flagsField = typeof(UriParser).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        if (getSyntax != null && flagsField != null)
        {
            foreach (string scheme in new[] { "http", "https" })
            {
                UriParser parser = (UriParser)getSyntax.Invoke(null, new object[] { scheme });
                if (parser != null)
                {
                    int flagsValue = (int)flagsField.GetValue(parser);

                    if ((flagsValue & 0x1000000) != 0)
                        flagsField.SetValue(parser, flagsValue & ~0x1000000);
                }
            }
        }
    }
</code>```

This solution is found here: HttpWebRequest to URL with dot at the end (.NET 2.0 Framework)

ContentLicense: CC BY-SA 3.0

Body:
This is what i use:

    // call this line only once in application lifetime (when app starts)
    ApplyFixEndDotUrl();

    // --------------------------
    Uri testUrl = new Uri("http://www.mattmulholland.co.nz/Matt_Mulholland/Matt_Mulholland_-_Official_Website._Boom./rss.xml");
    string strUrl = testUrl.ToString();

    // --------------------------
    // -> using System.Reflection;

    public static void ApplyFixEndDotUrl()
    {
        MethodInfo getSyntax = typeof(UriParser).GetMethod("GetSyntax", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
        FieldInfo flagsField = typeof(UriParser).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        if (getSyntax != null && flagsField != null)
        {
            foreach (string scheme in new[] { "http", "https" })
            {
                UriParser parser = (UriParser)getSyntax.Invoke(null, new object[] { scheme });
                if (parser != null)
                {
                    int flagsValue = (int)flagsField.GetValue(parser);

                    if ((flagsValue & 0x1000000) != 0)
                        flagsField.SetValue(parser, flagsValue & ~0x1000000);
                }
            }
        }
    }

This solution is found here: HttpWebRequest to URL with dot at the end (.NET 2.0 Framework)


问:
Looping dplyr and creating multiple dataframe
I have a large dataset in which I would like to use dplyr and filter and select the data to create 12 separate dataframes.

Essentially, I am using only two columns of data from a larger dataset. The first column is "plot", where I filter by "plot" number and another condition in another 3rd column ("pos_ID"). I want to create a loop that filters by plot number (I tried plot==[i]) and the 3rd condition, and then creates a new dataframe. The loop would repeat 12 times (because plot spans from 1-12).

Here is the code that I used without a loop (based on sample data)

```<code> p1_Germ <- data %>% #p1 stands for plot 1
   filter(plot==1, pos_ID<21) %>%
   select(germ_bin)
</code>```

Here is the code that I tried to incorporate a loop (based on sample data)

```<code>for(i in seq_along(plot)) {
   data %>%
     group_by(plot[[i]], pos_ID<21) %>%
     select(germ_bin)
 }
</code>```

Here is some sample data

```<code>plot <- c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12)
germ_bin <- c(0,0,1,0,1,0,0,1,1,0,1,1,0,1,0,1,0,1,1,0,1,0,1,0)
pos_ID <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24)
dataset <- data.frame(plot, germ_bin, pos_ID)
dataset
</code>```

My guess is to use a list, but I'm not familiar with loops and list and could not find a solution online. I need to create 12 dataframes because I'm trying to convert them each into a matrix after for another function. Any helpful would be much appreciated!

答:
We can use group_split and map to filter based on criteria to get list of dataframes.

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

dataset %>%
 group_split(plot) %>%
 map(. %>% filter(pos_ID < 21) %>% select(germ_bin))

#[[1]]
# A tibble: 2 x 1
#  germ_bin
#     <dbl>
#1        0
#2        0

#[[2]]
# A tibble: 2 x 1
#  germ_bin
#     <dbl>
#1        1
#2        0

#[[3]]
# A tibble: 2 x 1
#  germ_bin
#     <dbl>
#1        1
#2        0
#....
</code>```

For the shared example, if you want to drop empty groups you can filter first

```<code>dataset %>%
  filter(pos_ID < 21) %>%
  group_split(plot) %>%
  map(. %>% select(germ_bin))
</code>```

As far your attempt with for loop is concerned, you can correct that by doing

```<code>unique_plot <- unique(dataset$plot)
plot_list <- list(length = length(unique_plot))

for(i in seq_along(unique_plot)) {
   plot_list[[i]] <- dataset %>%
        filter(plot == unique_plot[i], pos_ID<21) %>%
        select(germ_bin)
}
</code>```

Or keeping it completely in base R

```<code>lapply(split(dataset, dataset$plot), function(x)
             subset(x, pos_ID < 21, select = germ_bin, drop = FALSE))
</code>```

Body:
I have a large dataset in which I would like to use dplyr and filter and select the data to create 12 separate dataframes.

Essentially, I am using only two columns of data from a larger dataset. The first column is "plot", where I filter by "plot" number and another condition in another 3rd column ("pos_ID"). I want to create a loop that filters by plot number (I tried plot==[i]) and the 3rd condition, and then creates a new dataframe. The loop would repeat 12 times (because plot spans from 1-12).

Here is the code that I used without a loop (based on sample data)

 p1_Germ <- data %>% #p1 stands for plot 1
   filter(plot==1, pos_ID<21) %>%
   select(germ_bin)

Here is the code that I tried to incorporate a loop (based on sample data)

for(i in seq_along(plot)) {
   data %>%
     group_by(plot[[i]], pos_ID<21) %>%
     select(germ_bin)
 }

Here is some sample data

plot <- c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12)
germ_bin <- c(0,0,1,0,1,0,0,1,1,0,1,1,0,1,0,1,0,1,1,0,1,0,1,0)
pos_ID <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24)
dataset <- data.frame(plot, germ_bin, pos_ID)
dataset

My guess is to use a list, but I'm not familiar with loops and list and could not find a solution online. I need to create 12 dataframes because I'm trying to convert them each into a matrix after for another function. Any helpful would be much appreciated!

Body:
We can use group_split and map to filter based on criteria to get list of dataframes.

library(dplyr)
library(purrr)

dataset %>%
 group_split(plot) %>%
 map(. %>% filter(pos_ID < 21) %>% select(germ_bin))

#[[1]]
# A tibble: 2 x 1
#  germ_bin
#     <dbl>
#1        0
#2        0

#[[2]]
# A tibble: 2 x 1
#  germ_bin
#     <dbl>
#1        1
#2        0

#[[3]]
# A tibble: 2 x 1
#  germ_bin
#     <dbl>
#1        1
#2        0
#....

For the shared example, if you want to drop empty groups you can filter first

dataset %>%
  filter(pos_ID < 21) %>%
  group_split(plot) %>%
  map(. %>% select(germ_bin))

As far your attempt with for loop is concerned, you can correct that by doing

unique_plot <- unique(dataset$plot)
plot_list <- list(length = length(unique_plot))

for(i in seq_along(unique_plot)) {
   plot_list[[i]] <- dataset %>%
        filter(plot == unique_plot[i], pos_ID<21) %>%
        select(germ_bin)
}

Or keeping it completely in base R

lapply(split(dataset, dataset$plot), function(x)
             subset(x, pos_ID < 21, select = germ_bin, drop = FALSE))


问:
2 Node Redis HA
I have two nodes which I want to run as servers in active-active mode and also have HA capability i.e if one is down, the other one should start receiving all the requests but while both are up, both should be taking all the requests. Now since Redis doesn't allow active-active mode for the same hash set and I don't have option to run Sentinel as I can't have a third node, my idea is to run the two nodes in replication and myself decide if master node is down and promote the slave to master. Are there any issues with this? When the original master comes back up, is there a way to configure it as slave?

Does this sound like a good idea? I am open to suggestions other than Redis.

答:
If you brought the replica online manually by changing it to replicaof no one, you need to be careful to bring the failed master back online as a replicaof the new node so you dont overwrite more recent data. I would not recommend doing this manually. You want to minimize downtime so automated failover is ideal

You mention being open to other products. Check out KeyDB which has the exact configuration you are looking for. It is a maintained multi-threaded fork of redis which offers the active-replica scenario you are looking for. Check out an example of it here.

Run both nodes as replicas of each other accepting reads and writes simultaneously (depending on upfront proxy config). If one fails the other continues to take the full load and is already sync'd.

Regarding the split brain concern, KeyDB can handle split brain scenarios where the connection between masters is severed, but writes continue to be made. Each write is timestamped and when the connection is restored each master will share their new data. The newest write will win. This prevents stale data from overwriting new data written after the connection was severed.

Title: 2 Node Redis HA


问:
looking for a replace() wildcard for numbers
I not an expert in C# i've only been doing it for a few months.

I have a token @Html.Raw(Model.Prices.SitePrice.Text) that displays a price for a product ($9.99)

I needed to remove the $ sign from the token so i put @Html.Raw(Model.Prices.SitePrice.Text.Replace("$", ""))

This all works fine, The issue is when I apply a special /promotion to that product, it changes the token to display:

$9.99 $7.99 it should display 7.99 once working.

I want the <stike>$##.## removed using a wildcard to deal with any number between the strike.

What would be the best way of writing the .replace() for this this text? (has to be inline for google schema data)

Ive tried:

@Html.Raw(Model.Prices.SitePrice.Text.Replace("$", "").Replace("[\r\n]+ ", ""))

@Html.Raw(Model.Prices.SitePrice.Text.Replace("$", "").Replace("(.*) ", ""))

7 different vaules?

$9.99 $7.99 it should display 7.99

$10.99 $8.99 it should display 8.99

$199.00 $188.00 it should display 188.00

$20.00 $18.50 it should display 18.50

$4.20 $2.20 it should display 2.20

$12345.00 $12225.00 it should display 12225.00

答:
One option to consider:

```<code>@Html.Raw(new string(Model.Prices.SitePrice.Text.Reverse().TakeWhile(z => z != '$').Reverse().ToArray()))
</code>```

This will take the text at the end of the SitePrice up until (and not including) the $.

Reverse means it reverses the string. TakeWhile gets you the text up until the $. Reverse reverses it back again. new string converts the char array back to a string.

Body:
One option to consider:

@Html.Raw(new string(Model.Prices.SitePrice.Text.Reverse().TakeWhile(z => z != '$').Reverse().ToArray()))

This will take the text at the end of the SitePrice up until (and not including) the $.

Reverse means it reverses the string. TakeWhile gets you the text up until the $. Reverse reverses it back again. new string converts the char array back to a string.


问:
Can I use azure logic App to remove old azure table row?
I have an azure table that contains fair amount of log info. Now I am looking at ways to delete old records (say X days ago).

Azure logic app provides Recurrence function and has built-in routine to delete Entity in Azure Table. Sounds really great, However, I got stuck really quick. This delete entity function requires Partition key and Row key. However, as I want to delete rows base on TimeStamp field, seems I can't use this one.

Ok, I tried to retrieve the old entries first and loop through each row and then delete them one by one. (copy paste this tutorial)

So I tris to create a filter query to retrieve old entries first:

```<code>@less(item()?['TimeStamp'].addDays(utcNow(), -7))
</code>```

However, azure says my expression is not valid. So I guess above expression is for blob, and not for azure tables??

Can anyone give me some guidance?

答:
In the logic apps, Get entities action support add Filter Query, so add it and use the query expression like this Timestamp ge datetime'2019-05-20T01:32Z'. Then delete the entities you get.

Here is the description about Timestamp Property, the below is my result page.

Update:
Yo could use expression addDays(utcNow(),-41) to filter the data, however you need to add '' or it won't be recognized.

This is the filter result.

Body:
I have an azure table that contains fair amount of log info. Now I am looking at ways to delete old records (say X days ago).

Azure logic app provides Recurrence function and has built-in routine to delete Entity in Azure Table. Sounds really great, However, I got stuck really quick. This delete entity function requires Partition key and Row key. However, as I want to delete rows base on TimeStamp field, seems I can't use this one.

Ok, I tried to retrieve the old entries first and loop through each row and then delete them one by one. (copy paste this tutorial)

So I tris to create a filter query to retrieve old entries first:

@less(item()?['TimeStamp'].addDays(utcNow(), -7))

However, azure says my expression is not valid. So I guess above expression is for blob, and not for azure tables??

Can anyone give me some guidance?


问:
How to sort pandas column base on a specified order?
I have a df that looks like this:

```<code>index  life_stage
1      Early Childhood
2      Birth
3      Infancy
...
</code>```

The life_stage column is not ordered correctly and I cannot rely on alphabetical order.

The correct order would be

```<code>Birth
Infancy
Early Childhood
</code>```

Is it possible to sort the life stage column according to an order that I specify in Pandas?

答:
Let's convert "life_stage" into an ordered categorical column using pd.Categorical:

```<code>df['life_stage'] = pd.Categorical(
    df['life_stage'],
    categories=['Birth', 'Infancy', 'Early Childhood'],
    ordered=True
)
</code>```

Note the order in which I specify the categories to pd.Categorical. Now, call sort_values using life_stage:

```<code>df.sort_values(by=['life_stage'])

   index       life_stage
2      1            Birth
1      2          Infancy
0      3  Early Childhood
</code>```

For reference, sorting "life_stage" alphabetically gets you

```<code>   index       life_stage
2      1            Birth
0      3  Early Childhood   # wrong!
1      2          Infancy
</code>```

Body:
I have a df that looks like this:

index  life_stage
1      Early Childhood
2      Birth
3      Infancy
...

The life_stage column is not ordered correctly and I cannot rely on alphabetical order.

The correct order would be

Birth
Infancy
Early Childhood

Is it possible to sort the life stage column according to an order that I specify in Pandas?

Body:
Let's convert "life_stage" into an ordered categorical column using pd.Categorical:

df['life_stage'] = pd.Categorical(
    df['life_stage'],
    categories=['Birth', 'Infancy', 'Early Childhood'],
    ordered=True
)

Note the order in which I specify the categories to pd.Categorical. Now, call sort_values using life_stage:

df.sort_values(by=['life_stage'])

   index       life_stage
2      1            Birth
1      2          Infancy
0      3  Early Childhood

For reference, sorting "life_stage" alphabetically gets you

   index       life_stage
2      1            Birth
0      3  Early Childhood   # wrong!
1      2          Infancy


答:
IIUC, you want pd.Categorical with order:

```<code>s = pd.Categorical(['Infancy', 'Birth', 'Early Childhood'],
               categories=['Birth', 'Infancy', 'Early Childhood'],
               ordered=True)
s.sort_values()
</code>```

Output:

```<code>[Birth, Infancy, Early Childhood]
Categories (3, object): [Birth < Infancy < Early Childhood]
</code>```

Title: How to sort pandas column base on a specified order?

Body:
IIUC, you want pd.Categorical with order:

s = pd.Categorical(['Infancy', 'Birth', 'Early Childhood'],
               categories=['Birth', 'Infancy', 'Early Childhood'],
               ordered=True)
s.sort_values()

Output:

[Birth, Infancy, Early Childhood]
Categories (3, object): [Birth < Infancy < Early Childhood]


问:
Apache redirect .js request to PHP request
I am trying to serve a JavaScript response from a JavaScript request using PHP.

Assuming that the request is embedded into the HTML source as

```<code><script type=\"text/javascript\" src=\"http://www.mydomain.com/generatejs.js\" charset=\"UTF-8\"></script>
</code>```

And i have a PHP script that is called generatejs.js.php which outputs more JavaScript code

The Apache rewrite condition/rule are

```<code>RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</code>```

But I am getting a 404 when trying to access http://www.mydomain.com/generatejs.js. Can someone please help me with the missing bit? :)

答:
Your RewriteRule is not matching /generatejs.js because of the [^\.]+ (which is anything BUT a .) So, if you update it to the following, you should have better luck:

```<code>RewriteRule ^([^\.]+)\.js$ $1.js.php [NC,L]
</code>```

Hope this helps.

Body:
I am trying to serve a JavaScript response from a JavaScript request using PHP.

Assuming that the request is embedded into the HTML source as

And i have a PHP script that is called generatejs.js.php which outputs more JavaScript code

The Apache rewrite condition/rule are

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]

But I am getting a 404 when trying to access http://www.mydomain.com/generatejs.js. Can someone please help me with the missing bit? :)

Body:
Your RewriteRule is not matching /generatejs.js because of the [^\.]+ (which is anything BUT a .) So, if you update it to the following, you should have better luck:

RewriteRule ^([^\.]+)\.js$ $1.js.php [NC,L]

Hope this helps.


问:
React - How to Populate one Dropdowns based on selection from another Dropdown by Passing State as props
I am creating a bar with two dropdown. The second dropdown depends of the selection from the first dropdown. I have 3 Components :
1. Dropdown Bar : Contains FirstDropdown and Second Dropdown
2. FirstDropdown
3. SecondDropdown

Trying to pass State -> Practice that appears in the FirstDropdown Component as props to SecondDropdown Component. Clearly I'm not doing this correctly. Any Help will be appreciate. Thank you in advance!

```<code>class DropdownBar extends React.Component {
constructor(props) {
    super(props);
}

render () {
    return (
        <div>
            <div className="top-bar">
                <Row>
                    <div style={{marginTop: 15, marginBottom:15}}>
                        <Col span={8}><FirstDropdown practice={this.props.practice} /></Col>
                        <Col span={8}><SecondDropdown /></Col>

                    </div>
                </Row>
            </div>
        </div>
    )
}

class FirstDropdown extends React.Component {
constructor() {
    super();
    this.state = {
        practices: [
            name = 'Jon',
            name = 'potato',
            name = 'stark',
        ],
        practice: 'stark'
    }
}

onChangePractice(value) {
    console.log(`selected ${value}`);
    this.setState({
        practice: value
    })
}

render () {
    const {practices} = this.state

    return  (
        <div>
            <Row>
                <div className="First-dropdown">
                <Col span={8}><div className="dropdown-title">Research: </div></Col>
                <Col span={14}>
                    <Select
                    showSearch
                    style={{ width: '100%' }}
                    placeholder="Select a Something"
                    optionFilterProp="children"
                    onChange={this.onChangePractice.bind(this)}
                    onFocus={onFocus}
                    onBlur={onBlur}
                    onSearch={onSearch}
                    filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    >
                        {practices.map(practice => (
                            <Option
                            value={practice}
                            key={practice}
                            data-automation={practice.name}
                            >{practice}</Option>
                        ))}
                    </Select>
                </Col>
                </div>
            </Row>
        </div>

    )
}

class SecondDropdown extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        modules: [
            name = 'Drogon',
            name = 'Rhaegal',
            name = 'Viserion',
        ]
    }
}
componentDidUpdate(prevProps) {
    console.log(this.props.practice)
    if (!equal(this.props.practice, prevProps.practice))
    {
        this.updatePractice();

    }
}

render () {
    const {modules} = this.state
    console.log(this.props.practice )
    let practice = this.props.practice;

    if (practice === 'stark') {
        return  (
            <div>
                <Row>
                    <div className="benchmark-dropdown">
                    <Col span={4}><div className="dropdown-title">Module: </div></Col>
                    <Col span={16}>
                        <Select
                        showSearch
                        style={{ width: '100%' }}
                        placeholder="Select Something"
                        optionFilterProp="children"
                        onChange={onChange}
                        onFocus={onFocus}
                        onBlur={onBlur}
                        onSearch={onSearch}
                        filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        >
                            {modules.map(item => (
                                <Option
                                value={item}
                                key={item}
                                >{item}</Option>
                            ))}
                        </Select>
                    </Col>
                    </div>
                </Row>
            </div>

        )
    } else {
        return <div> NOOOOO </div>
    }

}
</code>```

答:
I'd pull the state into the parent.

class MainBar extends React.Component {
  state = {
    practice: null
  };

  handleChange = practice => {
    this.setState({ practice });
  }

  render() {
    return (

        <Row>

              <Col span={8}>
                <FirstDropdown
                  onChange={this.handleChange}
                  practice={this.state.practice}
                />
              </Col>
              <Col span={8}>
                <SecondDropdown practice={this.state.practice} />
              </Col>

        </Row>

    );
  }
}```

Body:
I am creating a bar with two dropdown. The second dropdown depends of the selection from the first dropdown. I have 3 Components :
1. Dropdown Bar : Contains FirstDropdown and Second Dropdown
2. FirstDropdown
3. SecondDropdown

Trying to pass State -> Practice that appears in the FirstDropdown Component as props to SecondDropdown Component. Clearly I'm not doing this correctly. Any Help will be appreciate. Thank you in advance!

class DropdownBar extends React.Component {
constructor(props) {
    super(props);
}

render () {
    return (

                <Row>

                        <Col span={8}><FirstDropdown practice={this.props.practice} /></Col>
                        <Col span={8}><SecondDropdown /></Col>

                </Row>

    )
}

class FirstDropdown extends React.Component {
constructor() {
    super();
    this.state = {
        practices: [
            name = 'Jon',
            name = 'potato',
            name = 'stark',
        ],
        practice: 'stark'
    }
}

onChangePractice(value) {
    console.log(`selected ${value}`);
    this.setState({
        practice: value
    })
}

render () {
    const {practices} = this.state

    return  (

            <Row>

                <Col span={8}>
Research:
</Col>
                <Col span={14}>
                    <Select
                    showSearch
                    style={{ width: '100%' }}
                    placeholder="Select a Something"
                    optionFilterProp="children"
                    onChange={this.onChangePractice.bind(this)}
                    onFocus={onFocus}
                    onBlur={onBlur}
                    onSearch={onSearch}
                    filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    >
                        {practices.map(practice => (
                            <Option
                            value={practice}
                            key={practice}
                            data-automation={practice.name}
                            >{practice}</Option>
                        ))}
                    </Select>
                </Col>

            </Row>

    )
}

class SecondDropdown extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        modules: [
            name = 'Drogon',
            name = 'Rhaegal',
            name = 'Viserion',
        ]
    }
}
componentDidUpdate(prevProps) {
    console.log(this.props.practice)
    if (!equal(this.props.practice, prevProps.practice))
    {
        this.updatePractice();

    }
}

render () {
    const {modules} = this.state
    console.log(this.props.practice )
    let practice = this.props.practice;

    if (practice === 'stark') {
        return  (

                <Row>

                    <Col span={4}>
Module:
</Col>
                    <Col span={16}>
                        <Select
                        showSearch
                        style={{ width: '100%' }}
                        placeholder="Select Something"
                        optionFilterProp="children"
                        onChange={onChange}
                        onFocus={onFocus}
                        onBlur={onBlur}
                        onSearch={onSearch}
                        filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        >
                            {modules.map(item => (
                                <Option
                                value={item}
                                key={item}
                                >{item}</Option>
                            ))}
                        </Select>
                    </Col>

                </Row>

        )
    } else {
        return
 NOOOOO

    }

}

Body:
I'd pull the state into the parent.

class MainBar extends React.Component {
  state = {
    practice: null
  };

  handleChange = practice => {
    this.setState({ practice });
  }

  render() {
    return (
      <div className="top-bar">
        <Row>
          <div style={{marginTop: 15, marginBottom:15}}>
              <Col span={8}>
                <FirstDropdown
                  onChange={this.handleChange}
                  practice={this.state.practice}
                />
              </Col>
              <Col span={8}>
                <SecondDropdown practice={this.state.practice} />
              </Col>
          </div>
        </Row>
      </div>
    );
  }
}


问:
How do I send raw binary data via HTTP in node.js?
From a node.js back end, I need to send an HTTP message to a REST endpoint. The endpoint requires some parameters that it will expect to find in the HTTP message. Some of the parameters are simple enough, just requiring a number or a string as an argument. But one of the parameters is to be "the raw binary file content being uploaded" and this has puzzled me. As far as I understand, the parameters need to be gathered together into a string to put in the body of the HTTP request; How do I add raw binary data to a string? Obviously, for it to be in the string, it cannot be raw binary data; it needs to be encoded into characters.

The endpoint in question is the Twitter media upload API. The "raw binary data" parameter is called media. Below is an incomplete code snippet showing the basic gist of what I've tried. Specifically, the line where I build the requestBody string. I don't believe it is anywhere near correct, because the endpoint is returning a "bad request" message.

```<code>var https = require("https");

var base64ImageData = /* (some base 64 string here) */;

var options = {
    host: "api.twitter.com",
    path: "/1.1/media/upload.json",
    method: "POST",
    headers: {
        "Content-Type": "multipart/form-data"
    }
};
var request = https.request(options, function(response) {});
var requestBody = "media_id=18283918294&media=" + Buffer.from(base64ImageData, "base64").toString("binary");
request.write(requestBody);
request.end();
</code>```

Also worth noting, Twitter themselves note the following extremely confusing statement:

"When posting base64 encoded images, be sure to set the “Content-Transfer-Encoding: base64” on the image part of the message."

Source: https://developer.twitter.com/en/docs/media/upload-media/uploading-media/media-best-practices

That might be part of the answer to my question, but what I don't understand is: How do I apply different headers to different parts of the HTTP message? Because apparently, the image data needs to have a Content-Transfer-Encoding header of "base64" while the rest of the HTTP message does not...

答:
How do I apply different headers to different parts of the HTTP message?

This is the point of the multipart/form-data content type. A multi-part message looks like this:

```<code>Content-Type: multipart/form-data; boundary=---foo---

---foo---
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Transfer-Encoding: base64
Content-Type: image/gif

// data goes here
---foo---
Content-Disposition: form-data; name="datafile2"; filename="g.png"
Content-Transfer-Encoding: base64
Content-Type: image/png

// another file's data goes here
---foo---
</code>```

You probably don't want to put all this together yourself. There are a bunch of good libraries for putting together complex POSTs. For example: https://www.npmjs.com/package/form-data

Body:
From a node.js back end, I need to send an HTTP message to a REST endpoint. The endpoint requires some parameters that it will expect to find in the HTTP message. Some of the parameters are simple enough, just requiring a number or a string as an argument. But one of the parameters is to be "the raw binary file content being uploaded" and this has puzzled me. As far as I understand, the parameters need to be gathered together into a string to put in the body of the HTTP request; How do I add raw binary data to a string? Obviously, for it to be in the string, it cannot be raw binary data; it needs to be encoded into characters.

The endpoint in question is the Twitter media upload API. The "raw binary data" parameter is called media. Below is an incomplete code snippet showing the basic gist of what I've tried. Specifically, the line where I build the requestBody string. I don't believe it is anywhere near correct, because the endpoint is returning a "bad request" message.

var https = require("https");

var base64ImageData = /* (some base 64 string here) */;

var options = {
    host: "api.twitter.com",
    path: "/1.1/media/upload.json",
    method: "POST",
    headers: {
        "Content-Type": "multipart/form-data"
    }
};
var request = https.request(options, function(response) {});
var requestBody = "media_id=18283918294&media=" + Buffer.from(base64ImageData, "base64").toString("binary");
request.write(requestBody);
request.end();

Also worth noting, Twitter themselves note the following extremely confusing statement:

"When posting base64 encoded images, be sure to set the “Content-Transfer-Encoding: base64” on the image part of the message."

Source: https://developer.twitter.com/en/docs/media/upload-media/uploading-media/media-best-practices

That might be part of the answer to my question, but what I don't understand is: How do I apply different headers to different parts of the HTTP message? Because apparently, the image data needs to have a Content-Transfer-Encoding header of "base64" while the rest of the HTTP message does not...

Body:
How do I apply different headers to different parts of the HTTP message?

This is the point of the multipart/form-data content type. A multi-part message looks like this:

Content-Type: multipart/form-data; boundary=---foo---

---foo---
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Transfer-Encoding: base64
Content-Type: image/gif

// data goes here
---foo---
Content-Disposition: form-data; name="datafile2"; filename="g.png"
Content-Transfer-Encoding: base64
Content-Type: image/png

// another file's data goes here
---foo---

You probably don't want to put all this together yourself. There are a bunch of good libraries for putting together complex POSTs. For example: https://www.npmjs.com/package/form-data


答:
In order for both dropdowns to have access to the practice prop, you need to lift it up to the DropdownBar's state, and pass down both practice and a way to update practice.

```<code>class DropdownBar extends Component {
  state = {
    practice: '',
  }

  handlePracticeChange = (value) => {
    setState({ practice: value });
  }

  render() {
    return (
      <div>
        <FirstDropdown
          practice={this.state.practice}
          onPracticeChange={this.handlePracticeChange}
        />
        <SecondDropdown practice={this.state.practice} />
      </div>
    )
  }
}
</code>```

So, practice only lives in DropdownBar, and the practices array should live in FirstDropdown child.

In FirstDropdown, you should pass props.onPracticeChange to your Select's onChange:

```<code>class FirstDropdown extends Component {
  render() {
    ...
    <Select
      onChange={this.props.onPracticeChange}
    ...
  }
}
</code>```

From your code example, it looks like Select passes the currently selected value to onChange.

Title: React - How to Populate one Dropdowns based on selection from another Dropdown by Passing State as props

Body:
In order for both dropdowns to have access to the practice prop, you need to lift it up to the DropdownBar's state, and pass down both practice and a way to update practice.

class DropdownBar extends Component {
  state = {
    practice: '',
  }

  handlePracticeChange = (value) => {
    setState({ practice: value });
  }

  render() {
    return (
      <div>
        <FirstDropdown
          practice={this.state.practice}
          onPracticeChange={this.handlePracticeChange}
        />
        <SecondDropdown practice={this.state.practice} />
      </div>
    )
  }
}

So, practice only lives in DropdownBar, and the practices array should live in FirstDropdown child.

In FirstDropdown, you should pass props.onPracticeChange to your Select's onChange:

class FirstDropdown extends Component {
  render() {
    ...
    <Select
      onChange={this.props.onPracticeChange}
    ...
  }
}

From your code example, it looks like Select passes the currently selected value to onChange.


问:
Random number array sorted with Selection Sort -- garbage characters output for size > 130
My program takes user input (integer between 10 and 200) and prints out the entered number of random numbers and stores them in an array. Then the array is sorted and printed out (SEE IMAGE BELOW). The median is of the numbers are also printed on the screen.

I have not been able to find the error. The program works perfectly for numbers less than or equal to 130, but not over 130.

```<code>TITLE Program5    (Program5.asm)

INCLUDE Irvine32.inc

; (insert constant definitions here)
    MIN_INPUT = 10
    MAX_INPUT = 200
    LO_RANDOM = 100
    HI_RANDOM = 999

.data
request         DWORD   10
ask_user        BYTE    "How many numbers should be generated? [10 ... 200]: ", 0
error           BYTE    "Invalid input", 0

title_1         BYTE    "The unsorted random numbers: ", 0
title_2         BYTE    "The sorted list: ", 0
space           BYTE    "   ", 0
median          BYTE    "The median is: ", 0
temp            DWORD   0
list            DWORD   MAX_INPUT   DUP(?)

.code
main PROC

; (insert executable instructions here)
    call    randomize

    push    OFFSET request ;passed by reference
    call    getData

    call    CrLf

    push    request ; passed by value
    push    OFFSET list ; passed by reference
    call    fillArray

    push    OFFSET list
    push    request
    push    OFFSET title_1
    call    displaylist

    push    OFFSET list
    push    request
    call    sortList

    push    OFFSET list
    push    request
    call    displayMedian

    call    CrLf
    call    CrLf

    push    OFFSET list
    push    request
    push    OFFSET title_2
    call    displaylist

    exit    ; exit to operating system
main ENDP

; (insert additional procedures here)
getData PROC

    push    ebp ;Set up stack frame
    mov     ebp, esp

    ;get an integer from user
    mov     ebx, [ebp+8]    ;get address of request into ebx

    L1:
        mov     edx, OFFSET ask_user
        call    WriteString
        call    ReadDec

        cmp     eax, MIN_INPUT
        jl      errorMessage
        cmp     eax, MAX_INPUT
        jg      errorMessage

        cmp     eax, MIN_INPUT
        jge     endThis
        cmp     eax, MAX_INPUT
        jle     endThis

    errorMessage:
        mov     edx, OFFSET error
        call    WriteString
        call    CrLf
        jmp     L1

    endThis:
        mov     [ebx], eax
        pop     ebp
        ret     4 ; remove four more bytes from the stack (after ret @)

getData ENDP

fillArray PROC
;include parameters - request (value), array (reference)
    ; MAJORITY OF THE FOLLOWING CODE WAS EXTRACTED FROM LECTURE 20 SLIDES
    push    ebp
    mov     ebp, esp ;[ebp+4]
    mov     edi, [ebp+8] ; @list in edi
    mov     ecx, [ebp+12] ; value of request in ecx

    more:
        mov     eax, HI_RANDOM
        sub     eax, LO_RANDOM
        inc     eax
        call    RandomRange
        add     eax, LO_RANDOM

        mov     [edi], eax
        add     edi, 4
        loop    more

    endmore:
        pop     ebp
        ret     8
fillArray ENDP

sortList PROC
    push    ebp
    mov     ebp, esp
    mov     edi, [ebp+12]
    mov     ecx, [ebp+8]

    dec     ecx
    mov     ebx, 0

    firstLoop:
        mov     eax, ebx
        mov     edx, ebx
        inc     edx
        push    ecx
        mov     ecx, [ebp+8]

        secondLoop:
            mov     esi, [edi + (edx * 4)]
            cmp     esi, [edi + (eax * 4)]
            jle     lesser
            mov     eax, edx
        lesser:
            inc     edx
            loop    secondLoop

        push    edx
        push    esi
        push    [edi + (ebx * 4)] ; array[k]
        push    [edi + (eax * 4)] ; array[i]
        call    exchangeElements
        pop     [edi + (eax * 4)]
        pop     [edi + (ebx * 4)]
        pop     esi
        pop     edx
        pop     ecx ; set the
        inc     ebx ; increment k in the first loop
        loop    firstLoop

    pop     ebp
    ret     8

sortList ENDP

exchangeElements PROC
    push    ebp
    mov     ebp, esp
    mov     esi, [ebp+12] ; array[k]
    mov     edx, [ebp+8] ; array[i]
    mov     [ebp+8], esi
    mov     [ebp+12], edx
    pop     ebp
    ret
exchangeElements ENDP

displayMedian PROC
    push    ebp
    mov     ebp, esp ;[ebp+4]
    mov     edi, [ebp+12] ; @list in edi
    mov     ecx, [ebp+8] ; value of request in ecx

    mov     eax, ecx
    mov     ebx, 2
    cdq
    div     ebx
    cmp     edx, 0
    je      isEven
    cmp     edx, 1
    je      isOdd

    ; https://github.com/TRMassey/CS271/blob/master/assignment5.asm
    isEven:
        ; find the higher number
        mov     ebx, 4
        mul     ebx
        add     edi, eax
        mov     edx, [edi]

        ; find the lower number
        mov     eax, edi
        sub     eax, 4
        mov     edi, eax
        mov     eax, [edi]

        ; add and divide them by 2
        add     eax, edx
        mov     edx, 0
        mov     ebx, 2
        cdq
        div     ebx

        ; print out the median value (rounded to the nearest int)
        call    CrLf
        call    CrLf
        mov     edx, OFFSET median
        call    WriteString
        call    WriteDec
        jmp     finish

    isOdd:
        mov     eax, [edi + (eax * 4)]
        call    CrLf
        call    CrLf
        mov     edx, OFFSET median
        call    WriteString
        call    WriteDec
        jmp     finish

    finish:
        pop ebp
        ret
displayMedian ENDP

displayList PROC
    push    ebp
    mov     ebp, esp ; [ebp+4]
    mov     ecx, [ebp+12] ; @request
    mov     edi, [ebp+16] ; @list
    mov     esi, 10

    mov     edx, [ebp+8] ; @title
    call    WriteString
    call    CrLf

    show:
        mov     eax, [edi]
        call    WriteDec
        mov     edx, OFFSET space
        call    WriteString
        add     edi, 4

        dec     esi
        cmp     esi, 0
        je      callClear

    loopAgain:
        loop    show

    jmp     endshow

    callClear:
        mov     esi, 10
        call    CrLf
        jmp     loopAgain

    endshow:
        pop     ebp
        ret     12

displayList ENDP

END main
</code>```

Below is what my output currently looks like

Below is what I want my output to look like:

答:
I'm going to go ahead and turn my comments into an Answer so we can close this question.

I believe the problem OP is experiencing comes from this code:

```<code>mov     ebx, 0

firstLoop:
    mov     eax, ebx
    mov     edx, ebx
    inc     edx
    push    ecx
    mov     ecx, [ebp+8]

    secondLoop:
        mov     esi, [edi + (edx * 4)]
        cmp     esi, [edi + (eax * 4)]
        jle     lesser
        mov     eax, edx
    lesser:
        inc     edx
        loop    secondLoop
</code>```

As you can see, ecx gets loaded from [ebp+8].  This is where the user input regarding the number of entries is stored.  The code then walks over the array of generated random numbers located at edi.

The very first time this code is executed, ebx starts at 0.  So it safely walks the (say) 200 entries in the list.

However, on subsequent passes, ebx can be larger than 0.  But, ecx is still 200.  So we're still going to walk 200 entries, but we are no longer starting at index zero.

Which means, we're reading/writing past the end of the allocated space.  Which is why the output is junk.

The reason this seems to work for smaller numbers of entries is that the space for the list is pre-allocated (and apparently zero filled?).  Since the sort is 'descending,' the zeros all look like they don't need to be moved.

While I haven't traced thru all the ins and outs of the sort, at a minimum this is going to be a problem.

A simple fix of adding sub ecx, ebx right after mov ecx, [ebp+8] seems to resolve the problem.

Body:
My program takes user input (integer between 10 and 200) and prints out the entered number of random numbers and stores them in an array. Then the array is sorted and printed out (SEE IMAGE BELOW). The median is of the numbers are also printed on the screen.

I have not been able to find the error. The program works perfectly for numbers less than or equal to 130, but not over 130.

TITLE Program5    (Program5.asm)

INCLUDE Irvine32.inc

; (insert constant definitions here)
    MIN_INPUT = 10
    MAX_INPUT = 200
    LO_RANDOM = 100
    HI_RANDOM = 999

.data
request         DWORD   10
ask_user        BYTE    "How many numbers should be generated? [10 ... 200]: ", 0
error           BYTE    "Invalid input", 0

title_1         BYTE    "The unsorted random numbers: ", 0
title_2         BYTE    "The sorted list: ", 0
space           BYTE    "   ", 0
median          BYTE    "The median is: ", 0
temp            DWORD   0
list            DWORD   MAX_INPUT   DUP(?)

.code
main PROC

; (insert executable instructions here)
    call    randomize

    push    OFFSET request ;passed by reference
    call    getData

    call    CrLf

    push    request ; passed by value
    push    OFFSET list ; passed by reference
    call    fillArray

    push    OFFSET list
    push    request
    push    OFFSET title_1
    call    displaylist

    push    OFFSET list
    push    request
    call    sortList

    push    OFFSET list
    push    request
    call    displayMedian

    call    CrLf
    call    CrLf

    push    OFFSET list
    push    request
    push    OFFSET title_2
    call    displaylist

    exit    ; exit to operating system
main ENDP

; (insert additional procedures here)
getData PROC

    push    ebp ;Set up stack frame
    mov     ebp, esp

    ;get an integer from user
    mov     ebx, [ebp+8]    ;get address of request into ebx

    L1:
        mov     edx, OFFSET ask_user
        call    WriteString
        call    ReadDec

        cmp     eax, MIN_INPUT
        jl      errorMessage
        cmp     eax, MAX_INPUT
        jg      errorMessage

        cmp     eax, MIN_INPUT
        jge     endThis
        cmp     eax, MAX_INPUT
        jle     endThis

    errorMessage:
        mov     edx, OFFSET error
        call    WriteString
        call    CrLf
        jmp     L1

    endThis:
        mov     [ebx], eax
        pop     ebp
        ret     4 ; remove four more bytes from the stack (after ret @)

getData ENDP

fillArray PROC
;include parameters - request (value), array (reference)
    ; MAJORITY OF THE FOLLOWING CODE WAS EXTRACTED FROM LECTURE 20 SLIDES
    push    ebp
    mov     ebp, esp ;[ebp+4]
    mov     edi, [ebp+8] ; @list in edi
    mov     ecx, [ebp+12] ; value of request in ecx

    more:
        mov     eax, HI_RANDOM
        sub     eax, LO_RANDOM
        inc     eax
        call    RandomRange
        add     eax, LO_RANDOM

        mov     [edi], eax
        add     edi, 4
        loop    more

    endmore:
        pop     ebp
        ret     8
fillArray ENDP

sortList PROC
    push    ebp
    mov     ebp, esp
    mov     edi, [ebp+12]
    mov     ecx, [ebp+8]

    dec     ecx
    mov     ebx, 0

    firstLoop:
        mov     eax, ebx
        mov     edx, ebx
        inc     edx
        push    ecx
        mov     ecx, [ebp+8]

        secondLoop:
            mov     esi, [edi + (edx * 4)]
            cmp     esi, [edi + (eax * 4)]
            jle     lesser
            mov     eax, edx
        lesser:
            inc     edx
            loop    secondLoop

        push    edx
        push    esi
        push    [edi + (ebx * 4)] ; array[k]
        push    [edi + (eax * 4)] ; array[i]
        call    exchangeElements
        pop     [edi + (eax * 4)]
        pop     [edi + (ebx * 4)]
        pop     esi
        pop     edx
        pop     ecx ; set the
        inc     ebx ; increment k in the first loop
        loop    firstLoop

    pop     ebp
    ret     8

sortList ENDP

exchangeElements PROC
    push    ebp
    mov     ebp, esp
    mov     esi, [ebp+12] ; array[k]
    mov     edx, [ebp+8] ; array[i]
    mov     [ebp+8], esi
    mov     [ebp+12], edx
    pop     ebp
    ret
exchangeElements ENDP

displayMedian PROC
    push    ebp
    mov     ebp, esp ;[ebp+4]
    mov     edi, [ebp+12] ; @list in edi
    mov     ecx, [ebp+8] ; value of request in ecx

    mov     eax, ecx
    mov     ebx, 2
    cdq
    div     ebx
    cmp     edx, 0
    je      isEven
    cmp     edx, 1
    je      isOdd

    ; https://github.com/TRMassey/CS271/blob/master/assignment5.asm
    isEven:
        ; find the higher number
        mov     ebx, 4
        mul     ebx
        add     edi, eax
        mov     edx, [edi]

        ; find the lower number
        mov     eax, edi
        sub     eax, 4
        mov     edi, eax
        mov     eax, [edi]

        ; add and divide them by 2
        add     eax, edx
        mov     edx, 0
        mov     ebx, 2
        cdq
        div     ebx

        ; print out the median value (rounded to the nearest int)
        call    CrLf
        call    CrLf
        mov     edx, OFFSET median
        call    WriteString
        call    WriteDec
        jmp     finish

    isOdd:
        mov     eax, [edi + (eax * 4)]
        call    CrLf
        call    CrLf
        mov     edx, OFFSET median
        call    WriteString
        call    WriteDec
        jmp     finish

    finish:
        pop ebp
        ret
displayMedian ENDP

displayList PROC
    push    ebp
    mov     ebp, esp ; [ebp+4]
    mov     ecx, [ebp+12] ; @request
    mov     edi, [ebp+16] ; @list
    mov     esi, 10

    mov     edx, [ebp+8] ; @title
    call    WriteString
    call    CrLf

    show:
        mov     eax, [edi]
        call    WriteDec
        mov     edx, OFFSET space
        call    WriteString
        add     edi, 4

        dec     esi
        cmp     esi, 0
        je      callClear

    loopAgain:
        loop    show

    jmp     endshow

    callClear:
        mov     esi, 10
        call    CrLf
        jmp     loopAgain

    endshow:
        pop     ebp
        ret     12

displayList ENDP

END main

Below is what my output currently looks like

Below is what I want my output to look like:

Body:
I'm going to go ahead and turn my comments into an Answer so we can close this question.

I believe the problem OP is experiencing comes from this code:

mov     ebx, 0

firstLoop:
    mov     eax, ebx
    mov     edx, ebx
    inc     edx
    push    ecx
    mov     ecx, [ebp+8]

    secondLoop:
        mov     esi, [edi + (edx * 4)]
        cmp     esi, [edi + (eax * 4)]
        jle     lesser
        mov     eax, edx
    lesser:
        inc     edx
        loop    secondLoop

As you can see, ecx gets loaded from [ebp+8].  This is where the user input regarding the number of entries is stored.  The code then walks over the array of generated random numbers located at edi.

The very first time this code is executed, ebx starts at 0.  So it safely walks the (say) 200 entries in the list.

However, on subsequent passes, ebx can be larger than 0.  But, ecx is still 200.  So we're still going to walk 200 entries, but we are no longer starting at index zero.

Which means, we're reading/writing past the end of the allocated space.  Which is why the output is junk.

The reason this seems to work for smaller numbers of entries is that the space for the list is pre-allocated (and apparently zero filled?).  Since the sort is 'descending,' the zeros all look like they don't need to be moved.

While I haven't traced thru all the ins and outs of the sort, at a minimum this is going to be a problem.

A simple fix of adding sub ecx, ebx right after mov ecx, [ebp+8] seems to resolve the problem.


问:
Are there any good guides on custom Cocoa User Interface Design?
I've been a software developer (mainly Visual Studio) for many years and have been working with Objective C and Cocoa for some months now. I have a good handle now on the language and the frameworks but one thing I need to work on is interface design, more specifically custom views and tables.

There is a lot of info out there on standard design but not much on the custom designs. Here's an example of what I want to do. Create a table view with multiple information (text fields and images) per cell and have that cell expand showing more information when clicked on.

Are there any books, tutorials, walkthroughs, etc that you would recommend to learn this part of the process?

Many thanks in advance.

答:
For design topics, Apple's Human Interface Guidelines are a great place to start.

For implementation issues, have a look at Control and Cell Programming Topics For Cocoa. As the title implies, it goes into detail about how controls & cells work together, including how to subclass one or both to implement custom UIs. Also interesting are the View Programming Guide, the Cocoa Drawing Guide, the Core Animation Programming Guide, and the Core Animation Cookbook.


问:
Singleton tooltip design in React
Here is the case: I want to reuse a panel/callout/tooltip to display different content while I really do not want React to render multiple same DOMs. A code sample maybe look like below:

```<code><SingletonTooltip />
<SingletonTooltip />
<SingletonTooltip />
</code>```

And it will render 3 icons/buttons in the place I declare them but only renders one tooltip DOM when I click one of these icons/buttons.

A workaround I am not really into is:

```<code><TooltipIcon />
<TooltipIcon />
<TooltipIcon />
...
<TooltipContent />
</code>```

which brings extra effort to use and maintain code.

I have tried to save the instance in the state of component. However, this will make the component disconnected from the property passed by its parent.

Maybe React context will help? Looking forward to your guys suggestion.

答: Why not make one component that renders all the buttons and then only renders one content element based off which one was clicked? let each button invoke an onClick handler which is given to it as a prop and then use this to render only what you need. if you implemented some global state management solution you could use even allow more elements place content into the content element </p>

Title: Singleton tooltip design in React

Body:
Here is the case: I want to reuse a panel/callout/tooltip to display different content while I really do not want React to render multiple same DOMs. A code sample maybe look like below:

<SingletonTooltip />
<SingletonTooltip />
<SingletonTooltip />

And it will render 3 icons/buttons in the place I declare them but only renders one tooltip DOM when I click one of these icons/buttons.

A workaround I am not really into is:

<TooltipIcon />
<TooltipIcon />
<TooltipIcon />
...
<TooltipContent />

which brings extra effort to use and maintain code.

I have tried to save the instance in the state of component. However, this will make the component disconnected from the property passed by its parent.

Maybe React context will help? Looking forward to your guys suggestion.


问:
How can i have more than one buttons on action with search view?
Actually i want to make an action bar in which in should have dropdown menu , serach option,menu option and one other icon when i add drop down menu , the search bar is not on full action bar.when i click search icon the search view should be on full action bar but it only on half remaining is covered by dropdown menu

this is java code

```<code>@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mainpage, menu);
        getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.dropdown, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search, menu);

        MenuItem search_item = menu.findItem(R.id.mi_search);

        SearchView searchView = (SearchView) search_item.getActionView();
        searchView.setFocusable(false);
        searchView.setQueryHint("Search");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String s) {

                //clear the previous data in search arraylist if exist
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                     return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_alldocs) {
            // Handle the camera action
        } else if (id == R.id.nav_shared) {

        } else if (id == R.id.nav_tags) {

        } else if (id == R.id.notifications) {

        } else if (id == R.id.nav_settings) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

</code>```

this is xml of search view menu

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="codes4.com.simplelistview.MainActivity">

    <item

        android:id="@+id/mi_search"
        android:title="search something"
        app:showAsAction="always"

        app:actionViewClass="android.support.v7.widget.SearchView"
        />

</menu>
</code>```

this is xml of dropdown menu

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:title="ActionBar Spinner"
        app:actionViewClass="android.widget.Spinner"
        android:background="#ff00"
        app:showAsAction="always"
        />
</menu>
</code>```

答:
Perhaps, You should read the official documentation. You try to this code. Good luck!

```<code>import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Display the resulting frame
    cv2.imshow('frame',frame)
    cv2.imread('./your-dir/image.png', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
</code>```

more information click here

Body:
Actually i want to make an action bar in which in should have dropdown menu , serach option,menu option and one other icon when i add drop down menu , the search bar is not on full action bar.when i click search icon the search view should be on full action bar but it only on half remaining is covered by dropdown menu

this is java code

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mainpage, menu);
        getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.dropdown, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search, menu);

        MenuItem search_item = menu.findItem(R.id.mi_search);

        SearchView searchView = (SearchView) search_item.getActionView();
        searchView.setFocusable(false);
        searchView.setQueryHint("Search");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String s) {

                //clear the previous data in search arraylist if exist
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                     return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_alldocs) {
            // Handle the camera action
        } else if (id == R.id.nav_shared) {

        } else if (id == R.id.nav_tags) {

        } else if (id == R.id.notifications) {

        } else if (id == R.id.nav_settings) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

this is xml of search view menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="codes4.com.simplelistview.MainActivity">

    <item

        android:id="@+id/mi_search"
        android:title="search something"
        app:showAsAction="always"

        app:actionViewClass="android.support.v7.widget.SearchView"
        />

</menu>

this is xml of dropdown menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:title="ActionBar Spinner"
        app:actionViewClass="android.widget.Spinner"
        android:background="#ff00"
        app:showAsAction="always"
        />
</menu>

Body:
Perhaps, You should read the official documentation. You try to this code. Good luck!

import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Display the resulting frame
    cv2.imshow('frame',frame)
    cv2.imread('./your-dir/image.png', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

more information click here


问:
Dbpedia sparql gives empty result to my query, what is wrong?
I'm doing sparql query in this site.
It gives me an empty result, what is wrong with my query?

```<code>prefix foaf:    <http://xmlns.com/foaf/0.1/>
select * where {
?s rdf:type foaf:Person.

} LIMIT 100
</code>```

This query is ok, but when I add the second pattern, I got empty result.

?s foaf:name 'Abraham_Robinson'.

```<code>prefix foaf:    <http://xmlns.com/foaf/0.1/>
select * where {
?s rdf:type foaf:Person.
?s foaf:name 'Abraham_Robinson'.
} LIMIT 100
</code>```

How to correct my query so the result includes this record:

http://dbpedia.org/resource/Abraham_Robinson

答:
The following query should work. Right now it isn't working due to a need to refresh the text index associated with this instance (currently in progress):

```<code>PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
SELECT * where {
?s rdf:type foaf:Person.
?s foaf:name "'Abraham Robinson'".
}
LIMIT 100
</code>```

Note how the phrase is placed within single-quotes that are within double-quotes.

If the literal content is language-tagged, as is the case in DBpedia the exact-match query would take the form (already clarified in @TallTed's response):

```<code>PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
SELECT * where {
?s rdf:type foaf:Person.
?s foaf:name 'Abraham Robinson'@en.
}
LIMIT 100
</code>```

This SPARQL Results Page Link should produce a solution when the index update completes.

Body:
I'm doing sparql query in this site.
It gives me an empty result, what is wrong with my query?

prefix foaf:    <http://xmlns.com/foaf/0.1/>
select * where {
?s rdf:type foaf:Person.

} LIMIT 100

This query is ok, but when I add the second pattern, I got empty result.

?s foaf:name 'Abraham_Robinson'.

prefix foaf:    <http://xmlns.com/foaf/0.1/>
select * where {
?s rdf:type foaf:Person.
?s foaf:name 'Abraham_Robinson'.
} LIMIT 100

How to correct my query so the result includes this record:

http://dbpedia.org/resource/Abraham_Robinson

Body:
The following query should work. Right now it isn't working due to a need to refresh the text index associated with this instance (currently in progress):

PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
SELECT * where {
?s rdf:type foaf:Person.
?s foaf:name "'Abraham Robinson'".
}
LIMIT 100

Note how the phrase is placed within single-quotes that are within double-quotes.

If the literal content is language-tagged, as is the case in DBpedia the exact-match query would take the form (already clarified in @TallTed's response):

PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
SELECT * where {
?s rdf:type foaf:Person.
?s foaf:name 'Abraham Robinson'@en.
}
LIMIT 100

This SPARQL Results Page Link should produce a solution when the index update completes.


问:
Constructing the hashed token signature for cosmos DB
I am trying to create hashed token for creating a document in cosmos db but I am always getting 405 method not allowed, can someone verify whether the below format I provided is correct or not?</p>

```<code>url = https://cosmos-test-cache.documents.azure.com/dbs/FamilyDB/colls/FamilyCollection/docs/123456
ResourceLink = /dbs/FamilyDB/colls/FamilyCollection/docs/123456
ResourceType = docs
HTTP verb = POST

Response

{
  "code": "MethodNotAllowed",
  "message": "RequestHandler.Post"
}
</code>```

答:
To add to the above answer, for post calls to create hash token</p>

```<code>Resource method:Post
Resource Id:dbs/{dbs}/colls/{colls}
Resource Type:docs
and the url should be
dbs/{dbs}/colls/{colls}/docs
</code>```

Body:
I am trying to create hashed token for creating a document in cosmos db but I am always getting 405 method not allowed, can someone verify whether the below format I provided is correct or not?

url = https://cosmos-test-cache.documents.azure.com/dbs/FamilyDB/colls/FamilyCollection/docs/123456
ResourceLink = /dbs/FamilyDB/colls/FamilyCollection/docs/123456
ResourceType = docs
HTTP verb = POST

Response

{
  "code": "MethodNotAllowed",
  "message": "RequestHandler.Post"
}

Body:
To add to the above answer, for post calls to create hash token

Resource method:Post
Resource Id:dbs/{dbs}/colls/{colls}
Resource Type:docs
and the url should be
dbs/{dbs}/colls/{colls}/docs


问:
Move focus on GridView item one by one
I'm designing app for pc and xbox. Now facing a tricky problem.

I have a GridView, which is one row enabled. So the focus can move left/right. I have calculated the item's width, so in the user visual area, there are always 4 items visible.

On my pc, when the focus moves left/right, it seems good as expected.
But on my xbox, when move item to right, the items always show a part.

More clearly, here are two videos.

Pc

Xbox

Note on xbox, when I move focus to
 , the next item show a part of it.

So, how to disable the next item shows part of it, just act like pc. When the focus is on it, the item shows. When the focus is not on it, do not show it.

In the PreviewKeyDown event, I use

```<code>                case VirtualKey.Right:
                case VirtualKey.GamepadDPadRight:
                case VirtualKey.GamepadLeftThumbstickRight:
                    if (itemIndexInCurrentRiver + 1 <= currentRiver.Items.Count - 1)
                    {
                        currentRiver.Focus(FocusState.Programmatic);

                        GridViewItem item = new GridViewItem();
                        item = currentRiver.ContainerFromIndex(listIndexsInEachRiver[riverIndexInAllRivers]) as GridViewItem;
                        listIndexsInEachRiver[riverIndexInAllRivers] = itemIndexInCurrentRiver + 1;

                        item.Focus(FocusState.Programmatic);
                        item.IsSelected = true;
                        item.StartBringIntoView();

                        e.Handled = false;
                    }
                    else
                        e.Handled = true;
                    break;
</code>```

答:
I checked your video record, If you want to make Xbox GridView display same as pc, you need turn off overscan border manually.

Xbox Settings> Display&Sound> Video output, under "Advanced" select "Video fidelity & overscan" You will see an option that says "Apps can add a border", turn if off.

Unfortunately, we have not provide api could turn if off programmatically. Please feel free post it on the UserVoice. And you could also share code sample for us, We will check if there is other workaround for this.

Title: Move focus on GridView item one by one

Body:
I'm designing app for pc and xbox. Now facing a tricky problem.

I have a GridView, which is one row enabled. So the focus can move left/right. I have calculated the item's width, so in the user visual area, there are always 4 items visible.

On my pc, when the focus moves left/right, it seems good as expected.
But on my xbox, when move item to right, the items always show a part.

More clearly, here are two videos.

Pc

Xbox

Note on xbox, when I move focus to
 , the next item show a part of it.

So, how to disable the next item shows part of it, just act like pc. When the focus is on it, the item shows. When the focus is not on it, do not show it.

In the PreviewKeyDown event, I use

                case VirtualKey.Right:
                case VirtualKey.GamepadDPadRight:
                case VirtualKey.GamepadLeftThumbstickRight:
                    if (itemIndexInCurrentRiver + 1 <= currentRiver.Items.Count - 1)
                    {
                        currentRiver.Focus(FocusState.Programmatic);

                        GridViewItem item = new GridViewItem();
                        item = currentRiver.ContainerFromIndex(listIndexsInEachRiver[riverIndexInAllRivers]) as GridViewItem;
                        listIndexsInEachRiver[riverIndexInAllRivers] = itemIndexInCurrentRiver + 1;

                        item.Focus(FocusState.Programmatic);
                        item.IsSelected = true;
                        item.StartBringIntoView();

                        e.Handled = false;
                    }
                    else
                        e.Handled = true;
                    break;


问:
Downloading through IE in Perl
I want to know a way in which I can monitor the download of an application in IE through Perl. I am doing automation, and as soon as the download completes, I need to start a Perl script for processing the downloaded application. The download has to be done through IE. I found out IE::Mechanize and LWP::Simple in Perl but I want something which is a combination of both. I also looked at URLDownloadToFile but couldn't understand how to implement it in Perl.

答:
If you want to use Perl through a browser (IE), use Selenium RC.

Other than that, for web automation I usually use WWW::Mechanize.

Title: Downloading through IE in Perl


问:
How can I access a self-signed webserver using SSL but from another computer on LAN?
Problem: Since Chrome updated a while back (version 58?), I'm not able to access my computer's development Express web server with HTTPS from a remote machine on the same private LAN.

I have created a self-signed certificate on the server (my laptop), and it works great from the same machine via https://localhost:8383 (the local SSL port).

In the past I could bypass the warning on a remote machine on the same network but it has stopped working.

I've gone through the steps of creating a local secure DNS server on my own router with DD-WRT, and self-signed a new certificate with SAN so I could use a DNS host name to access it without specifying an IP address.

I'm able to get to the page after bypassing the message that warns the site's SSL certificate could not be verified. But that's not good enough because while the site will load, the underlying websocket service I'm using on the same port does not work, and so the application loads but is broken on the remote machine. Still works on the local machine because the certificate is valid.

It seems the issue centers around Websockets within Express.

Any guidance would be greatly appreciated! This is a strictly secure environment that's meant to be used on a private network and it makes no sense for me to spend a bunch of money on a public certificate if that even matters.

Thank you.

答:
It appears that the issue is with mobile Chrome and Safari on IOS -- I can get untrusted SSL certificates to work with websockets from another computer on the same network with the latest versions of Chrome and Safari. But on IOS (ipads and iphones), the page will load after being prompted, but Websockets FAIL to function whatsoever.

I've found a couple other people finding this issue.

My workaround for this problem was to revert away from SSL for my private network and completely avoid self-signed certificates.

In a private environment this is OK.


问:
Gathering multiple data columns currently in factor form
I have a dataset of train carloads. It currently has a number (weekly carload) listed for each company (the row) for each week (the columns) over the course of a couple years (100+ columns). I want to gather this into just two columns: a date and loads.

It currently looks like this:

```<code>3/29/2017  4/5/2017  4/12/2017  4/19/2017
32.7       31.6      32.3       32.5
20.5       21.8      22.0       22.3
24.1       24.1      23.6       23.4
24.9       24.7      24.8       26.5
</code>```

I'm looking for:

```<code>Date        Load
3/29/2017   32.7
3/29/2017   20.5
3/29/2017   24.1
3/29/2017   24.9
4/5/2017    31.6
</code>```

I've been doing various versions of the following:

rail3 <- rail2 %>%
  gather(`3/29/2017`:`1/24/2018`, key = "date", value = "loads")
```

<p>When I do this it makes a dataset called rail3, but it didn't make the new columns I wanted. It only made the dataset 44 times longer than it was. And it gave me the following message: </p>

```Warning message:
attributes are not identical across measure variables;
they will be dropped
```

<p>I'm assuming this is because the date columns are currently coded as factors. But I'm also not sure how to convert 100+ columns from factors to numeric. I've tried the following and various other methods:</p>

<pre class="lang-r prettyprint-override"><code>rail2["3/29/2017":"1/24/2018"] <- lapply(rail2["3/29/2017":"1/24/2018"], as.numeric)
</code>```

None of this has worked. Let me know if you have any advice. Thanks!

Body:
I have a dataset of train carloads. It currently has a number (weekly carload) listed for each company (the row) for each week (the columns) over the course of a couple years (100+ columns). I want to gather this into just two columns: a date and loads.

It currently looks like this:

3/29/2017  4/5/2017  4/12/2017  4/19/2017
32.7       31.6      32.3       32.5
20.5       21.8      22.0       22.3
24.1       24.1      23.6       23.4
24.9       24.7      24.8       26.5

I'm looking for:

Date        Load
3/29/2017   32.7
3/29/2017   20.5
3/29/2017   24.1
3/29/2017   24.9
4/5/2017    31.6

I've been doing various versions of the following:

rail3 <- rail2 %>%
  gather(`3/29/2017`:`1/24/2018`, key = "date", value = "loads")

When I do this it makes a dataset called rail3, but it didn't make the new columns I wanted. It only made the dataset 44 times longer than it was. And it gave me the following message:

Warning message:
attributes are not identical across measure variables;
they will be dropped

I'm assuming this is because the date columns are currently coded as factors. But I'm also not sure how to convert 100+ columns from factors to numeric. I've tried the following and various other methods:

rail2["3/29/2017":"1/24/2018"] <- lapply(rail2["3/29/2017":"1/24/2018"], as.numeric)

None of this has worked. Let me know if you have any advice. Thanks!

Body:
Here is a possible solution:

rail2<-read.table(header=TRUE, text="3/29/2017  4/5/2017  4/12/2017  4/19/2017
32.7       31.6      32.3       32.5
20.5       21.8      22.0       22.3
24.1       24.1      23.6       23.4
24.9       24.7      24.8       26.5", check.names=FALSE)

library(tidyr)
# gather the data from columns and convert to long format.
rail3 <- rail2 %>% gather(key="date", value="load")

rail3
#        date load
#1  3/29/2017 32.7
#2  3/29/2017 20.5
#3  3/29/2017 24.1
#4  3/29/2017 24.9
#5   4/5/2017 31.6
#6   4/5/2017 21.8
#7 ...


问:
Migration application from Applet
Our application runs on Java applet, we are planning to migrate from Applet, but not before 2019
Please let me know if Applet IE 11 compatibility plugin can get removed in near future or not.
How long APIs needed to support Applets in Internet Explorer 11 will be available?</p>

答:
Not sure, about which Applet IE 11 compatibility plugin you are talking here.

There is a setting in Internet Explorer options. If you enable it than you will be able to run the JAVA Applet. This setting will remain there and it will not get removed from IE 11.

You can refer the steps below to enable JAVA Applet scripting in IE.

(1) Click Tools and then Internet Options

(2) Select the Security tab, and select the Custom Level button

(3) Scroll down to Scripting of Java applets

(4) Make sure the Enable radio button is checked

(5) Click OK to save your preference

Title: Migration application from Applet


问:
Htaccess rules http to https redirecting too many times
I am using simple htaccess rules to redirect http to https but it breaks the page and shows an error "Redirecting too many times" . Here is my code

Approach -1

```<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

Approach -2

```<code>RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

I tried both approaches but its not working. Here is the error i get:

答:
You either have additional redirects that match similar conditions in your .htaccess or you are using a reverse proxy such as Cloudflare that also does https redirection.

Comment out your rewrite rules and sort them by the order that you want them to execute in the order of "general/generic" to "specific".  Un-comment them one at a time and test them.

Disable the https redirects built into your reverse proxy to test.

If you manage virtual hosts you may want to check at that level as well.

Body:
I am using simple htaccess rules to redirect http to https but it breaks the page and shows an error "Redirecting too many times" . Here is my code

Approach -1

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Approach -2

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

I tried both approaches but its not working. Here is the error i get:


问:
How to install packages (like tweepy, textblob etc.) in Anaconda?
I want to use the twitter API. But in order to use that package named tweepy should be installed.

I tried installing it using the command conda install tweepy on the Anaconda Command Prompt.

But every time, the installation failed.

Can anyone please tell me how to install a package in Anaconda.

答:
You can please try:

```<code>conda install -c conda-forge tweepy
</code>```

Source: tweepy

Body:
You can please try:

conda install -c conda-forge tweepy

Source: tweepy