问:
Show Google Map In Modal After Ajax Call
so I'm working on a site where I want to show a google map inside a modal after an ajax call. I'm using bootstrap to show a modal, the problem is the map just stays blank after the modal is opened.

Something weird that happens is when I hit f12 on chrome to bring up the developer tab the map magically shows up although not centered on the marker position.

This is my Ajax Call:

```<code>$('.btnSeeOrder').on("click", function(){
    $("#modalSeeOrder").modal("show"); //open bootstrap modal
    var order_id = $(this).attr("data-orderId");

    $.ajax({
      type: "POST",
      url: "get_order_details.php",
      data: {
        order_id: order_id
      },
      beforeSend: function(){
        $(".order-details-modal").html("<i class='glyphicon glyphicon-refresh spinning'></i>");
      },
      success: function(data){
        $(".order-details-modal").html(data);
      },
      error: function(){
        $(".order-details-modal").html("<b>Ooops... Error....</b>");
      }
    });
  });
</code>```

This is my get_order_details.php file:

```<code><?php
  require '../../../app/Functions.php';
  $obj = new Admin_Functions();

  //Get order info, user info and map
  $info = $obj->getOrderInfo($_POST['order_id']);

?>

<div class="row">
  <div class="col-lg-12" style="margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px solid #ccc;">
    <div class="row">
      <div id="map-canvas" style="width: 100%; height: 400px;"></div>

    </div>
  </div>
</div>

<script type="text/javascript">
// latitude and longitude are being loaded in from the database
// example coords from database: 50.44444,-19.444444

var myLatlng = new google.maps.LatLng(<?php echo explode(",", $info["lat_lng"])[0]; ?>,<?php echo explode(",", $info["lat_lng"])[1]; ?>);
var mapOptions = {
  zoom: 16,
  center: myLatlng,
  styles:
  [{"featureType":"landscape","elementType":"geometry","stylers":[{"saturation":"-100"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#e9e5dc"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels.text","stylers":[{"color":"#545454"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"saturation":"-87"},{"lightness":"-40"},{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.fill","stylers":[{"color":"#f0f0f0"},{"saturation":"-22"},{"lightness":"-16"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.highway.controlled_access","elementType":"labels.icon","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road.local","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"saturation":"-52"},{"hue":"#00e4ff"},{"lightness":"-16"}]}]
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  icon: 'https://www.robotevents.com/images/maps/markers/orange.png'
});
</script>
</code>```

This is what the map looks like when loaded in:

Anyone know how I can fix or go about this issue? Any help is greatly appreciated!

答:
Trying add this in your CSS class

```<code>._gmaps_cdv_{
    background-color: transparent !;
    padding: 0px !important;
}
</code>```

Or verify if you put in your script tag for google maps attr async

Body:
so I'm working on a site where I want to show a google map inside a modal after an ajax call. I'm using bootstrap to show a modal, the problem is the map just stays blank after the modal is opened.

Something weird that happens is when I hit f12 on chrome to bring up the developer tab the map magically shows up although not centered on the marker position.

This is my Ajax Call:

$('.btnSeeOrder').on("click", function(){
    $("#modalSeeOrder").modal("show"); //open bootstrap modal
    var order_id = $(this).attr("data-orderId");

    $.ajax({
      type: "POST",
      url: "get_order_details.php",
      data: {
        order_id: order_id
      },
      beforeSend: function(){
        $(".order-details-modal").html("");
      },
      success: function(data){
        $(".order-details-modal").html(data);
      },
      error: function(){
        $(".order-details-modal").html("Ooops... Error....");
      }
    });
  });

This is my get_order_details.php file:

<?php
  require '../../../app/Functions.php';
  $obj = new Admin_Functions();

  //Get order info, user info and map
  $info = $obj->getOrderInfo($_POST['order_id']);

?>

This is what the map looks like when loaded in:

Anyone know how I can fix or go about this issue? Any help is greatly appreciated!

Body:
Trying add this in your CSS class

._gmaps_cdv_{
    background-color: transparent !;
    padding: 0px !important;
}

Or verify if you put in your script tag for google maps attr async


来源: stackexchange

问:
Modifying pi-config values using python
I'm trying to create a python script that will toggle my pi3 /boot/config.txt files gpu_mem=156 parameter for desktop and game mode. I have tried looking into ConfigParser but the config file I'm using uses a simpler format of simply:

```<code>var1=value0
var2=value1
</code>```

I would appreciate some advice.

答:
If you are using a text file to store your config you can parse it like

```<code>with open('config.txt', 'r') as config:
    for line in config.read().splitlines():
        var, val = line.split('=')
        print var, val
</code>```

But if you are storing your config that can be parsed by ConfigParser in the following format

```<code>[global]
var1=value0
var2=value1
</code>```

Then you can parse it with ConfigParser like so

```<code>import ConfigParser

config_parser = ConfigParser.ConfigParser()
config_parser.read('config.txt')
print config_parser.get('global', 'var1')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Modifying pi-config values using python

Body:
I'm trying to create a python script that will toggle my pi3 /boot/config.txt files gpu_mem=156 parameter for desktop and game mode. I have tried looking into ConfigParser but the config file I'm using uses a simpler format of simply:

var1=value0
var2=value1

I would appreciate some advice.

Body:
If you are using a text file to store your config you can parse it like

with open('config.txt', 'r') as config:
    for line in config.read().splitlines():
        var, val = line.split('=')
        print var, val

But if you are storing your config that can be parsed by ConfigParser in the following format

[global]
var1=value0
var2=value1

Then you can parse it with ConfigParser like so

import ConfigParser

config_parser = ConfigParser.ConfigParser()
config_parser.read('config.txt')
print config_parser.get('global', 'var1')


问:
Regarding Ajax in UserControl
We have created a  UserControl. Inside user control we are creating an update panel. Inside the panel we are creating various controls such as TextBox, Button, DropDownList and ListBox and event associated with them buttonclick(),DropDown_selectedIndexChanged(),TextBox_TextChenged() etc. All the controls(including update panel) are created programatically using c#.
To ajaxify the events we have used ScriptManager.

ScriptManager is added on OnInit function programatically like as shown:

```<code>ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            if (scriptManager == null)
            {
                scriptManager = new ScriptManager();
                //scriptManager.EnablePartialRendering = true;
                this.Controls.AddAt(0,scriptManager);
            }
</code>```

Every time after page load only one event get fired  partial postback(which is desired) but after that no event gets fired .

All valid changes have already been done in web.config file for AJAX .
Please suggest the possible cause and solution of the problem.

答:
On a partial postback, the ScriptManager will not be added because you are trying to add it outside the UpdatePanel (where it has to be). This works on the first page load because it's not a partial postback. But after the partial postback, the dynamically added ScriptManager won't be available to the page, and because you are trying to add it outside the UpdatePanel -- AddAt(0,...) - after a partial postback, it won't actually be added. On a partial postback you can only affect things inside the UpdatePanel that initiated the postback.

Bottom line is, you really can't add a ScriptManager dynamically, since it will never be there after a partial postback. Just like you can't dynamically add any other control outside of an UpdatePanel after an event sourced inside it.

ContentLicense: CC BY-SA 2.5

Title: Regarding Ajax in UserControl

Body:
We have created a  UserControl. Inside user control we are creating an update panel. Inside the panel we are creating various controls such as TextBox, Button, DropDownList and ListBox and event associated with them buttonclick(),DropDown_selectedIndexChanged(),TextBox_TextChenged() etc. All the controls(including update panel) are created programatically using c#.
To ajaxify the events we have used ScriptManager.

ScriptManager is added on OnInit function programatically like as shown:

ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            if (scriptManager == null)
            {
                scriptManager = new ScriptManager();
                //scriptManager.EnablePartialRendering = true;
                this.Controls.AddAt(0,scriptManager);
            }

Every time after page load only one event get fired  partial postback(which is desired) but after that no event gets fired .

All valid changes have already been done in web.config file for AJAX .
Please suggest the possible cause and solution of the problem.


问:
Can I initialize Firebase without using google-services.json?
EDIT: I should emphasize, I have flavors, for which I don't want to use any of these Google services, and attempting to apply the google-services plugin in such a case, without having an applicable google-services.json, would result in a failed build.

I would like to be able to initialize the Firebase SDK, specifically to use the Remote Config, WITHOUT using the google-services.json.

I see that FirebaseApp has an initialize method, which receives a FirebaseOptions object.

I've built the FirebaseOptions with values provided in the google-services.json, and after a call to FirebaseApp.initialize with these options, I always get

```<code>FirebaseInitProvider: FirebaseApp initialization unsuccessful
</code>```

I know it's the recommended way to use the google-services.json file, but I need to be able to make the app call different Firebase projects, depending on debug/release builds, while keeping the package name the same.

The way I would like to do this is to have a debug/release pairs for all values necessary to initialize Firebase, and then dynamically do the initialization.

```<code>        FirebaseOptions options = new FirebaseOptions.Builder()
                .setApplicationId(appId)
                .setApiKey(apiKey)
                .setGcmSenderId(appContext.getString(
                        isDebug ? R.string.firebase_testing_gcm_sender_id :
                                R.string.firebase_production_gcm_sender_id))
                .setDatabaseUrl(appContext.getString(
                        isDebug ? R.string.firebase_testing_database_url :
                                R.string.firebase_production_database_url))
                .setStorageBucket(
                        appContext.getString(
                                isDebug ? R.string.firebase_testing_storage_bucket :
                                        R.string.firebase_production_storage_bucket))
                .build();
        FirebaseApp.initializeApp(appContext, options);
</code>```

So far it doesn't seem to work.

All help is greatly appreciated!

答:
I've found interesting workaround. Try the following:
put your google-services.json to any sample app google provides for Firebase integration. Compile it.

Take a look on path app/build/generated/res/google-services/debug/values/  there should be generated values.xml file with bunch of strings mentioned in errors you described. Copy these strings to value.xml file of your project. That's it.

Body:
EDIT: I should emphasize, I have flavors, for which I don't want to use any of these Google services, and attempting to apply the google-services plugin in such a case, without having an applicable google-services.json, would result in a failed build.

I would like to be able to initialize the Firebase SDK, specifically to use the Remote Config, WITHOUT using the google-services.json.

I see that FirebaseApp has an initialize method, which receives a FirebaseOptions object.

I've built the FirebaseOptions with values provided in the google-services.json, and after a call to FirebaseApp.initialize with these options, I always get

FirebaseInitProvider: FirebaseApp initialization unsuccessful

I know it's the recommended way to use the google-services.json file, but I need to be able to make the app call different Firebase projects, depending on debug/release builds, while keeping the package name the same.

The way I would like to do this is to have a debug/release pairs for all values necessary to initialize Firebase, and then dynamically do the initialization.

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setApplicationId(appId)
                .setApiKey(apiKey)
                .setGcmSenderId(appContext.getString(
                        isDebug ? R.string.firebase_testing_gcm_sender_id :
                                R.string.firebase_production_gcm_sender_id))
                .setDatabaseUrl(appContext.getString(
                        isDebug ? R.string.firebase_testing_database_url :
                                R.string.firebase_production_database_url))
                .setStorageBucket(
                        appContext.getString(
                                isDebug ? R.string.firebase_testing_storage_bucket :
                                        R.string.firebase_production_storage_bucket))
                .build();
        FirebaseApp.initializeApp(appContext, options);

So far it doesn't seem to work.

All help is greatly appreciated!


问:
Install a python package in a virtual environment directly from git
I have a python package I want to use, but it appears that the version installed through pip is seriously outdated, to the point where example code doesn't work.  some research independently verified that in order to get the code to work properly, I need the latest version from git.

How do I install a python package from within a virtual environment directly from git without going through pip?

Alternatively, since I don't know too much about pip, if this should never be necessary, then how do I force pip to install the latest version on github?

答:
You'll want to reference this documentation.

Here's the basic format:

```<code>pip install -e vcs+protocol://repo_url/#egg=pkg&subdirectory=pkg_dir
</code>```

In the case of git it'd be something like

```<code>pip install -e git+https://www.github.com/name_your_project/name_your_repo
</code>```

Body:
You'll want to reference this documentation.

Here's the basic format:

pip install -e vcs+protocol://repo_url/#egg=pkg&subdirectory=pkg_dir

In the case of git it'd be something like

pip install -e git+https://www.github.com/name_your_project/name_your_repo


问:
inline code causes ASP.NET to insert 500 page inside the current page
I have some code in an .ascx that looks like this:

```<code><%
 int a = 0;
 int b = 5;
 int c = b/a;
 %>
</code>```

Throws a 500 error as you would expect (division by 0).

CustomErrors looks like this

```<code>    <customErrors mode="On" redirectMode="ResponseRewrite">
        <error statusCode="500" redirect="/500.aspx" />
    </customErrors>
</code>```

I get a messed up render of the page I'm trying to hit.  Viewing the source, I see half the normal page THEN the 500 page follows it.

```<code>    <div class="mapTextOverlay" style="width:448px;padding-left:232.96px;">

    [main page abruptly ends here and the 500 page starts]

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head"><title>
        500
    </title>

    [etc.]
</code>```

So the server transfer is happening in the middle of the page render.

How do I prevent the possibility of a partial-page render in the case of a 500 error?

This only happens with inline code, if the error is in code-behind the error displays normally.

Nothing in the code is calling Response.Flush()

Response.BufferOutput is true

The code is setting a Response.Filter, but I tried commenting that and it did not fix it

答:
I still don't know why this is happening, but the fix turns out to be rather simple.

Put Response.Clear(); in the Page_Load()of the 500 page.

Body:
I have some code in an .ascx that looks like this:

<%
 int a = 0;
 int b = 5;
 int c = b/a;
 %>

Throws a 500 error as you would expect (division by 0).

CustomErrors looks like this

    <customErrors mode="On" redirectMode="ResponseRewrite">
        <error statusCode="500" redirect="/500.aspx" />
    </customErrors>

I get a messed up render of the page I'm trying to hit.  Viewing the source, I see half the normal page THEN the 500 page follows it.

    [main page abruptly ends here and the 500 page starts]

    <!DOCTYPE html>

    <title>
        500
    </title>

    [etc.]

So the server transfer is happening in the middle of the page render.

How do I prevent the possibility of a partial-page render in the case of a 500 error?

This only happens with inline code, if the error is in code-behind the error displays normally.

Nothing in the code is calling Response.Flush()

Response.BufferOutput is true

The code is setting a Response.Filter, but I tried commenting that and it did not fix it


问:
Is it possible to configure Firebase analytics without google-services.json configuration file?
I would like to use Firebase analytics for one of my library modules. I would like to program in such a way that configuration file (google-services.json) should be accessible from either client app folder or configure the same from the client side.

Is there a way I could implement the above mentioned scenario?

Thanks in advance.

Body:
I've found interesting workaround. Try the following:
put your google-services.json to any sample app google provides for Firebase integration. Compile it.

Take a look on path app/build/generated/res/google-services/debug/values/  there should be generated values.xml file with bunch of strings mentioned in errors you described. Copy these strings to value.xml file of your project. That's it.


问:
JavaScript get php array and post key + vaule to body
I'm new to coding and i have no idea why this is not working
please explain so i can learn, Thank You.
EDIT: Moving PHP to top is still not printing any thing.

```<code>        <?php
           //create array
            $someArray = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
            //encode array
            $someJSON = json_encode($someArray);
            //pritn array
        ?>

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                var array = "<?PHP echo $someJSON?>";
                var arrayDecode = jQuery.parseJSON(array);
                $.each(arrayDecode, function(key, value){
                    $('body').append(key + value + "<br><br>");
                });
            });
        </script>
    </head>
    <body>
    </body>
</html>
</code>```

答:
Try This.
You Need to Declare PHP Variable Before use in JS Script.
Otherwise the variable doesn't have any value and it will return error. </p>

```<code><!DOCTYPE html>
<html>
 <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <?php
   //create array
   $someArray = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
   //encode array
   $someJSON = json_encode($someArray);
   ?>
<script>
   $(document).ready(function(){
     var array = '<?php echo $someJSON; ?>';
     arrayDecode = jQuery.parseJSON(array);
     $.each(arrayDecode, function(key, value){
       $('body').append(key + value + "<br><br>");
    });
  });
</script>
</head>
<body>

</body>
</html>
</code>```

Body:
I'm new to coding and i have no idea why this is not working
please explain so i can learn, Thank You.
EDIT: Moving PHP to top is still not printing any thing.

        <?php
           //create array
            $someArray = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
            //encode array
            $someJSON = json_encode($someArray);
            //pritn array
        ?>

<!DOCTYPE html>

Body:
Try This.
You Need to Declare PHP Variable Before use in JS Script.
Otherwise the variable doesn't have any value and it will return error.

<!DOCTYPE html>
<html>
 <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <?php
   //create array
   $someArray = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
   //encode array
   $someJSON = json_encode($someArray);
   ?>
<script>
   $(document).ready(function(){
     var array = '<?php echo $someJSON; ?>';
     arrayDecode = jQuery.parseJSON(array);
     $.each(arrayDecode, function(key, value){
       $('body').append(key + value + "<br><br>");
    });
  });
</script>
</head>
<body>

</body>
</html>


问:
Rmarkdown crop white space around ggplots
Although I use a horizontal barplot as an example here, that itself is not the issue. The general issue is how to deal with the white space that is created around ggplots in rmarkdown after using

+coord_fixed(ratio=...)

To reduce the space used by barplots, especially with few factor, I prefer horizontal barplots, where I use coord_fixed(ratio=...) to have a sensible ratio between width and length of the bars.

The plot itself looks the way I want to (see first example below), but it has a lot of white space around it, which I tried to remove by using fig.height = ... in the knitr-header. As the next example shows, this didn't turn out well.

```<code>library(ggplot2)
library(ggstance)
library(dplyr)

X <- data.frame(X = sample(c("A", "B"), 30, replace = TRUE))
X <- X %>% group_by(X) %>% summarise(n = n())
ggplot(X, aes(y = X, x = n))+
   geom_barh(stat = "identity")+
   coord_fixed(ratio = 1)+
   ggtitle("blub")
</code>```

Using this inside rmarkdown where I used x = 3  ; x = 1  ; x=0.5:

```<code>```{r,fig.height = x}

# see code above
```
</code>```

This results in:

fig.height=3

fig.height=1

fig.height=0.5

What I hoped it would do:

Crop the white margins

while keeping the plot (plot + (axis)titles) area itself constant

The latter clearly doesn't happen as the plot area gets narrower and the titles are moved to the inside of the plot.

I don't know if the solution is to be found inside ggplot or inside knitr. On top of that, an ideal solution should be easily automated for use inside a loop (adapt the solution to changing number of factors).

答:
You can pass parameters to the fig.width and fig.height chunk options. You just have to calculate them before evaluating that chunk:

```<code>---
output: html_document
---

```{r, message=FALSE}
library(ggplot2)
library(ggstance)
library(dplyr)

X <- data.frame(X = sample(c("A", "B"), 30, replace = TRUE))
X <- X %>% group_by(X) %>% summarise(n = n())

hei <- length(X$X) + 1
len <- max(X$n) + 2

```

Text before the plot
```{r, fig.height=hei, fig.width=len, echo=FALSE}

ggplot(X, aes(y = X, x = n))+
  geom_barh(stat = "identity")+
  coord_fixed(ratio = 1)+
  ggtitle("blub") +
  theme(plot.background = element_rect(fill = 'red'))

```

Text after the plot

```{r, message=FALSE}

X <- data.frame(X = sample(c("A", "B", "C"), 30, replace = TRUE))
X <- X %>% group_by(X) %>% summarise(n = n())

hei <- length(X$X) + 1
len <- max(X$n) + 2

```
Another plot
```{r, fig.height=hei, fig.width=len, echo=FALSE}

ggplot(X, aes(y = X, x = n))+
  geom_barh(stat = "identity")+
  coord_fixed(ratio = 1)+
  ggtitle("blub") +
  theme(plot.background = element_rect(fill = 'red'))

```
</code>```

Result:

Body:
Although I use a horizontal barplot as an example here, that itself is not the issue. The general issue is how to deal with the white space that is created around ggplots in rmarkdown after using

+coord_fixed(ratio=...)

To reduce the space used by barplots, especially with few factor, I prefer horizontal barplots, where I use coord_fixed(ratio=...) to have a sensible ratio between width and length of the bars.

The plot itself looks the way I want to (see first example below), but it has a lot of white space around it, which I tried to remove by using fig.height = ... in the knitr-header. As the next example shows, this didn't turn out well.

library(ggplot2)
library(ggstance)
library(dplyr)

X <- data.frame(X = sample(c("A", "B"), 30, replace = TRUE))
X <- X %>% group_by(X) %>% summarise(n = n())
ggplot(X, aes(y = X, x = n))+
   geom_barh(stat = "identity")+
   coord_fixed(ratio = 1)+
   ggtitle("blub")

Using this inside rmarkdown where I used x = 3  ; x = 1  ; x=0.5:

```{r,fig.height = x}

# see code above
```

This results in:

fig.height=3

fig.height=1

fig.height=0.5

What I hoped it would do:

Crop the white margins

while keeping the plot (plot + (axis)titles) area itself constant

The latter clearly doesn't happen as the plot area gets narrower and the titles are moved to the inside of the plot.

I don't know if the solution is to be found inside ggplot or inside knitr. On top of that, an ideal solution should be easily automated for use inside a loop (adapt the solution to changing number of factors).

Body:
You can pass parameters to the fig.width and fig.height chunk options. You just have to calculate them before evaluating that chunk:

---
output: html_document
---

```{r, message=FALSE}
library(ggplot2)
library(ggstance)
library(dplyr)

X <- data.frame(X = sample(c("A", "B"), 30, replace = TRUE))
X <- X %>% group_by(X) %>% summarise(n = n())

hei <- length(X$X) + 1
len <- max(X$n) + 2

```

Text before the plot
```{r, fig.height=hei, fig.width=len, echo=FALSE}

ggplot(X, aes(y = X, x = n))+
  geom_barh(stat = "identity")+
  coord_fixed(ratio = 1)+
  ggtitle("blub") +
  theme(plot.background = element_rect(fill = 'red'))

```

Text after the plot

```{r, message=FALSE}

X <- data.frame(X = sample(c("A", "B", "C"), 30, replace = TRUE))
X <- X %>% group_by(X) %>% summarise(n = n())

hei <- length(X$X) + 1
len <- max(X$n) + 2

```
Another plot
```{r, fig.height=hei, fig.width=len, echo=FALSE}

ggplot(X, aes(y = X, x = n))+
  geom_barh(stat = "identity")+
  coord_fixed(ratio = 1)+
  ggtitle("blub") +
  theme(plot.background = element_rect(fill = 'red'))

```

Result:


问:
Setting a property of all objects of an Iterable
is there a smart way to set a property of all objects of an Iterable to a specified value?

I have a class SystemUser that looks like that:

```<code>class SystemUser{
  private String name;
  private String password;
  ...
}
</code>```

and another class that generates an Iterable object like:

```<code>public Iterable<SystemUser> getUsers(){
   ...
   return users;
}
</code>```

Can I set the attribute "password" of all objects of the Iterable to null without iterating?

Thanks!

答:
Any way to apply any function to item You need to iterate over all element and change the value.There is lot of 3rd party library available for this purpose like
GUAVA OR as suggested above foreach.

Util using generic

```<code>public static <T> void apply(Iterable<T> iterable, Function<T, Void> function) {
    for (T input : iterable)
        function.apply(input);
}
</code>```

using guava

```<code>final List<String> list = Arrays.asList("race", "box");
final List<String> transformed =
    Lists.newArrayList(Iterables.transform(list, new Function<String, String>() {

        @Override
        public String apply(final String input) {
            return new StringBuilder().append(input).append("car").toString();
        }
    }));
</code>```

Using for-each

```<code>// Suppose that I have already init the list of car
List<Car> cars = //...
List<String> names = new ArrayList<String>();

// LAMBDA EXPRESSION
cars.forEach( (car) -> names.add(car.getName()) );
</code>```

Body:
is there a smart way to set a property of all objects of an Iterable to a specified value?

I have a class SystemUser that looks like that:

class SystemUser{
  private String name;
  private String password;
  ...
}

and another class that generates an Iterable object like:

public Iterable<SystemUser> getUsers(){
   ...
   return users;
}

Can I set the attribute "password" of all objects of the Iterable to null without iterating?

Thanks!

Body:
Any way to apply any function to item You need to iterate over all element and change the value.There is lot of 3rd party library available for this purpose like
GUAVA OR as suggested above foreach.

Util using generic

public static <T> void apply(Iterable<T> iterable, Function<T, Void> function) {
    for (T input : iterable)
        function.apply(input);
}

using guava

final List<String> list = Arrays.asList("race", "box");
final List<String> transformed =
    Lists.newArrayList(Iterables.transform(list, new Function<String, String>() {

        @Override
        public String apply(final String input) {
            return new StringBuilder().append(input).append("car").toString();
        }
    }));

Using for-each

// Suppose that I have already init the list of car
List<Car> cars = //...
List<String> names = new ArrayList<String>();

// LAMBDA EXPRESSION
cars.forEach( (car) -> names.add(car.getName()) );


问:
Rails Production Logs in Google App Engine
I have recently deployed my Rails application to GAE. However it throws up an error, as a result of which i need to check the log files to find out what's happening. Normally i used to access the logs/production.log to see what went wrong. How can I access logs/production.log in this case?

I have checked the logs provided by Stackdriver logging, but they are mostly nginx and build logs, and i can't find the production.log file.

答:
Figured it out. You have to enable debug on your instances, and then ssh into your instances. Following which, you have to access the docker container running your app.

https://cloud.google.com/appengine/docs/flexible/ruby/debugging-an-instance


问:
Active Record Scope: Only include if all joined models match where statement
I have the following scope for customers:

```<code>scope :filter, -> {
    joins(:subscriptions)
    .where("subscriptions.end_date <= ?", 1.year.ago.to_date)
  }
</code>```

This scope works fine if customers have one subscriptions less than one year but if they have 2 subscriptions and one is greater than a year and one is less than a year, it still is included in this scope.

How do I write the scope to NOT include the customer if one of the subscriptions doesn't match the where statement?

答:
you could probably do a subquery where you count the number of subscriptions > 1.year.ago, and compare that count to 0
It would look something like this</p>

```<code>scope :filter, -> {
  joins(:subscriptions)
    .where("subscriptions.end_date <= ?", 1.year.ago.to_date)
    .where("(select count(subscriptions.id) from subscriptions where subscriptions.customer_id = id && subscriptions.end_date > ?) = 0", 1.year.ago.to_date)
}
</code>```

Body:
I have the following scope for customers:

scope :filter, -> {
    joins(:subscriptions)
    .where("subscriptions.end_date <= ?", 1.year.ago.to_date)
  }

This scope works fine if customers have one subscriptions less than one year but if they have 2 subscriptions and one is greater than a year and one is less than a year, it still is included in this scope.

How do I write the scope to NOT include the customer if one of the subscriptions doesn't match the where statement?

Body:
you could probably do a subquery where you count the number of subscriptions > 1.year.ago, and compare that count to 0
It would look something like this

scope :filter, -> {
  joins(:subscriptions)
    .where("subscriptions.end_date <= ?", 1.year.ago.to_date)
    .where("(select count(subscriptions.id) from subscriptions where subscriptions.customer_id = id && subscriptions.end_date > ?) = 0", 1.year.ago.to_date)
}


问:
Input from stream to enum type
How to input from stream to enum type?

I can do it so

```<code>unsigned int sex = 0;
stream >> sex;
student.m_bio.sex = static_cast<Sex>(sex);
</code>```

Otherwise?

答:
This is not pretty but should do it

```<code>stream >>  reinterpret_cast<std::underlying_type<Sex>::type &>(student.m_bio.sex);
</code>```

Cheers,
CC

Title: Input from stream to enum type

Body:
How to input from stream to enum type?

I can do it so

unsigned int sex = 0;
stream >> sex;
student.m_bio.sex = static_cast<Sex>(sex);

Otherwise?

Body:
This is not pretty but should do it

stream >>  reinterpret_cast<std::underlying_type<Sex>::type &>(student.m_bio.sex);

Cheers,
CC


问:
how to do tooltip on button in iphone?
I am having download icon on my page i want that when the user takes his finger over the button a tooltip should show as showing download in text.

is there any option in iphone to show a tooltip???

答:
Dan is absolutely right on how to do it but I'd answer you should rethink your design to not need the tooltip at all.

There's a reason that there isn't one by default - what if the user presses down on the button to see what it does, reads the tooltip and realises that's not what they want. They then have to be very careful not to let go while still over the button or it will press and do the wrong thing. (And most users don't know that they can press down over a button, move their finger off it and release it to cancel the press.)

You should rethink your design to make it obvious what the buttons do without the user having to interact with them first.

However, if you definitely still want a tooltip, Dan's method is fine.

Title: how to do tooltip on button in iphone?


问:
NoMethodError: undefined method `to_d' for nil:NilClass
```<code>NoMethodError: undefined method `to_d' for nil:NilClass
</code>```

this seems to be inconsistent with other "to_"

eg with Rails 3.2.14, and ruby 1.9.3p362:

```<code>1.9.3p362 :055 > nil.to_f
 => 0.0
1.9.3p362 :056 > nil.to_d
NoMethodError: undefined method `to_d' for nil:NilClass
1.9.3p362 :057 > nil.to_s
 => ""
1.9.3p362 :058 > nil.to_i
 => 0
</code>```

it means that when ever i might want to convert to big decimal that i first have to make sure the value is not nil and assign it a 0 value anyway... so... comments on what is the best way to make this consistent? and should i consider this a bug?

答:
you're probably better off converting to a string first if that's what you need</p>

```<code>BigDecimal.new(amount.to_s)
</code>```

Body:
NoMethodError: undefined method `to_d' for nil:NilClass

this seems to be inconsistent with other "to_"

eg with Rails 3.2.14, and ruby 1.9.3p362:

1.9.3p362 :055 > nil.to_f
 => 0.0
1.9.3p362 :056 > nil.to_d
NoMethodError: undefined method `to_d' for nil:NilClass
1.9.3p362 :057 > nil.to_s
 => ""
1.9.3p362 :058 > nil.to_i
 => 0

it means that when ever i might want to convert to big decimal that i first have to make sure the value is not nil and assign it a 0 value anyway... so... comments on what is the best way to make this consistent? and should i consider this a bug?

Body:
you're probably better off converting to a string first if that's what you need

BigDecimal.new(amount.to_s)


问:
AngularJS watching property of factory objects - unexpected behavior
I would like to understand a certain behavior of AngularJS when it comes to watching changes of objects provided by a factory.

There is a different behavior depending on whether I read a property of a factory-provided object in the controller or in the html.

Compare the following 2 ways of displaying the property in the view:

```<code>app.controller("testController", function($scope, testFactory){
    $scope.test_obj = testFactory.read();
    $scope.test_prop = testFactory.read().prop;
});

<div>{{test_obj.prop}}</div>
<div>{{test_prop}}</div>
</code>```

When the property changes in the testFactory, the change is updated in the view only in the first case, when the whole object is declared to scope and the property is called in the view. When the property is directly declared to the scope, it doesn't update automatically in the view.

This behavior can be observed in the following jsfiddle: https://jsfiddle.net/fb86p4fm/

What's the reason for this behavior?

答:
$scope.test_prop = testFactory.read().prop;

In the above line, the initial value of prop is 0. In javascript, numbers are copied by value, but objects/arrays are by reference. $scope.test_obj is referencing the service object, while $scope.test_prop is not.

Body:
I would like to understand a certain behavior of AngularJS when it comes to watching changes of objects provided by a factory.

There is a different behavior depending on whether I read a property of a factory-provided object in the controller or in the html.

Compare the following 2 ways of displaying the property in the view:

app.controller("testController", function($scope, testFactory){
    $scope.test_obj = testFactory.read();
    $scope.test_prop = testFactory.read().prop;
});

{{test_obj.prop}}

{{test_prop}}

When the property changes in the testFactory, the change is updated in the view only in the first case, when the whole object is declared to scope and the property is called in the view. When the property is directly declared to the scope, it doesn't update automatically in the view.

This behavior can be observed in the following jsfiddle: https://jsfiddle.net/fb86p4fm/

What's the reason for this behavior?


问:
Rounded cornes (border radius) Safari issue

.activity_rounded {
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    -khtml-border-radius: 50%;
    border: 3px solid #fff;
    behavior: url(css/PIE.htc);
}
```
<pre class="lang-html prettyprint-override"><code><img src="img/demo/avatar_3.jpg" class="activity_rounded" alt="" />
</code>```

This is my CSS & HTML. I want to make an image look like a circle. Everything works fine in IE8+, Google Chrome, and Mozilla Firefox. But Safari is acting kinda strange. Here is a demo picture:

答:
But if you have a border with radius on a div and inside it you have dynamic content (like if you click on that div, it slides down and show some other content), and you want to redesign your border with the same radius, you can use an aux class that redraw the radius (but the hack is that if you don't change the colour of the border the webkit will not redraw it).

Eg:

$(document).on('click', '.parent', function(e){ $('.content').toggleClass('opened').slideToggle(300);
 $(this).toggleClass('refreshBorders');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent{
cursor:pointer;
text-align:center;
-webkit-border:2px solid black;
-moz-border:2px solid black;
border:2px solid black;
-webkit-border-radius:50px;
-moz-border-radius:50px;
border-radius:50px;
-webkit-background-clip:padding-box;
transition: all 0.15s ease-in-out;
}

.content{
text-align:center;
display:none;
}
.opened{
display:inline-block;
}
.refreshBorders{
-webkit-border:2px solid red;
-moz-border:2px solid red;
border:2px solid red;
-webkit-border-radius:50px;
-moz-border-radius:50px;
border-radius:50px;
-webkit-background-clip:padding-box;
}</code>```

 title

 content content content

```

ContentLicense: CC BY-SA 4.0

Body:
.activity_rounded {
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    -khtml-border-radius: 50%;
    border: 3px solid #fff;
    behavior: url(css/PIE.htc);
}

This is my CSS & HTML. I want to make an image look like a circle. Everything works fine in IE8+, Google Chrome, and Mozilla Firefox. But Safari is acting kinda strange. Here is a demo picture:

Body:
But if you have a border with radius on a div and inside it you have dynamic content (like if you click on that div, it slides down and show some other content), and you want to redesign your border with the same radius, you can use an aux class that redraw the radius (but the hack is that if you don't change the colour of the border the webkit will not redraw it).

Eg:

$(document).on('click', '.parent', function(e){ $('.content').toggleClass('opened').slideToggle(300);
 $(this).toggleClass('refreshBorders');
});

.parent{
cursor:pointer;
text-align:center;
-webkit-border:2px solid black;
-moz-border:2px solid black;
border:2px solid black;
-webkit-border-radius:50px;
-moz-border-radius:50px;
border-radius:50px;
-webkit-background-clip:padding-box;
transition: all 0.15s ease-in-out;
}

.content{
text-align:center;
display:none;
}
.opened{
display:inline-block;
}
.refreshBorders{
-webkit-border:2px solid red;
-moz-border:2px solid red;
border:2px solid red;
-webkit-border-radius:50px;
-moz-border-radius:50px;
border-radius:50px;
-webkit-background-clip:padding-box;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">

 <div class="first">
  <h1> title </h1>
 </div>
 <div class="content">
  <p> content content content</p>
 </div>

</div>


问:
Upgrade from VS Setup MSI to Wix MSI being treated as uninstall
Scenario:

We have used VS 2010 Setup project till now. Migrating new builds to Wix going forward.

Issue:

Msiexec is treating the upgrade as un-install + fresh-install instead of just upgrade.

Details:

I have used the same UpgradeCode Guid for the new WIX setup

I've added MajorUpgrade tag as required

I've also tried using Upgrade and UpgradeVersion instead of MajorUpgrade

Version number is updated

I've restructured WXS to see if it's the issue and it's not

Note - System correctly recognizes both as same product and during setup automatically removes the old one.

Problem is, the old product is being run as uninstall rather than as a upgrade.
I have a custom action set to run during uninstall, which will remove user-data. Now the issue is, this custom action is being triggered during upgrade for some reason.

This problem doesn't happen if it's 2010 to 2010 or Wix to Wix, Only if it's 2010 to Wix.

Scenarios

1.0(built using 2010) -> 1.1(built using 2010) - No custom action triggered

1.0(built using 2010) -> 1.1(built using Wix) - Uninstall custom action

1.1(built using Wix) -> 1.2(built using Wix) - No custom action triggered

The only difference I've noticed in the logs -

For VS 2010 to 2010

```<code>Action ended: MsiUnpublishAssemblies. Return value 1.
MSI (s) (90:A4) : Skipping action: _[guid].uninstall.SetProperty (condition is false)
MSI (s) (90:A4): Skipping action: _[guid].uninstall (condition is false)
MSI (s) (90:A4) [21:54:10:299]: Doing action: UnpublishComponents
Action start 21:54:10: UnpublishComponents.
</code>```

For 2010 to WIX -

```<code>MsiUnpublishAssemblies. Return value 1.
Doing action: [guid].uninstall.SetProperty
Action start : [guid].uninstall.SetProperty.
MSI (s) (90:D4) :
Note:
1: 2235
2:
3: ExtendedType
4: SELECT `Action`,`Type`,`Source`,`Target`, NULL, `ExtendedType` FROM `CustomAction` WHERE `Action` = '[guid].uninstall.SetProperty'
MSI (s) (90:D4) : PROPERTY CHANGE: Adding [guid].uninstall property. Its value is '/installtype=notransaction /action=uninstall /LogFile= ... "[custom-action].exe" "oldmsi.tmp"'.
Action ended _[guid].SetProperty. Return value 1.
MSI (s) (90:D4) : Doing action: _[guid].uninstall
Action start : _[guid].uninstall.
MSI (s) (90:D4):
Note:
1: 2235
2:
3: ExtendedType
4: SELECT `Action`,`Type`,`Source`,`Target`, NULL, `ExtendedType` FROM `CustomAction` WHERE `Action` = '_[guid].uninstall'
Action ended: _[guid].uninstall. Return value 1.
MSI (s) (90:D4): Doing action: UnpublishComponents
Action start : UnpublishComponents.
</code>```

I'm clueless why this uninstall is happening. Any help is appreciated.

答:
There's not enough information to be sure, but this should help:

A major upgrade always uninstalls the product being upgraded. That is the definition of a major upgrade based on new ProductCode, same UpgradeCode and incremented version and same installation context. This means that your issue depends on your assumptions about an "uninstall custom action"

Visual Studio "uninstall" custom actions are not really "uninstall" custom actions. They are called when the component (denoted by component id) is removed. When you go from VS 2010 built to VS 2010 built the component id remains the same (internally ref counted) and the component remains installed. The same happens with the WiX builds. When you go from VS 2010 built to WiX built the component ids have probably changed, therefore the component from the VS 2010 built MSI is removed, therefore the custom action is called.

In other words the issue is most likely that the component ids in your VS 2010 build (which you cannot see because VS 2010 doesn't even hint at their existence) are not the same as the component ids in your WiX build.

Body:
Scenario:

We have used VS 2010 Setup project till now. Migrating new builds to Wix going forward.

Issue:

Msiexec is treating the upgrade as un-install + fresh-install instead of just upgrade.

Details:

I have used the same UpgradeCode Guid for the new WIX setup

I've added MajorUpgrade tag as required

I've also tried using Upgrade and UpgradeVersion instead of MajorUpgrade

Version number is updated

I've restructured WXS to see if it's the issue and it's not

Note - System correctly recognizes both as same product and during setup automatically removes the old one.

Problem is, the old product is being run as uninstall rather than as a upgrade.
I have a custom action set to run during uninstall, which will remove user-data. Now the issue is, this custom action is being triggered during upgrade for some reason.

This problem doesn't happen if it's 2010 to 2010 or Wix to Wix, Only if it's 2010 to Wix.

Scenarios

1.0(built using 2010) -> 1.1(built using 2010) - No custom action triggered

1.0(built using 2010) -> 1.1(built using Wix) - Uninstall custom action

1.1(built using Wix) -> 1.2(built using Wix) - No custom action triggered

The only difference I've noticed in the logs -

For VS 2010 to 2010

Action ended: MsiUnpublishAssemblies. Return value 1.
MSI (s) (90:A4) : Skipping action: _[guid].uninstall.SetProperty (condition is false)
MSI (s) (90:A4): Skipping action: _[guid].uninstall (condition is false)
MSI (s) (90:A4) [21:54:10:299]: Doing action: UnpublishComponents
Action start 21:54:10: UnpublishComponents.

For 2010 to WIX -

MsiUnpublishAssemblies. Return value 1.
Doing action: [guid].uninstall.SetProperty
Action start : [guid].uninstall.SetProperty.
MSI (s) (90:D4) :
Note:
1: 2235
2:
3: ExtendedType
4: SELECT `Action`,`Type`,`Source`,`Target`, NULL, `ExtendedType` FROM `CustomAction` WHERE `Action` = '[guid].uninstall.SetProperty'
MSI (s) (90:D4) : PROPERTY CHANGE: Adding [guid].uninstall property. Its value is '/installtype=notransaction /action=uninstall /LogFile= ... "[custom-action].exe" "oldmsi.tmp"'.
Action ended _[guid].SetProperty. Return value 1.
MSI (s) (90:D4) : Doing action: _[guid].uninstall
Action start : _[guid].uninstall.
MSI (s) (90:D4):
Note:
1: 2235
2:
3: ExtendedType
4: SELECT `Action`,`Type`,`Source`,`Target`, NULL, `ExtendedType` FROM `CustomAction` WHERE `Action` = '_[guid].uninstall'
Action ended: _[guid].uninstall. Return value 1.
MSI (s) (90:D4): Doing action: UnpublishComponents
Action start : UnpublishComponents.

I'm clueless why this uninstall is happening. Any help is appreciated.


问:
cuda kernel for conway's game of life
I'm trying to calculate the number of transitions that would be made in a run of Conway's GOL for a pxq matrix for n iterations. For instance, given 1 iteration with the initial state being 1 blinker (as below). there would be 5 transitions (2 births, 1 survival, 2 deaths from underpopulation). I've already got this working, but I'd like to convert this logic to run using CUDA. Below is what I want to port to CUDA.

    code:

```<code>    static void gol() // call this iterations x's
    {
        int[] tempGrid = new int[rows * cols]; // grid holds init conditions
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                tempGrid[i * cols + j] = grid[i * cols + j];
            }
        }

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                int numNeighbors = neighbors(i, j); // finds # of neighbors

                if (grid[i * cols + j] == 1 && numNeighbors > 3)
                {
                    tempGrid[i * cols + j] = 0;
                    overcrowding++;
                }
                else if (grid[i * cols + j] == 1 && numNeighbors < 2)
                {
                    tempGrid[i * cols + j] = 0;
                    underpopulation++;
                }
                else if (grid[i * cols + j] == 1 && numNeighbors > 1)
                {
                    tempGrid[i * cols + j] = 1;
                    survival++;
                }
                else if (grid[i * cols + j] == 0 && numNeighbors == 3)
                {
                    tempGrid[i * cols + j] = 1;
                    birth++;
                }
            }
        }

        grid = tempGrid;
    }
</code>```

答:
Here's one way you could proceed:

Each thread makes the computation for 1 element of the grid

Each thread first loads up one element from the main grid into shared memory

Threads on the edge of the thread block need also to load up boundary elements

Each thread can then make their survival computation based on the contents of shared memory

Each thread then writes their result back to main memory

Title: cuda kernel for conway's game of life

Body:
I'm trying to calculate the number of transitions that would be made in a run of Conway's GOL for a pxq matrix for n iterations. For instance, given 1 iteration with the initial state being 1 blinker (as below). there would be 5 transitions (2 births, 1 survival, 2 deaths from underpopulation). I've already got this working, but I'd like to convert this logic to run using CUDA. Below is what I want to port to CUDA.

    code:

    static void gol() // call this iterations x's
    {
        int[] tempGrid = new int[rows * cols]; // grid holds init conditions
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                tempGrid[i * cols + j] = grid[i * cols + j];
            }
        }

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                int numNeighbors = neighbors(i, j); // finds # of neighbors

                if (grid[i * cols + j] == 1 && numNeighbors > 3)
                {
                    tempGrid[i * cols + j] = 0;
                    overcrowding++;
                }
                else if (grid[i * cols + j] == 1 && numNeighbors < 2)
                {
                    tempGrid[i * cols + j] = 0;
                    underpopulation++;
                }
                else if (grid[i * cols + j] == 1 && numNeighbors > 1)
                {
                    tempGrid[i * cols + j] = 1;
                    survival++;
                }
                else if (grid[i * cols + j] == 0 && numNeighbors == 3)
                {
                    tempGrid[i * cols + j] = 1;
                    birth++;
                }
            }
        }

        grid = tempGrid;
    }


问:
How to install Github for Windows offline?
As the question says how to install Github for Windows without an internet connection?
If it is not possible then is there some alternative client with the following features:

Support for proxy

Offline installer

I found smartgit which has an offline installer but it seems it doesn't have proxy support.

If there is no such client then what can be done to extend the functionality of github for windows or some other client? I mean is there a way to use some API to extend it? Any links for that would be helpful.

答:
For the current version (as of June 2017) of GitHub Desktop (windows), you can go to https://github-windows.s3.amazonaws.com/standalone/GitHubDesktop.exe for the standalone, offline installer.

For GitHub Desktop (beta), the team is also working to make it an offline installer hopefully by version 1.0. Currently the installer has some issues that prevent it from installing successfully.


问:
Extract text from within a cell and paste text in corresponding column using vba
I have a spreadsheet that has data organized like so:

The user will insert multiple or as many text files as they want therefore each time the user imports a new text file the data gets placed beneath the previous import so the filepath, depth, A0, A180, etc are all present each time a text file is imported.
I want to be able to get the corresponding date and time (2003-11-03 17-52-04) for each file under the column 'Reading Date'. However I'm not sure how to go about this.

Any tips/help would be greatly appreciated!

Here is my code to import the data:

```<code>Sub Import_Textfiles()
Dim fName As String, LastRow As Long

LastRow = Range("A" & Rows.Count).End(xlUp).Row + 2

fName = Application.GetOpenFilename("Text Files (*.txt), *.txt")

If fName = "False" Then Exit Sub

    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _
        Destination:=Range("A" & LastRow))
        .Name = "2001-02-27 14-48-00"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlFixedWidth
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
        .TextFileFixedColumnWidths = Array(14, 14, 8, 16, 12, 14)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Range("W16").Select
    ActiveWindow.SmallScroll Down:=0

    Dim strShortName As String
    Dim strInitialDir As String

    'Adding Updating Location to Excel Sheet:

    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
    Dim currentRowValue As String

    sourceCol = 1   'column A has a value of 1
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    strShortName = fName

    'for every row, find the first blank cell and select it
    For currentRow = 1 To rowCount
        currentRowValue = Cells(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
            Cells(currentRow, sourceCol) = ("Updating Location: " & strShortName)
        End If
    Next

End Sub
</code>```

答:
I got it to do what I need it to do with the following code:

Sub Import_Textfiles()
Dim fName As String, LastRow As Long

LastRow = Range("A" & Rows.Count).End(xlUp).Row + 2

fName = Application.GetOpenFilename("Text Files (*.txt), *.txt")

If fName = "False" Then Exit Sub

```<code>With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _
    Destination:=Range("A" & LastRow))
    .Name = "2001-02-27 14-48-00"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlFixedWidth
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
    .TextFileFixedColumnWidths = Array(14, 14, 8, 16, 12, 14)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False

End With
Range("W16").Select
ActiveWindow.SmallScroll Down:=0

Dim strShortName As String
Dim strInitialDir As String

'Adding Updating Location to Excel Sheet:

Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
Dim fileDate1 As String
Dim fileDate2 As String

sourceCol = 1   'column A has a value of 1
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

strShortName = fName
fileDate1 = Mid(fName, InStrRev(fName, "\") + 1)
fileDate2 = Left(fileDate1, 19)

'for every row, find the first blank cell and select it
For currentRow = 1 To rowCount
    currentRowValue = Cells(currentRow, sourceCol).Value
    If IsEmpty(currentRowValue) Or currentRowValue = "" Then
        Cells(currentRow, sourceCol).Select
        Cells(currentRow, sourceCol) = ("Updating Location: " & strShortName)
        Cells((currentRow + 1), (sourceCol + 7)).Select
        Cells((currentRow + 1), (sourceCol + 7)) = "Reading Date"
        Cells((currentRow + 1), (sourceCol + 7)).Select
        Cells((currentRow + 2), (sourceCol + 7)) = fileDate2

    End If
Next
</code>```

End Sub

Thanks for the other suggestions!!

Body:
I have a spreadsheet that has data organized like so:

The user will insert multiple or as many text files as they want therefore each time the user imports a new text file the data gets placed beneath the previous import so the filepath, depth, A0, A180, etc are all present each time a text file is imported.
I want to be able to get the corresponding date and time (2003-11-03 17-52-04) for each file under the column 'Reading Date'. However I'm not sure how to go about this.

Any tips/help would be greatly appreciated!

Here is my code to import the data:

Sub Import_Textfiles()
Dim fName As String, LastRow As Long

LastRow = Range("A" & Rows.Count).End(xlUp).Row + 2

fName = Application.GetOpenFilename("Text Files (*.txt), *.txt")

If fName = "False" Then Exit Sub

    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _
        Destination:=Range("A" & LastRow))
        .Name = "2001-02-27 14-48-00"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlFixedWidth
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
        .TextFileFixedColumnWidths = Array(14, 14, 8, 16, 12, 14)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Range("W16").Select
    ActiveWindow.SmallScroll Down:=0

    Dim strShortName As String
    Dim strInitialDir As String

    'Adding Updating Location to Excel Sheet:

    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
    Dim currentRowValue As String

    sourceCol = 1   'column A has a value of 1
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    strShortName = fName

    'for every row, find the first blank cell and select it
    For currentRow = 1 To rowCount
        currentRowValue = Cells(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
            Cells(currentRow, sourceCol) = ("Updating Location: " & strShortName)
        End If
    Next

End Sub

Body:
I got it to do what I need it to do with the following code:

Sub Import_Textfiles()
Dim fName As String, LastRow As Long

LastRow = Range("A" & Rows.Count).End(xlUp).Row + 2

fName = Application.GetOpenFilename("Text Files (*.txt), *.txt")

If fName = "False" Then Exit Sub

With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _
    Destination:=Range("A" & LastRow))
    .Name = "2001-02-27 14-48-00"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlFixedWidth
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
    .TextFileFixedColumnWidths = Array(14, 14, 8, 16, 12, 14)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False

End With
Range("W16").Select
ActiveWindow.SmallScroll Down:=0

Dim strShortName As String
Dim strInitialDir As String

'Adding Updating Location to Excel Sheet:

Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
Dim fileDate1 As String
Dim fileDate2 As String

sourceCol = 1   'column A has a value of 1
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

strShortName = fName
fileDate1 = Mid(fName, InStrRev(fName, "\") + 1)
fileDate2 = Left(fileDate1, 19)

'for every row, find the first blank cell and select it
For currentRow = 1 To rowCount
    currentRowValue = Cells(currentRow, sourceCol).Value
    If IsEmpty(currentRowValue) Or currentRowValue = "" Then
        Cells(currentRow, sourceCol).Select
        Cells(currentRow, sourceCol) = ("Updating Location: " & strShortName)
        Cells((currentRow + 1), (sourceCol + 7)).Select
        Cells((currentRow + 1), (sourceCol + 7)) = "Reading Date"
        Cells((currentRow + 1), (sourceCol + 7)).Select
        Cells((currentRow + 2), (sourceCol + 7)) = fileDate2

    End If
Next

End Sub

Thanks for the other suggestions!!


问:
How can I use a single partial to render each object in a collection?
I have a working partial for an instance of my Quote class, _quote.html.erb, I would like to use this same partial to render each object within the collection provided by the index action. However, I am getting stuck and can no longer see where I am going wrong. An instance variable naming issue, a controller crud action format issue? Code below:

quotes_controller.rb

```<code>class QuotesController < ApplicationController
  before_action :authenticate_user!, only: [ :new, :create, :edit, :update, :destroy ]
  # before_action :owners_only, only: [ :show, :edit, :index, :update, :destroy ]

  def new
    @quote = Quote.new
  end

  def create
    # @quote = Quote.new(quote_params)
    @quote = current_user.quotes.new(quote_params)
    if @quote.save
        redirect_to quote_url(@quote), notice: 'Quote request created'
    else
      render :new
    end
  end

  def show
    # @quote = Quote.find(params[:id])
    @quote = current_user.quotes.find(params[:id])
  end

  def index
    @quotes = current_user.quotes.all
  end

  def edit
    @quote = current_user.quotes.find(params[:id])
  end

  def update
    @quote = current_user.quotes.find(params[:id])
    if @quote.update_attributes(quote_params)
      redirect_to quote_path(@quote)
    else
      render :edit
    end
  end

  def destroy
    @quote = current_user.quotes.find(params[:id])
    @quote.destroy
    redirect_to quotes_path
  end

private

  def quote_params
    params.require(:quote).permit(:gla, :prev_cover, :co_name, :co_number, :postcode, :industry, :lives_overseas,
                                  :scheme_start_date, :payment_frequency, :commission_level)
  end
end
</code>```

_quote.html.erb

```<code><section id="quote">
<div class="container">
<div class="row">
    <div class="col-md-4 text-center">
    <div class="panel panel-success panel-quote">
      <div class="panel-heading">
        <strong>GLA</strong>
        </div>
      <div class="panel-body text-center">
         <p><strong>Quote ID; <%= @quote.id %></strong></p>
      </div>

      <table class="table table-bordered">
        <tr>
          <td>Company name</td>
          <td><%= @quote.co_name %></td>
        </tr>
        <tr>
          <td>Company number</td>
          <td><%= @quote.co_number %></td>
        </tr>
        <tr>
          <td>Office postcode</td>
          <td><%= @quote.postcode %></td>
        </tr>
        <tr>
          <td>Industry</td>
          <td><%= @quote.industry %></td>
        </tr>
        <tr>
          <td>Previous cover</td>
          <td><%= @quote.prev_cover %></td>
        </tr>
        <tr>
          <td>Lives overseas</td>
          <td><%= @quote.lives_overseas %></td>
        </tr>
        <tr>
          <td>Scheme start date</td>
          <td><%= @quote.scheme_start_date %></td>
        </tr>
        <tr>
          <td>Payment frequency</td>
          <td><%= @quote.payment_frequency %></td>
        </tr>
        <tr>
          <td>Commission level</td>
          <td><%= @quote.commission_level %></td>
        </tr>
      </table>
    </div>
  </div>
</div>
</code>```

index.html.erb

```<code><% @quotes.each do |q| %>
  <%= render :partial => "quote", :collection => q %>
<% end %>
</code>```

Am i doing something blindingly obvious here that someone can point out for me, been staring so long I can't see it any more!

If I run:

```<code><% @quotes.each do |q| %>
  <%= q.co_name %>
<% end %>
</code>```

The index page renders the co_name values just fine, showing that the collection does get through.

答:
I think this:

```<code><% @quotes.each do |q| %>
  <%= render :partial => "quote", :collection => q %>
<% end %>
</code>```

Might be something more like this:

```<code><% @quotes.each do |quote| %>
  <%= render :partial => "quote", locals: {quote: quote} %>
<% end %>
</code>```

And then in your partial, at the top, do something like:

```<code><% @quote = local_assigns[:quote] %>
<section id="quote">
<div class="container">
<div class="row">
    <div class="col-md-4 text-center">
    <div class="panel panel-success panel-quote">
      <div class="panel-heading">
        <strong>GLA</strong>
        </div>
      <div class="panel-body text-center">
         <p><strong>Quote ID; <%= @quote.id %></strong></p>
      </div>

      <table class="table table-bordered">
        <tr>
          <td>Company name</td>
          <td><%= @quote.co_name %></td>
        </tr>
        ...
      </table>
    </div>
  </div>
</div>
</code>```

Then I think you'll be on your way.

Body:
I have a working partial for an instance of my Quote class, _quote.html.erb, I would like to use this same partial to render each object within the collection provided by the index action. However, I am getting stuck and can no longer see where I am going wrong. An instance variable naming issue, a controller crud action format issue? Code below:

quotes_controller.rb

class QuotesController < ApplicationController
  before_action :authenticate_user!, only: [ :new, :create, :edit, :update, :destroy ]
  # before_action :owners_only, only: [ :show, :edit, :index, :update, :destroy ]

  def new
    @quote = Quote.new
  end

  def create
    # @quote = Quote.new(quote_params)
    @quote = current_user.quotes.new(quote_params)
    if @quote.save
        redirect_to quote_url(@quote), notice: 'Quote request created'
    else
      render :new
    end
  end

  def show
    # @quote = Quote.find(params[:id])
    @quote = current_user.quotes.find(params[:id])
  end

  def index
    @quotes = current_user.quotes.all
  end

  def edit
    @quote = current_user.quotes.find(params[:id])
  end

  def update
    @quote = current_user.quotes.find(params[:id])
    if @quote.update_attributes(quote_params)
      redirect_to quote_path(@quote)
    else
      render :edit
    end
  end

  def destroy
    @quote = current_user.quotes.find(params[:id])
    @quote.destroy
    redirect_to quotes_path
  end

private

  def quote_params
    params.require(:quote).permit(:gla, :prev_cover, :co_name, :co_number, :postcode, :industry, :lives_overseas,
                                  :scheme_start_date, :payment_frequency, :commission_level)
  end
end

_quote.html.erb

        GLA

Quote ID; <%= @quote.id %>

          Company name
          <%= @quote.co_name %>

          Company number
          <%= @quote.co_number %>

          Office postcode
          <%= @quote.postcode %>

          Industry
          <%= @quote.industry %>

          Previous cover
          <%= @quote.prev_cover %>

          Lives overseas
          <%= @quote.lives_overseas %>

          Scheme start date
          <%= @quote.scheme_start_date %>

          Payment frequency
          <%= @quote.payment_frequency %>

          Commission level
          <%= @quote.commission_level %>

index.html.erb

<% @quotes.each do |q| %>
  <%= render :partial => "quote", :collection => q %>
<% end %>

Am i doing something blindingly obvious here that someone can point out for me, been staring so long I can't see it any more!

If I run:

<% @quotes.each do |q| %>
  <%= q.co_name %>
<% end %>

The index page renders the co_name values just fine, showing that the collection does get through.

Body:
I think this:

<% @quotes.each do |q| %>
  <%= render :partial => "quote", :collection => q %>
<% end %>

Might be something more like this:

<% @quotes.each do |quote| %>
  <%= render :partial => "quote", locals: {quote: quote} %>
<% end %>

And then in your partial, at the top, do something like:

<% @quote = local_assigns[:quote] %>
<section id="quote">
<div class="container">
<div class="row">
    <div class="col-md-4 text-center">
    <div class="panel panel-success panel-quote">
      <div class="panel-heading">
        <strong>GLA</strong>
        </div>
      <div class="panel-body text-center">
         <p><strong>Quote ID; <%= @quote.id %></strong></p>
      </div>

      <table class="table table-bordered">
        <tr>
          <td>Company name</td>
          <td><%= @quote.co_name %></td>
        </tr>
        ...
      </table>
    </div>
  </div>
</div>

Then I think you'll be on your way.


问:
Different coloured fly out menu
I'm creating a custom master page for a MOSS publishing site. The designers have come up with this idea for the fly out menu...

alt text http://www.abbeylegal.com/Downloads/2009-01-06/gradient%20menu.jpg

which uses graduated/different backgrond and text colours for each menu option.

Does anyone know how to accomplish this?

答:
You can use the CSS next-sibling selector (+) to achieve this however IE6 won't get the styles.

Do something like the following (colour properties are just for example):

```<code>ul ul li { background: darkblue; color: lightblue; }
ul ul li+li { background: blue; color: lightblue; }
ul ul li+li+li { background: lightblue; color: darkblue; }
ul ul li a:hover { color: black; }
</code>```

Alternatively, you'll have to either apply a CSS class to each subitem going down (talk to the programmer if you're not responsible for that), or do it by adding classes with javascript.

Ideally try to convince them that you can't do it for IE6 but modern browsers will manage fine. As long as the site is still usable the gradient of colours is a very minor loss.

OwnerDisplayName: Rob

Title: Different coloured fly out menu

Body:
You can use the CSS next-sibling selector (+) to achieve this however IE6 won't get the styles.

Do something like the following (colour properties are just for example):

ul ul li { background: darkblue; color: lightblue; }
ul ul li+li { background: blue; color: lightblue; }
ul ul li+li+li { background: lightblue; color: darkblue; }
ul ul li a:hover { color: black; }

Alternatively, you'll have to either apply a CSS class to each subitem going down (talk to the programmer if you're not responsible for that), or do it by adding classes with javascript.

Ideally try to convince them that you can't do it for IE6 but modern browsers will manage fine. As long as the site is still usable the gradient of colours is a very minor loss.

OwnerDisplayName: sanchothefat


问:
Does my application "contain encryption"?
I'm uploading a binary for the first time. iTunes Connect has asked me:

Export laws require that products containing encryption be properly authorized for export.

  Failure to comply could result in severe penalties.

  For further information, click here.

  Does your product contain encryption?

I use https://, but only via NSURLConnection and UIWebView.

My reading of this is that my app doesn't "contain encryption," but I'm wondering if this is spelled out anywhere. "Severe penalties" doesn't sound pleasant at all, so "I think that's right" is a bit sketchy... an authoritative answer would be better.

Thanks.

答:
Yes, according to iTunes Connect Export Compliance Information screens, if you use built-in iOS or MacOS encryption (keychain, https), you are using encryption for purposes of US Government Export regulations. Whether you qualify for an export compliance exemption depends on what your app does and how it uses this encryption. Attached images show the iTunes Connect Export Compliance Screens to help you determine your export reporting obligations. In particular, it states:

If you are making use of ATS or making a call to HTTPS please note that you are required to submit a year-end self classification report to the US government. Learn more


问:
Imacros extraction
I just started using Imacros,so far so good.  I'm attempting to scrap large amounts of information from tables and then delimit it in excel.  However when I try and do so i'm told the info is all ready delimited.  Any ideas how I can brake this information up or how it's being imported into excel?  The extracted info appears in one cell as a long string with long spaces in between?  I bow down to anyone who can solve this problem!</p>

```<code>VERSION BUILD=7300701 RECORDER=FX
TAB T=1
SET !DATASOURCE 130.csv
SET !DATASOURCE_COLUMNS 1
SET !DATASOURCE_LINE {{!LOOP}}
SET !EXTRACT_TEST_POPUP NO
URL GOTO=http://www.autohausaz.com/index.html
SET !ERRORIGNORE YES
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:searchkeyword ATTR=ID:topsearchbox CONTENT={{!COL1}}
TAG POS=1 TYPE=INPUT:IMAGE FORM=NAME:searchkeyword ATTR=NAME:searchbutton&&SRC:http://www.autohausaz.com/assets/images/topsearchbutton.gif
TAG POS=1 TYPE=TABLE ATTR=ID:dlGroups
TAG POS=3 TYPE=TD ATTR=TXT:* EXTRACT=TXT
SAVEAS TYPE=EXTRACT FOLDER=* FILE=brake.csv
</code>```

答:
You can use EVAL to delimit the data if it is in constant format.

I see the tabular format of data, I think you want to scrape all of the data, I will suggest you make a javascript for this.

You can use the relative tag to get data of adjacent column into your CSV.

```<code>TAG POS=R1 TYPE=SPAN ATTR=* EXTRACT=TXT
</code>```

Title: Imacros extraction

Body:
I just started using Imacros,so far so good.  I'm attempting to scrap large amounts of information from tables and then delimit it in excel.  However when I try and do so i'm told the info is all ready delimited.  Any ideas how I can brake this information up or how it's being imported into excel?  The extracted info appears in one cell as a long string with long spaces in between?  I bow down to anyone who can solve this problem!

VERSION BUILD=7300701 RECORDER=FX
TAB T=1
SET !DATASOURCE 130.csv
SET !DATASOURCE_COLUMNS 1
SET !DATASOURCE_LINE {{!LOOP}}
SET !EXTRACT_TEST_POPUP NO
URL GOTO=http://www.autohausaz.com/index.html
SET !ERRORIGNORE YES
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:searchkeyword ATTR=ID:topsearchbox CONTENT={{!COL1}}
TAG POS=1 TYPE=INPUT:IMAGE FORM=NAME:searchkeyword ATTR=NAME:searchbutton&&SRC:http://www.autohausaz.com/assets/images/topsearchbutton.gif
TAG POS=1 TYPE=TABLE ATTR=ID:dlGroups
TAG POS=3 TYPE=TD ATTR=TXT:* EXTRACT=TXT
SAVEAS TYPE=EXTRACT FOLDER=* FILE=brake.csv

Body:
You can use EVAL to delimit the data if it is in constant format.

I see the tabular format of data, I think you want to scrape all of the data, I will suggest you make a javascript for this.

You can use the relative tag to get data of adjacent column into your CSV.

TAG POS=R1 TYPE=SPAN ATTR=* EXTRACT=TXT


问:
Increasing Linux DMA_ZONE memory on ARM i.MX287
I am working in an Embedded Linux system which has the 2.6.35.3 kernel.

Within the device we require a 4MB+192kB contiguous DMA capable buffer for one of our data capture drivers. The driver uses SPI transfers to copy data into this buffer.

The user space application issues a mmap system call to map the buffer into user space and after that, it directly reads the available data.

The buffer is allocated using "alloc_bootmem_low_pages" call, because it is not possible to allocate more than 4 MB buffer using other methods, such as kmalloc.

However, due to a recent upgrade, we need to increase the buffer space to 22MB+192kB. As I've read, the Linux kernel has only 16MB of DMA capable memory. Therefore, theoretically this is not possible unless there is a way to tweak this setting.

If there is anyone who knows how to perform this, please let me know?

Is this a good idea or will this make the system unstable?

答:
The ZONE_DMA 16MB limit is imposed by a hardware limitation of certain devices.  Specifically, on the PC architecture in the olden days, ISA cards performing DMA needed buffers allocated in the first 16MB of the physical address space because the ISA interface had 24 physical address lines which were only capable of addressing the first 2^24=16MB of physical memory.  Therefore, device drivers for these cards would allocate DMA buffers in the ZONE_DMA area to accommodate this hardware limitation.

Depending on your embedded system and device hardware, your device either is or isn't subject to this limitation.  If it is subject to this limitation, there is no software fix you can apply to allow your device to address a 22MB block of memory, and if you modify the kernel to extend the DMA address space beyond 16MB, then of course the system will become unstable.

On the other hand, if your device is not subject to this limitation (which is the only way it could possibly write to a 22MB buffer), then there is no reason to allocate memory in ZONE_DMA.  In this case, I think if you simply replace your alloc_bootmem_low_pages call with an alloc_bootmem_pages call, it should work fine to allocate your 22MB buffer.  If the system becomes unstable, then it's probably because your device is subject to a hardware limitation, and you cannot use a 22MB buffer.


问:
Flexbox align-self being ignored
The documentation for align-self states:

The align-self CSS property aligns flex items of the current flex line overriding the align-items value.

However, this does not happen:

.example {
  display: flex;
  align-items: center;
  border: 1px solid blue;
  height: 8ex;
}

.example > div {
  border: 1px solid red;
}

#a > div:last-child {
  align-self: top;
}

#b > div:last-child {
  align-self: center;
}

#c > div:last-child {
  align-self: bottom;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div id="a" class="example"><div>1</div><div>2</div></div>
<div id="b" class="example"><div>1</div><div>2</div></div>
<div id="c" class="example"><div>1</div><div>2</div></div>
</body></code>```

The docs also say:

If any of the item's cross-axis margin is set to auto, then align-self is ignored. The property doesn't apply to block-level boxes, or to table cells.

However, none of these things work:

Explicitly adding margin:0 to the child divs.

Adding display:inline to the child divs.

Changing the divs to spans.

Why is align-self not working?

答:
top and bottom are not valid values for align-self. Use flex-start and flex-end instead:

.example {
  display: flex;
  align-items: center;
  border: 1px solid blue;
  height: 8ex;
}

.example > div {
  border: 1px solid red;
}

#a > div:last-child {
  align-self: flex-start;
}

#b > div:last-child {
  align-self: center;
}

#c > div:last-child {
  align-self: flex-end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div id="a" class="example"><div>1</div><div>2</div></div>
<div id="b" class="example"><div>1</div><div>2</div></div>
<div id="c" class="example"><div>1</div><div>2</div></div>
</body></code>```

Title: Flexbox align-self being ignored

Body:
The documentation for align-self states:

The align-self CSS property aligns flex items of the current flex line overriding the align-items value.

However, this does not happen:

.example {
  display: flex;
  align-items: center;
  border: 1px solid blue;
  height: 8ex;
}

.example > div {
  border: 1px solid red;
}

#a > div:last-child {
  align-self: top;
}

#b > div:last-child {
  align-self: center;
}

#c > div:last-child {
  align-self: bottom;
}

1

2

1

2

1

2

The docs also say:

If any of the item's cross-axis margin is set to auto, then align-self is ignored. The property doesn't apply to block-level boxes, or to table cells.

However, none of these things work:

Explicitly adding margin:0 to the child divs.

Adding display:inline to the child divs.

Changing the divs to spans.

Why is align-self not working?

Body:
top and bottom are not valid values for align-self. Use flex-start and flex-end instead:

.example {
  display: flex;
  align-items: center;
  border: 1px solid blue;
  height: 8ex;
}

.example > div {
  border: 1px solid red;
}

#a > div:last-child {
  align-self: flex-start;
}

#b > div:last-child {
  align-self: center;
}

#c > div:last-child {
  align-self: flex-end;
}

<body>
<div id="a" class="example"><div>1</div><div>2</div></div>
<div id="b" class="example"><div>1</div><div>2</div></div>
<div id="c" class="example"><div>1</div><div>2</div></div>
</body>


问:
Simple Directory Lookup in Azure Active Directory
I am writing a simple desktop application that needs to retrieve some basic properties about a user from Microsoft’ directory. Specifically:

I am writing a single tenant native LOB application.

The application runs on my desktop.

The application runs as my logged on domain account.

The organization' domain accounts are synced to AAD.

I am not trying to secure a native web app or a Web API or anything like that. I do not need users to sign in.

I have email addresses of folks in my organization from an external event management tool. I need to lookup the AAD account profile data (address book info - specifically job title) from AAD based on the email address. I will only be reading AAD data.

So far, I have done the following:-

It appears that the Azure AD Graph API is the right way to fetch the profile information. In particular, the information is available at the endpoint: https://graph.windows.net/{tenant}/users/{email}?api-version=1.6

When registering the native application in AAD, no key was provided. So I don't have a client secret.

Looked at the sample in GitHub here: https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console. The instructions here seem to be wrong because no Keys section is available [see (2)].

Based on the sample above, I wrote a simple function. Code is below:

```<code>    private static async Task PrintAADUserData(string email)
    {
        string clientId = "0a202b2c-6220-438d-9501-036d4e05037f";
        Uri redirectUri = new Uri("http://localhost:4000");
        string resource = "https://graph.windows.net/{tenant}";
        string authority = "https://login.microsoftonline.com/{tenant}/oauth2/authorize";
        AuthenticationContext authContext = new AuthenticationContext(authority);

        AuthenticationResult authResult = await authContext.AcquireTokenAsync(resource, clientId, redirectUri, new PlatformParameters(PromptBehavior.Auto));

        string api = String.Format("https://graph.windows.net/{tenant}/users/{0}?api-version=1.6", email);
        LOG.DebugFormat("Using API URL {0}", api);

        // Create an HTTP client and add the token to the Authorization header
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authResult.AccessTokenType, authResult.AccessToken);
        HttpResponseMessage response = await httpClient.GetAsync(api);

        string data = await response.Content.ReadAsStringAsync();
        LOG.Debug(data);
    }
</code>```

Questions

The application when run was able to bring up the authentication page. Why do I need that? The application already runs as my domain account. Is an additional authentication necessary? If I were to run this application in Azure as a worker process, then I would not want to use my domain credentials.

The primary problem seems to be the resource URL which is wrong. What resource do I need to specify to access the Azure AD Graph API?

Thanks,

Vijai.

EDITS

Based on the comments from @Saca, the code and application has been edited.

Code

```<code>string clientId = ConfigurationManager.AppSettings["AADClientId"];
string clientSecret = ConfigurationManager.AppSettings["AADClientSecret"];
string appIdUri = ConfigurationManager.AppSettings["AADAppIdURI"];
string authEndpoint = ConfigurationManager.AppSettings["AADGraphAuthority"];
string graphEndpoint = ConfigurationManager.AppSettings["AADGraphEndpoint"];

AuthenticationContext authContext = new AuthenticationContext(authEndpoint, false);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.windows.net", new ClientCredential(clientId, clientSecret));
ExistingTokenWrapper wrapper = new ExistingTokenWrapper(authResult.AccessToken);
ActiveDirectoryClient client = new ActiveDirectoryClient(new Uri(graphEndpoint), async () => await wrapper.GetToken());

IUser user = client.Users.Where(_ => _.UserPrincipalName.Equals(email.ToLowerInvariant())).Take(1).ExecuteSingleAsync().Result;
</code>```

App

Error
Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> Microsoft.Data.OData.ODataErrorException: Insufficient privileges to complete the operation. ---> System.Data.Services.Client.DataServiceQueryException: An error occurred while processing this request. ---> System.Data.Services.Client.DataServiceClientException: {"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"Insufficient privileges to complete the operation."}}}

It appears that despite giving the right permissions, the correct resource and being able to acquire a token, there is still something missing.

答:
Hope help some one that are using GraphClient:

```<code>var userPriNam = "johndoe@cloudalloc.com";
var userLookupTask = activeDirectoryClient.Users.Where(
    user => user.UserPrincipalName.Equals(userPriNam, StringComparison.CurrentCultureIgnoreCase)).ExecuteSingleAsync();
User userJohnDoe = (User)await userLookupTask;
</code>```

from https://www.simple-talk.com/cloud/security-and-compliance/azure-active-directory-part-5-graph-api/

Body:
I am writing a simple desktop application that needs to retrieve some basic properties about a user from Microsoft’ directory. Specifically:

I am writing a single tenant native LOB application.

The application runs on my desktop.

The application runs as my logged on domain account.

The organization' domain accounts are synced to AAD.

I am not trying to secure a native web app or a Web API or anything like that. I do not need users to sign in.

I have email addresses of folks in my organization from an external event management tool. I need to lookup the AAD account profile data (address book info - specifically job title) from AAD based on the email address. I will only be reading AAD data.

So far, I have done the following:-

It appears that the Azure AD Graph API is the right way to fetch the profile information. In particular, the information is available at the endpoint: https://graph.windows.net/{tenant}/users/{email}?api-version=1.6

When registering the native application in AAD, no key was provided. So I don't have a client secret.

Looked at the sample in GitHub here: https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console. The instructions here seem to be wrong because no Keys section is available [see (2)].

Based on the sample above, I wrote a simple function. Code is below:

    private static async Task PrintAADUserData(string email)
    {
        string clientId = "0a202b2c-6220-438d-9501-036d4e05037f";
        Uri redirectUri = new Uri("http://localhost:4000");
        string resource = "https://graph.windows.net/{tenant}";
        string authority = "https://login.microsoftonline.com/{tenant}/oauth2/authorize";
        AuthenticationContext authContext = new AuthenticationContext(authority);

        AuthenticationResult authResult = await authContext.AcquireTokenAsync(resource, clientId, redirectUri, new PlatformParameters(PromptBehavior.Auto));

        string api = String.Format("https://graph.windows.net/{tenant}/users/{0}?api-version=1.6", email);
        LOG.DebugFormat("Using API URL {0}", api);

        // Create an HTTP client and add the token to the Authorization header
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authResult.AccessTokenType, authResult.AccessToken);
        HttpResponseMessage response = await httpClient.GetAsync(api);

        string data = await response.Content.ReadAsStringAsync();
        LOG.Debug(data);
    }

Questions

The application when run was able to bring up the authentication page. Why do I need that? The application already runs as my domain account. Is an additional authentication necessary? If I were to run this application in Azure as a worker process, then I would not want to use my domain credentials.

The primary problem seems to be the resource URL which is wrong. What resource do I need to specify to access the Azure AD Graph API?

Thanks,

Vijai.

EDITS

Based on the comments from @Saca, the code and application has been edited.

Code

string clientId = ConfigurationManager.AppSettings["AADClientId"];
string clientSecret = ConfigurationManager.AppSettings["AADClientSecret"];
string appIdUri = ConfigurationManager.AppSettings["AADAppIdURI"];
string authEndpoint = ConfigurationManager.AppSettings["AADGraphAuthority"];
string graphEndpoint = ConfigurationManager.AppSettings["AADGraphEndpoint"];

AuthenticationContext authContext = new AuthenticationContext(authEndpoint, false);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.windows.net", new ClientCredential(clientId, clientSecret));
ExistingTokenWrapper wrapper = new ExistingTokenWrapper(authResult.AccessToken);
ActiveDirectoryClient client = new ActiveDirectoryClient(new Uri(graphEndpoint), async () => await wrapper.GetToken());

IUser user = client.Users.Where(_ => _.UserPrincipalName.Equals(email.ToLowerInvariant())).Take(1).ExecuteSingleAsync().Result;

App

Error
Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> Microsoft.Data.OData.ODataErrorException: Insufficient privileges to complete the operation. ---> System.Data.Services.Client.DataServiceQueryException: An error occurred while processing this request. ---> System.Data.Services.Client.DataServiceClientException: {"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"Insufficient privileges to complete the operation."}}}

It appears that despite giving the right permissions, the correct resource and being able to acquire a token, there is still something missing.

Body:
Hope help some one that are using GraphClient:

var userPriNam = "johndoe@cloudalloc.com";
var userLookupTask = activeDirectoryClient.Users.Where(
    user => user.UserPrincipalName.Equals(userPriNam, StringComparison.CurrentCultureIgnoreCase)).ExecuteSingleAsync();
User userJohnDoe = (User)await userLookupTask;

from https://www.simple-talk.com/cloud/security-and-compliance/azure-active-directory-part-5-graph-api/


问:
How to use warpAffine function in OpenCV C++
I need to warp an image by using an affine transformation. The error I get is that the "code has crashed".

Can anyone tell me what is wrong with my code?

```<code>Mat imgAffine, image, par;
image = imread("/media/sf_vbox_share/ubuntushare/board.jpg",1);

par.at<double>(0,0)=  1.01121;  //p1
par.at<double>(1,0)=  0.21067;  //p2;
par.at<double>(0,1)= -89.69693; //p3;
par.at<double>(1,1)= - 0.11557; //p4;
par.at<double>(0,2)= 1.44982;   //p5;
par.at<double>(1,2)= -193.66149;//p6;

imgAffine = Mat::zeros(image.rows, image.cols, image.type());
warpAffine(image,imgAffine,par, image.size(),INTER_LINEAR);
namedWindow("image",WINDOW_AUTOSIZE);
imshow("image",imgAffine);
cvWaitKey(0);
</code>```

答:
par is undefined in size so when trying to write elements to it, it is most likely giving you segmentation faults.  Try allocating the memory for it first before setting its elements:

```<code>// Your code
Mat imgAffine, image, par;
image = imread ("/media/sf_vbox_share/ubuntushare/board.jpg",1);

// New code
par = Mat(2, 3, CV_64FC1); // Allocate memory

// Rest of your code
par.at<double>(0,0)=  1.01121;  //p1
par.at<double>(1,0)=  0.21067 ;  //p2;
par.at<double>(0,1)= -89.69693; //p3;
par.at<double>(1,1)= - 0.11557;  //p4;
par.at<double>(0,2)= 1.44982;   //p5;
par.at<double>(1,2)= -193.66149;//p6;
//
// ....
// ....
</code>```

Alternatively, you can use the constructor of cv::Mat when declaring par, so at the beginning of the code:

```<code>Mat imgAffine, image;
Mat par(2, 3, CV_64FC1);

// Rest of your code
image = imread ("/media/sf_vbox_share/ubuntushare/board.jpg",1);

//
// ....
// ....
</code>```

Body:
I need to warp an image by using an affine transformation. The error I get is that the "code has crashed".

Can anyone tell me what is wrong with my code?

Mat imgAffine, image, par;
image = imread("/media/sf_vbox_share/ubuntushare/board.jpg",1);

par.at<double>(0,0)=  1.01121;  //p1
par.at<double>(1,0)=  0.21067;  //p2;
par.at<double>(0,1)= -89.69693; //p3;
par.at<double>(1,1)= - 0.11557; //p4;
par.at<double>(0,2)= 1.44982;   //p5;
par.at<double>(1,2)= -193.66149;//p6;

imgAffine = Mat::zeros(image.rows, image.cols, image.type());
warpAffine(image,imgAffine,par, image.size(),INTER_LINEAR);
namedWindow("image",WINDOW_AUTOSIZE);
imshow("image",imgAffine);
cvWaitKey(0);

Body:
par is undefined in size so when trying to write elements to it, it is most likely giving you segmentation faults.  Try allocating the memory for it first before setting its elements:

// Your code
Mat imgAffine, image, par;
image = imread ("/media/sf_vbox_share/ubuntushare/board.jpg",1);

// New code
par = Mat(2, 3, CV_64FC1); // Allocate memory

// Rest of your code
par.at<double>(0,0)=  1.01121;  //p1
par.at<double>(1,0)=  0.21067 ;  //p2;
par.at<double>(0,1)= -89.69693; //p3;
par.at<double>(1,1)= - 0.11557;  //p4;
par.at<double>(0,2)= 1.44982;   //p5;
par.at<double>(1,2)= -193.66149;//p6;
//
// ....
// ....

Alternatively, you can use the constructor of cv::Mat when declaring par, so at the beginning of the code:

Mat imgAffine, image;
Mat par(2, 3, CV_64FC1);

// Rest of your code
image = imread ("/media/sf_vbox_share/ubuntushare/board.jpg",1);

//
// ....
// ....


问:
Xcode6: Run two instances of the simulator
I have two different targets for my iOS app. Is it possible to run simultaneously the two apps on two different instances of the simulator?
It's ok if it would require not to benefit of the Xcode's debugger.
So far the only solution I found was to install two versions of XCode, but that's a very heavy/space-consuming solution.</p>

答:
Xcode 9+

Xcode 9 now supports launching multiple simulators. This was announced in WWDC 2017.

Just go and change the simulator in Xcode, Cmd + R and you will see a new simulator popping up.