问:
Scroll to top not working after ajax
Sorry for the long explanation: I have not been a coder for some years now, and time to time I return to do some projects because of budget issues. I am currently running this site for educational purposes, that informs the community about the benefits of animal-humans interactions. We do much some entertainment posts, but most are written by veterinary doctors. Recently I add to organize the site posts into categories i.e dog cats vaccines, etc. Since the site is not very optimised and the server is kind of slow I made a lateral menu calling post via Ajax.
The problem I am facing is that despite my efforts of placing a:

window.scrollTo(0, 0);

$('html, body').animate({ scrollTop: 0 }, 'slow');

$('html, body').animate({ scrollTop: 0 }, 0);

A settimeout function to deal with the AJAX loading

Nothing works. I am probably being dense about this but it is taking me days to figure out what am not seeing. And is rendering the site not very functional.
The site is www.guiadocao.com the menu on the site when you click does not go up after loading the contents. I am not asking anyone to debug this but honestly i ran all the option available. So just appreciate if a fresh pair of eyes could shed new light into this.

Regards to all,

答:
Try adding a success callback scrollTop function to your AJAX request.</p>

```<code>var call = $.ajax({
    type: "POST",
    url: "/path/",
    success: $(window).scrollTop(0)
});
</code>```

Title: Scroll to top not working after ajax

Body:
Try adding a success callback scrollTop function to your AJAX request.

var call = $.ajax({
    type: "POST",
    url: "/path/",
    success: $(window).scrollTop(0)
});


来源: stackexchange

问:
Why it is not redirecting
```<code><?php

  if(isset($_POST['confirm'])){

    $name = $db->validation($_POST['name']);

    $id = "";
    for($i= strlen($name) ; $i>=1 ; $i--){
         if($name[$i-1] == 'a'){
               break;
            }else{
          $id = $id.$name[$i-1];
       }
    }
    $userid =  strrev($id);
    $query = "SELECT * FROM bluekolar_user WHERE token = '$name' AND user_id='$userid'";
    $result = $db->select($query);
    if($result){
        if(mysqli_num_rows($result) ==1 ){
            $qu = "UPDATE bluekolar_user SET active = '1' WHERE user_id='$userid'";
            $res = $db->update($qu);
            if($res){
                $url = "profile/index.php?id=".$userid ;
                header('location:'.$url) ;
                exit();
            }else{
                $error = "Provide correct confirmation code";
            }
        }else{
            $error = "Provide correct confirmation code";
        }
    }

  }

 ?>
</code>```

<p>The code is performing good but it is unable to redirect. I don't know why. I need help.
Please help me so that I can redirect my code command to another page.
Thank you. </p>

答: You need to ensure the path you are trying to redirect to is correct.  The code in your question will try to redirect to a "profile" subdirectory of the location where this script is running.  If you want to go to "http://example.com/profile/index.php?id=" you need to change your $url to be "/profile/index.php"</p>

ContentLicense: CC BY-SA 3.0

Title: Why it is not redirecting

Body:
<?php

  if(isset($_POST['confirm'])){

    $name = $db->validation($_POST['name']);

    $id = "";
    for($i= strlen($name) ; $i>=1 ; $i--){
         if($name[$i-1] == 'a'){
               break;
            }else{
          $id = $id.$name[$i-1];
       }
    }
    $userid =  strrev($id);
    $query = "SELECT * FROM bluekolar_user WHERE token = '$name' AND user_id='$userid'";
    $result = $db->select($query);
    if($result){
        if(mysqli_num_rows($result) ==1 ){
            $qu = "UPDATE bluekolar_user SET active = '1' WHERE user_id='$userid'";
            $res = $db->update($qu);
            if($res){
                $url = "profile/index.php?id=".$userid ;
                header('location:'.$url) ;
                exit();
            }else{
                $error = "Provide correct confirmation code";
            }
        }else{
            $error = "Provide correct confirmation code";
        }
    }

  }

 ?>

The code is performing good but it is unable to redirect. I don't know why. I need help.
Please help me so that I can redirect my code command to another page.
Thank you.


问:
Retrieving deep nested values looping through a HTML page using HTMLAgilityPack C#
I'm trying to use the HTMLAgilityPack to retrieve various specific values from a web page. The web page is always the same an the data I want to scrape from it is always in the same place (same divs/classes/attributes etc).

I've tried to loop through and get the values, but I always mess up somewhere. I'd provide some code to help but honestly I've tried 5 times and each time I don't get results close to what I want to - I'm well and truly in a pickle.

I have written the main chunk of HTML:

```<code><div id ="markers">
   <div class="row">
      <div class="span2 filter-pane   ">
         <div class="teaser teaser-small">
            <h1 class="teaser-title">
            <a href="#map" data-lat="Value1" data-lng="Value2" data-name="Value3">...</a>
         </div>
         <p> Value4 </p>
      </div>
   </div>
   <div class="span2 filter-pane   ">
   </div>
   <div class="span2 filter-pane   ">
   </div>
</div>
<div class="row"></div>
<div class="row"></div>
</div>
</code>```

Basically the values (1-4) are the values I want to extract from the data.

The
 is ONE div on the page, all the information I need is in this div.

There are multiple
 divs, I need to loop through all of these.

Inside each of these divs, there are three or less
 divs. I need to loop through these 3 divs also.

My data is inside here - Value3 is here in the
...
. And the other values can be found within the
 node, where they are attributes in an  element.

I hope somebody can provide me with a solution, or at least some good guidance to accessing all pieces of data I want. I've tried various things but I don't get the results I want.

Thanks.

答:
Here are some hints for you. So first you need to get div#markers because you mentioned that it contains all your info you need.

```<code>string mainURL = your url;
HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(mainURL);
var markerDiv = doc.DocumentNode.Descendants("div").FirstOrDefault(n => n.Id.Equal("markers');
//Check if marketDiv is null or not
//Same idea, get list of row divs
var rows = marketDiv.Descendants("div").HasClass("row") //I will provide .HasClass function or you can write your own, it's simple;
//Iterate throw your rows object
//for each row object
var aElement = row.Descendants("a").FirstOrDefault()//you can have more criteria here if it has more than 1 a element
aElement.GetAttributeValue("data-lat", "") //will return Value1 here, do the same thing for other attributes and p.
</code>```

Hope it helps

Body:
I'm trying to use the HTMLAgilityPack to retrieve various specific values from a web page. The web page is always the same an the data I want to scrape from it is always in the same place (same divs/classes/attributes etc).

I've tried to loop through and get the values, but I always mess up somewhere. I'd provide some code to help but honestly I've tried 5 times and each time I don't get results close to what I want to - I'm well and truly in a pickle.

I have written the main chunk of HTML:

            ...

 Value4

Basically the values (1-4) are the values I want to extract from the data.

The
 is ONE div on the page, all the information I need is in this div.

There are multiple
 divs, I need to loop through all of these.

Inside each of these divs, there are three or less
 divs. I need to loop through these 3 divs also.

My data is inside here - Value3 is here in the
...
. And the other values can be found within the
 node, where they are attributes in an  element.

I hope somebody can provide me with a solution, or at least some good guidance to accessing all pieces of data I want. I've tried various things but I don't get the results I want.

Thanks.

Body:
Here are some hints for you. So first you need to get div#markers because you mentioned that it contains all your info you need.

string mainURL = your url;
HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(mainURL);
var markerDiv = doc.DocumentNode.Descendants("div").FirstOrDefault(n => n.Id.Equal("markers');
//Check if marketDiv is null or not
//Same idea, get list of row divs
var rows = marketDiv.Descendants("div").HasClass("row") //I will provide .HasClass function or you can write your own, it's simple;
//Iterate throw your rows object
//for each row object
var aElement = row.Descendants("a").FirstOrDefault()//you can have more criteria here if it has more than 1 a element
aElement.GetAttributeValue("data-lat", "") //will return Value1 here, do the same thing for other attributes and p.

Hope it helps


问:
Refreshing lazy loaded relationships in Entity Framework
I'm trying to find a way to refresh my EF entities after they've been modified by another context. Everything works fine, except for navigation properties, which are not updated.

After the change I've tried both:

```<code>var objectContext = ((IObjectContextAdapter)context).ObjectContext;
objectContext.Refresh(RefreshMode.ClientWins, entity);
</code>```

And:

```<code>context.Entry(entity).Reload();
</code>```

But neither cause the relationship to update. This is the code-first model (with some stuff cut out):

```<code>public class ElementType : IElementType
{
    [Key]
    public Guid ID { get; set; } = Guid.NewGuid();

    public virtual List<Element> Elements { get; set; }
}

public class ElementType : IElementType
{
    [Key]
    public Guid ID { get; set; } = Guid.NewGuid();

    public virtual ElementType ElementType { get; set; }
}
</code>```

I'm adding a new Element, and refresh is not updating the Elements relationship property in ElementType. I know things are getting updated by the other context fine, because when I close everything down and restart it, everthing looks like I expect.

The context is still connected, as I can get the new entity from the DB context. I can even force the ElementType to update it's Element collection in the debugger by navagating to the new Element, checking it's relationship property, (which then triggers ElementType to update):

So it's 0 after the update methods above:

If I navigate to the context in the debugger, check the Elements set, the new Element is present, and the relationship property is set right (and refers to the same Proxy ElementType object). So this is the DBContext's Elements collection:

And now back to the origional Element:

Everything is up to date!

So I'm pretty sure everything is working except the Refresh/Update method. This question here suggests that Reload should work for lazy loaded relationships, and I can't seem to find any further information on how to actually refresh this collection. Anyone know why it's not working as I'd expect it?

答:
Thanks to Cristian Szpisjak pointing me in the direction of the Collection method for the DbEntityEntry.

I wrote a generic method for refreshing my collections:

```<code>    public void Refresh(object entity)
    {
        DbEntityEntry entry = context.Entry(entity);
        entry.Reload();

        var values = entity.GetType().BaseType
                           .GetProperties()
                           .Where(propertyInfo => propertyInfo.GetCustomAttributes(typeof(ReloadCollectionOnRefresh), false).Count() > 0)
                           .Select(propertyInfo => propertyInfo.Name);

        foreach (string value in values)
        {
            var collection = entry.Collection(value);
            collection?.Load();
        }
    }
</code>```

Where the collection properties are tagged with a ReloadCollectionOnRefresh Custom Attribute:

```<code>    [ReloadCollectionOnRefresh]
    public virtual List<MyEntity> MyEntities{ get; set; }
</code>```

which is just a pretty much empty attribute to 'tag' the collection:

```<code>[AttributeUsage(AttributeTargets.Property)]
class ReloadCollectionOnRefresh : Attribute
{
    // can we add checking that this is applied to a virtual collection?
}
</code>```

Body:
I'm trying to find a way to refresh my EF entities after they've been modified by another context. Everything works fine, except for navigation properties, which are not updated.

After the change I've tried both:

var objectContext = ((IObjectContextAdapter)context).ObjectContext;
objectContext.Refresh(RefreshMode.ClientWins, entity);

And:

context.Entry(entity).Reload();

But neither cause the relationship to update. This is the code-first model (with some stuff cut out):

public class ElementType : IElementType
{
    [Key]
    public Guid ID { get; set; } = Guid.NewGuid();

    public virtual List<Element> Elements { get; set; }
}

public class ElementType : IElementType
{
    [Key]
    public Guid ID { get; set; } = Guid.NewGuid();

    public virtual ElementType ElementType { get; set; }
}

I'm adding a new Element, and refresh is not updating the Elements relationship property in ElementType. I know things are getting updated by the other context fine, because when I close everything down and restart it, everthing looks like I expect.

The context is still connected, as I can get the new entity from the DB context. I can even force the ElementType to update it's Element collection in the debugger by navagating to the new Element, checking it's relationship property, (which then triggers ElementType to update):

So it's 0 after the update methods above:

If I navigate to the context in the debugger, check the Elements set, the new Element is present, and the relationship property is set right (and refers to the same Proxy ElementType object). So this is the DBContext's Elements collection:

And now back to the origional Element:

Everything is up to date!

So I'm pretty sure everything is working except the Refresh/Update method. This question here suggests that Reload should work for lazy loaded relationships, and I can't seem to find any further information on how to actually refresh this collection. Anyone know why it's not working as I'd expect it?

Body:
Thanks to Cristian Szpisjak pointing me in the direction of the Collection method for the DbEntityEntry.

I wrote a generic method for refreshing my collections:

    public void Refresh(object entity)
    {
        DbEntityEntry entry = context.Entry(entity);
        entry.Reload();

        var values = entity.GetType().BaseType
                           .GetProperties()
                           .Where(propertyInfo => propertyInfo.GetCustomAttributes(typeof(ReloadCollectionOnRefresh), false).Count() > 0)
                           .Select(propertyInfo => propertyInfo.Name);

        foreach (string value in values)
        {
            var collection = entry.Collection(value);
            collection?.Load();
        }
    }

Where the collection properties are tagged with a ReloadCollectionOnRefresh Custom Attribute:

    [ReloadCollectionOnRefresh]
    public virtual List<MyEntity> MyEntities{ get; set; }

which is just a pretty much empty attribute to 'tag' the collection:

[AttributeUsage(AttributeTargets.Property)]
class ReloadCollectionOnRefresh : Attribute
{
    // can we add checking that this is applied to a virtual collection?
}


问:
Angular 2 Http Post Set Content-Length header to 0
I need to make a POST call with a content-length equal to 0. So I tried setting the header to 0 when I make the call but in the web service that receives the call the content-length is much greater than 0.

Request

```<code>let url = '/blah/blah/'+ anUID +'/blah/' + anotherUID + '';
let headers = new Headers({'Content-Length': '0'});
let options = new RequestOptions({
  method: RequestMethod.Post,
  headers: headers,
});

return this.http.post(url, options)
  .map(this.extractData)
  .catch(this.handleError.bind(this));
</code>```

The on in the receiving web service there is a check to make sure that the request's content length is 0.

```<code>@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("{anUID}/blah/{anotherUID}")
public Response myWebService(@PathParam("anUID") Integer anUID, @PathParam("anotherUID") Integer anotherUID,
        @Context ServletContext application, @Context HttpServletRequest request, @Context UriInfo info) {
    Response resp = Response.notModified().build();
    String method = request.getMethod();    // == "POST"
    int meh = request.getContentLength();   // = 172 NEEDS TO BE 0

    if (request.getContentLength() < 1) {
       ...
    }

    ...
}
</code>```

What could I do differently to set the content-length equal to 0?

答:
You don't need to set header. Just send empty body will do.</p>

```<code>return this.http.post(url, '')
  .map(this.extractData)
  .catch(this.handleError.bind(this));
</code>```

Body:
I need to make a POST call with a content-length equal to 0. So I tried setting the header to 0 when I make the call but in the web service that receives the call the content-length is much greater than 0.

Request

let url = '/blah/blah/'+ anUID +'/blah/' + anotherUID + '';
let headers = new Headers({'Content-Length': '0'});
let options = new RequestOptions({
  method: RequestMethod.Post,
  headers: headers,
});

return this.http.post(url, options)
  .map(this.extractData)
  .catch(this.handleError.bind(this));

The on in the receiving web service there is a check to make sure that the request's content length is 0.

@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("{anUID}/blah/{anotherUID}")
public Response myWebService(@PathParam("anUID") Integer anUID, @PathParam("anotherUID") Integer anotherUID,
        @Context ServletContext application, @Context HttpServletRequest request, @Context UriInfo info) {
    Response resp = Response.notModified().build();
    String method = request.getMethod();    // == "POST"
    int meh = request.getContentLength();   // = 172 NEEDS TO BE 0

    if (request.getContentLength() < 1) {
       ...
    }

    ...
}

What could I do differently to set the content-length equal to 0?

Body:
You don't need to set header. Just send empty body will do.

return this.http.post(url, '')
  .map(this.extractData)
  .catch(this.handleError.bind(this));


问:
math_functions.hpp not found when using CUDA with Eigen
I have some code that is heavily dependent on Eigen. I would like to optimize it with CUDA, but when I am compiling I get:

```<code>[tcai4@golubh4 Try1]$ nvcc conv_parallel.cu -I /home/tcai4/project-cse/Try1 -lfftw3 -o conv.o
In file included from Eigen/Dense:1,
             from Eigen/Eigen:1,
             from functions.h:8,
             from conv_parallel.cu:10:
Eigen/Core:44:34: error: math_functions.hpp: No such file or directory
</code>```

I think math_functions.hpp is a file from CUDA. Can someone help me figure out why nvcc cannot find it?

edit: I am using CUDA 5.5 and Eigen 3.3, except from linking Eigen and fftw3 library, I did not use any other flags(as you can see from my code).

答:
The reason nvcc cannot find the file in question is because that file is part of the CUDA Math library, which was introduced in CUDA 6. Your almost 4 year old version of CUDA predates the release of the Math library. Your CUDA version doesn't contain said file.

You should, therefore, assume that what you are trying to do cannot work without first updating to a newer version of the CUDA toolkit.

Body:
I have some code that is heavily dependent on Eigen. I would like to optimize it with CUDA, but when I am compiling I get:

[tcai4@golubh4 Try1]$ nvcc conv_parallel.cu -I /home/tcai4/project-cse/Try1 -lfftw3 -o conv.o
In file included from Eigen/Dense:1,
             from Eigen/Eigen:1,
             from functions.h:8,
             from conv_parallel.cu:10:
Eigen/Core:44:34: error: math_functions.hpp: No such file or directory

I think math_functions.hpp is a file from CUDA. Can someone help me figure out why nvcc cannot find it?

edit: I am using CUDA 5.5 and Eigen 3.3, except from linking Eigen and fftw3 library, I did not use any other flags(as you can see from my code).


问:
Using the Bot Framework to send message on the user's behalf
I'm currently attempting to accept voice input from the user, feed it into the Bing Speech API to get text, and pass that text as a user response. I've gotten as far as receiving the text back from Bing, but I'm not sure how to send that text as a user response. I've been scouring GitHub, so any feedback is appreciated. Relevant code is below:</p>

```<code>function(session){
    var bing = new client.BingSpeechClient('mykey');
    var results = '';
    var wave = fs.readFileSync('./new.wav');

    const text = bing.recognize(wave).then(result => {
      console.log('Speech To Text completed');
      console.log(result.header.lexical)
      console.log('\n');
      results.response = result.header.lexical;
    });
    }]
</code>```

答:
You should use session.send.

I recommend you to take a look to the intelligence-SpeechToText sample, where a similar scenario is being shown.

Body:
I'm currently attempting to accept voice input from the user, feed it into the Bing Speech API to get text, and pass that text as a user response. I've gotten as far as receiving the text back from Bing, but I'm not sure how to send that text as a user response. I've been scouring GitHub, so any feedback is appreciated. Relevant code is below:

function(session){
    var bing = new client.BingSpeechClient('mykey');
    var results = '';
    var wave = fs.readFileSync('./new.wav');

    const text = bing.recognize(wave).then(result => {
      console.log('Speech To Text completed');
      console.log(result.header.lexical)
      console.log('\n');
      results.response = result.header.lexical;
    });
    }]


问:
How to create a url for a view that has a variable passed into it?
I've looked into this on my own and I'm currently not having any luck.  I read Microsoft's documentation on routes and I've tried to implement it but I don't quite understand how it works.  I tried working it out but all of the routes I tried are giving me the same error, so currently I am still using the Default route in RouteConfig.cs.

For my Controller I have a class that takes in a int

```<code>public ActionResult ViewGame(int id)
</code>```

In my .cshtml file for it I have a list of games, with their names being Html.ActionLink to take the user to the correct page when you click on the link.

```<code>@Html.ActionLink(game.title, "ViewGame", "Game", new { id = game.id })
</code>```

When I am selecting the link it is sending me to url like this:

```<code>http://localhost:58858/Home/ViewGame?Length=4
</code>```

The error on the page reads:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Home/ViewGame

I'm unsure how to fix this error and what I need to do to make

答:
You are using the method overload wrong

There is another overload of ActionLink helper which lets you specify the controller name, action name and the route values.

```<code>public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    object routeValues,
    object htmlAttributes
)
</code>```

This should work

```<code>@Html.ActionLink(game.title, "ViewGame", "Game", new { id = game.id },null)
</code>```

Body:
I've looked into this on my own and I'm currently not having any luck.  I read Microsoft's documentation on routes and I've tried to implement it but I don't quite understand how it works.  I tried working it out but all of the routes I tried are giving me the same error, so currently I am still using the Default route in RouteConfig.cs.

For my Controller I have a class that takes in a int

public ActionResult ViewGame(int id)

In my .cshtml file for it I have a list of games, with their names being Html.ActionLink to take the user to the correct page when you click on the link.

@Html.ActionLink(game.title, "ViewGame", "Game", new { id = game.id })

When I am selecting the link it is sending me to url like this:

http://localhost:58858/Home/ViewGame?Length=4

The error on the page reads:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Home/ViewGame

I'm unsure how to fix this error and what I need to do to make

Body:
You are using the method overload wrong

There is another overload of ActionLink helper which lets you specify the controller name, action name and the route values.

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    object routeValues,
    object htmlAttributes
)

This should work

@Html.ActionLink(game.title, "ViewGame", "Game", new { id = game.id },null)


问:
Json Deserialize C#
I want to parsing this json file.

{"features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[26.4217861898109,40.127607984644],[26.4219934821323,40.1275230229872],[26.4218810759267,40.1273800013679],[26.4216801413981,40.1274730404221],[26.4217861898109,40.127607984644]]]},"properties":{"ParselNo":"1","Alan":"340.48
  m2","Mevkii":"-","Nitelik":"Arsa","Ada":"698","Il":"Çanakkale","Ilce":"Merkez","Pafta":"16","Mahalle":"Barbaros"}}],"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:4326"}}}

I try this code:

```<code>string fileName = file.FileName;
string json = System.IO.File.ReadAllText(fileName);
dynamic stuff = JsonConvert.DeserializeObject(json);

string s1 = Convert.ToString(stuff.features.Count);
string s2 = stuff.properties.ParselNo;
MessageBox.Show(s1);
MessageBox.Show(s2);
</code>```

s1 is working but s2 give error. How can I fix it?

I want to get it like this:

```<code>Coordinates[] coordinates = [(26.xx, 40.xx), (26.xx,40.xx) ... ]
ParselNo = 1
Alan = 340.48
Nitelik = Arsa
Ada = 698
İl = Çanakkale
İlçe = Merkez
Pafta = 16
dat_name = EPSG:4326
</code>```

what can i do?

答:
According to the json you provided features are  List<Feature> so you cannot access a property of list like stuff.features.properties.ParselNo it should be

stuff.features[0].properties.ParselNo

i used features[0] because it will get the first feature from the list and features.Count will return the number of features in list  you can use http://json2csharp.com/ to check your json

Edit

and about your second question it should be like this

```<code>List<List<double>> s2 =stuff.features[0].geometry.coordinates[0].ToObject<List<List<double>>>();
var firstcordinates = s2[0];
</code>```

it will get the coordinates from array and s2[0] will get first coordinates from list

Title: Json Deserialize C#

Body:
I want to parsing this json file.

{"features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[26.4217861898109,40.127607984644],[26.4219934821323,40.1275230229872],[26.4218810759267,40.1273800013679],[26.4216801413981,40.1274730404221],[26.4217861898109,40.127607984644]]]},"properties":{"ParselNo":"1","Alan":"340.48
  m2","Mevkii":"-","Nitelik":"Arsa","Ada":"698","Il":"Çanakkale","Ilce":"Merkez","Pafta":"16","Mahalle":"Barbaros"}}],"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:4326"}}}

I try this code:

string fileName = file.FileName;
string json = System.IO.File.ReadAllText(fileName);
dynamic stuff = JsonConvert.DeserializeObject(json);

string s1 = Convert.ToString(stuff.features.Count);
string s2 = stuff.properties.ParselNo;
MessageBox.Show(s1);
MessageBox.Show(s2);

s1 is working but s2 give error. How can I fix it?

I want to get it like this:

Coordinates[] coordinates = [(26.xx, 40.xx), (26.xx,40.xx) ... ]
ParselNo = 1
Alan = 340.48
Nitelik = Arsa
Ada = 698
İl = Çanakkale
İlçe = Merkez
Pafta = 16
dat_name = EPSG:4326

what can i do?

Body:
According to the json you provided features are  List<Feature> so you cannot access a property of list like stuff.features.properties.ParselNo it should be

stuff.features[0].properties.ParselNo

i used features[0] because it will get the first feature from the list and features.Count will return the number of features in list  you can use http://json2csharp.com/ to check your json

Edit

and about your second question it should be like this

List<List<double>> s2 =stuff.features[0].geometry.coordinates[0].ToObject<List<List<double>>>();
var firstcordinates = s2[0];

it will get the coordinates from array and s2[0] will get first coordinates from list


问:
Kentico 9 tild not being resolved for files
I have a custom page Type that lets the user select uploaded files (pdf, docx, xlxs). I've noticed that the tilde (~) is not being resolved when i look at the rendered page. I've checked the Output Filter in settings, but the settings here are default. What am I missing?

Here's a snippet from my transformation

```<code><%# IfEmpty(Eval("File"),"n/a","<a href=" + Eval("File") +" target='blank'><span class='fa fa-download'></span></a>")%>
</code>```

答:
Can you try what's described in this post?
https://devnet.kentico.com/questions/tilde-being-added-to-src-attribute-of-image-tags-in-static-html-webpart</p>

Body:
I have a custom page Type that lets the user select uploaded files (pdf, docx, xlxs). I've noticed that the tilde (~) is not being resolved when i look at the rendered page. I've checked the Output Filter in settings, but the settings here are default. What am I missing?

Here's a snippet from my transformation

<%# IfEmpty(Eval("File"),"n/a","")%>


问:
Best Way to Implement Unique ID DynamoDB Swift
I am working on an app where users can create posts that uses Amazon DynamoDB. One of the attributes of a post item in the database is postId. I am searching for the best practice to set this value upon creation. So far, I have thought of:

Counting the current items in the DB and then assigning the value as postId = dbcount + 1. I cannot find a count method for DynamoDB using Swift, and the ways I have found (scan & description) are either inefficient or accurate. Also, I thought of the scenario of 2 users posting at the same time.

I could create a UUID with Swift and set the postId to this value.

Upon these 2 options, which route is better? Is there a preferred industry standard? Option 2 seems to be the better choice, but I am not sure. Are there any other potential alternatives? Thank you!

答:
I would definitely stay away from option 1 - as you said the potential for a race condition is too high and it could be expensive to implement too.

A UUID would certain work and is likely to be the least painful.  However, there are other options too.  An atomic counter would work.  A bit more complicated but you could even use a conditional write.  But the logic for that would be a pain.

The advantage of the UUID is that you generate it so that it can be used for, as an example, a row of data in a child table.


问:
RegularExpressionValidator ErrorMessage With Border Overflowing Across Two Lines
When attempting to create a lengthy RegEx ErrorMessage via server controls, I though it would be a nice add a background color and boarder to give the message some "flair".

When I tried attaching a CssClassto the server control with a border and color, the border ran over across two lines like below:

```<code>______________________________________
|                                     |
|    ---------------------------      |
|   | My very long error message      |  <-- confined box where error
|    ----------------------------     |      messages and text-box for input
|    ----------------------------     |      resides
|      that ran over two lines  |     |
|   ---------------------------       |
|                                     |
|              ^                      |
|              | The two line error   |
|                 message             |
|_____________________________________|

<asp:RegularExpressionValidator
    ID="MyFirstRegex"
    ControlToValidate="SomeControl"
    runat="server">
    Display="Dynamic"
    CssClass="SomeClass"
    ValidationGroup="MyGroup"
    ErrorMessage="Silly User. <br\> You made a very, very, very, very, very dumb error"<br />"
    ValidationExpression="regex code to validate"
</asp:RegularExpressionValidator>

<asp:RequiredFieldValidator
    ID="ReqOne"
    ValidationGroup="MyGroup"
    ControlToValidate="SomeControl"
    runat="server">
</asp:RequiredFieldValidator>
</code>```

Also, when it hides, the boarder is visible (just not the contents)

I have tried placing the control in a div with run at server. The issue with that is when you hide the div, the regex validation stops. Any ideas on how to approach this?

答:
Normally you set Validators to Display="Dynamic". This ensures they do not take us space until they are triggered by a button.
This is done by aspnet by adding style="display:none;" to the  element containing the error message.

```<code><span id="RequiredFieldValidator1" style="display: none;">RequiredFieldValidator</span>
</code>```

Now when the validator is triggered the style is changed from display:none to display: inline.

```<code><span id="RequiredFieldValidator1" class="SomeClass" style="display: inline;">RequiredFieldValidator</span>
</code>```

And it is with the inline part that causes all the problems. We want it to be a normal block. To do that you can override a javascript function that normally is located in the ScriptResource.axd file. That function is called ValidatorUpdateDisplay, and is has a line which contains val.style.display = val.isvalid ? "none" : "inline";. That is the line that needs to be overridden.

```<code><script type="text/javascript">
    function ValidatorUpdateDisplay(val) {
        if (typeof (val.display) == "string") {
            if (val.display == "None") {
                return;
            }
            if (val.display == "Dynamic") {
                val.style.display = val.isvalid ? "none" : "block";
                return;
            }
        }
        if ((navigator.userAgent.indexOf("Mac") > -1) &&
            (navigator.userAgent.indexOf("MSIE") > -1)) {
            val.style.display = "inline";
        }
        val.style.visibility = val.isvalid ? "hidden" : "visible";
    }
</script>
</code>```

Body:
When attempting to create a lengthy RegEx ErrorMessage via server controls, I though it would be a nice add a background color and boarder to give the message some "flair".

When I tried attaching a CssClassto the server control with a border and color, the border ran over across two lines like below:

______________________________________
|                                     |
|    ---------------------------      |
|   | My very long error message      |  <-- confined box where error
|    ----------------------------     |      messages and text-box for input
|    ----------------------------     |      resides
|      that ran over two lines  |     |
|   ---------------------------       |
|                                     |
|              ^                      |
|              | The two line error   |
|                 message             |
|_____________________________________|

<asp:RegularExpressionValidator
    ID="MyFirstRegex"
    ControlToValidate="SomeControl"
    runat="server">
    Display="Dynamic"
    CssClass="SomeClass"
    ValidationGroup="MyGroup"
    ErrorMessage="Silly User.
 You made a very, very, very, very, very dumb error"
"
    ValidationExpression="regex code to validate"
</asp:RegularExpressionValidator>

<asp:RequiredFieldValidator
    ID="ReqOne"
    ValidationGroup="MyGroup"
    ControlToValidate="SomeControl"
    runat="server">
</asp:RequiredFieldValidator>

Also, when it hides, the boarder is visible (just not the contents)

I have tried placing the control in a div with run at server. The issue with that is when you hide the div, the regex validation stops. Any ideas on how to approach this?

Body:
Normally you set Validators to Display="Dynamic". This ensures they do not take us space until they are triggered by a button.
This is done by aspnet by adding style="display:none;" to the <span> element containing the error message.

<span id="RequiredFieldValidator1" style="display: none;">RequiredFieldValidator</span>

Now when the validator is triggered the style is changed from display:none to display: inline.

<span id="RequiredFieldValidator1" class="SomeClass" style="display: inline;">RequiredFieldValidator</span>

And it is with the inline part that causes all the problems. We want it to be a normal block. To do that you can override a javascript function that normally is located in the ScriptResource.axd file. That function is called ValidatorUpdateDisplay, and is has a line which contains val.style.display = val.isvalid ? "none" : "inline";. That is the line that needs to be overridden.

<script type="text/javascript">
    function ValidatorUpdateDisplay(val) {
        if (typeof (val.display) == "string") {
            if (val.display == "None") {
                return;
            }
            if (val.display == "Dynamic") {
                val.style.display = val.isvalid ? "none" : "block";
                return;
            }
        }
        if ((navigator.userAgent.indexOf("Mac") > -1) &&
            (navigator.userAgent.indexOf("MSIE") > -1)) {
            val.style.display = "inline";
        }
        val.style.visibility = val.isvalid ? "hidden" : "visible";
    }
</script>


问:
Error in Spark 1.3.1 (PySpark) and MongoDB 3.4
I have a very simple script to persist a dataframe with two columns in MongoDB:

```<code>from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
from pyspark.sql.types import *
from pyspark.sql.functions import col, udf
from datetime import datetime

sparkConf = SparkConf().setMaster("local").setAppName("Wiki-Analyzer").set("spark.app.id", "Wiki-Analyzer")
sparkConf.set("spark.mongodb.input.uri", "...")
sparkConf.set("spark.mongodb.output.uri", "...")

sc = SparkContext(conf=sparkConf)
sqlContext = SQLContext(sc)

charactersRdd = sc.parallelize([("Bilbo Baggins",  50), ("Gandalf", 1000), ("Thorin", 195), ("Balin", 178), ("Kili", 77), ("Dwalin", 169), ("Oin", 167), ("Gloin", 158), ("Fili", 82), ("Bombur", None)])
    characters = sqlContext.createDataFrame(charactersRdd, ["name", "age"])
    characters.write.format("com.mongodb.spark.sql.DefaultSource").mode("overwrite").save()
</code>```

But I get the following error:

```<code>py4j.protocol.Py4JJavaError: An error occurred while calling o91.apply.
: org.apache.spark.sql.AnalysisException: Cannot resolve column name "write" among (name, age);
        at org.apache.spark.sql.DataFrame$$anonfun$resolve$1.apply(DataFrame.scala:162)
        at org.apache.spark.sql.DataFrame$$anonfun$resolve$1.apply(DataFrame.scala:162)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.sql.DataFrame.resolve(DataFrame.scala:161)
        at org.apache.spark.sql.DataFrame.col(DataFrame.scala:447)
        at org.apache.spark.sql.DataFrame.apply(DataFrame.scala:437)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:379)
        at py4j.Gateway.invoke(Gateway.java:259)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:207)
        at java.lang.Thread.run(Thread.java:745)
</code>```

I am runing the script with:

```<code>spark-submit --packages org.mongodb.spark:mongo-spark-connector_2.10:1.1.0 wiki-analyzer.py
</code>```

Thank you in advance!

答:
The problem here is that in

```<code>characters.write.format("com.mongodb.spark.sql.DefaultSource").mode("overwrite").save()
</code>```

the .write is being interpreted as selecting a column named "write". The reason for this is that you're using Spark 1.3.1, which doesn't support the .write syntax in its generic load/save functions (see Spark 1.3.1 docs); that syntax is only supported in Spark 1.4.0+ (see Spark 1.4.0 docs).

If you must use Spark 1.3.x, try

```<code>characters.save(source="com.mongodb.spark.sql.DefaultSource", mode="overwrite")
</code>```

(based on the DataFrame.save() Python API docs for Spark 1.3.x).

If at all possible, though, I'd recommend upgrading to a newer Spark version (1.6.x or 2.1.x).

Body:
I have a very simple script to persist a dataframe with two columns in MongoDB:

from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
from pyspark.sql.types import *
from pyspark.sql.functions import col, udf
from datetime import datetime

sparkConf = SparkConf().setMaster("local").setAppName("Wiki-Analyzer").set("spark.app.id", "Wiki-Analyzer")
sparkConf.set("spark.mongodb.input.uri", "...")
sparkConf.set("spark.mongodb.output.uri", "...")

sc = SparkContext(conf=sparkConf)
sqlContext = SQLContext(sc)

charactersRdd = sc.parallelize([("Bilbo Baggins",  50), ("Gandalf", 1000), ("Thorin", 195), ("Balin", 178), ("Kili", 77), ("Dwalin", 169), ("Oin", 167), ("Gloin", 158), ("Fili", 82), ("Bombur", None)])
    characters = sqlContext.createDataFrame(charactersRdd, ["name", "age"])
    characters.write.format("com.mongodb.spark.sql.DefaultSource").mode("overwrite").save()

But I get the following error:

py4j.protocol.Py4JJavaError: An error occurred while calling o91.apply.
: org.apache.spark.sql.AnalysisException: Cannot resolve column name "write" among (name, age);
        at org.apache.spark.sql.DataFrame$$anonfun$resolve$1.apply(DataFrame.scala:162)
        at org.apache.spark.sql.DataFrame$$anonfun$resolve$1.apply(DataFrame.scala:162)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.sql.DataFrame.resolve(DataFrame.scala:161)
        at org.apache.spark.sql.DataFrame.col(DataFrame.scala:447)
        at org.apache.spark.sql.DataFrame.apply(DataFrame.scala:437)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:379)
        at py4j.Gateway.invoke(Gateway.java:259)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:207)
        at java.lang.Thread.run(Thread.java:745)

I am runing the script with:

spark-submit --packages org.mongodb.spark:mongo-spark-connector_2.10:1.1.0 wiki-analyzer.py

Thank you in advance!

Body:
The problem here is that in

characters.write.format("com.mongodb.spark.sql.DefaultSource").mode("overwrite").save()

the .write is being interpreted as selecting a column named "write". The reason for this is that you're using Spark 1.3.1, which doesn't support the .write syntax in its generic load/save functions (see Spark 1.3.1 docs); that syntax is only supported in Spark 1.4.0+ (see Spark 1.4.0 docs).

If you must use Spark 1.3.x, try

characters.save(source="com.mongodb.spark.sql.DefaultSource", mode="overwrite")

(based on the DataFrame.save() Python API docs for Spark 1.3.x).

If at all possible, though, I'd recommend upgrading to a newer Spark version (1.6.x or 2.1.x).


问:
JavaScript non selectable text not working in Chrome/Internet Explorer
In Firefox seems fine, Chrome and Internet Explorer the text is still selectable, is there any way around this? The code was taken from another question, (which I can't find right now) so it may be out of date?

```<code>// Prevent selection
function disableSelection(target) {
    if (typeof target.onselectstart != "undefined") // Internet Explorer route
        target.onselectstart = function() { return false }
    else if (typeof target.style.MozUserSelect != "undefined") // Firefox route
        target.style.MozUserSelect = "none"
    else // All other routes (for example, Opera)
        target.onmousedown = function() { return false }
}
</code>```

Used in code as:

```<code>disableSelection(document.getElementById("gBar"));
</code>```

答:
Like the MozUserSelect styling in Firefox you can use -webkit-user-select: none for Webkit based browser (like Safari and Chrome).

I think that you can use -o-user-select: none in Opera. But I have not tested it.

```<code>// Prevent selection
function disableSelection(target) {
    if (typeof target.onselectstart != "undefined") //IE route
        target.onselectstart = function() { return false }
    else if (typeof target.style.userSelect != "undefined") //Some day in the future?
        target.style.userSelect = "none"
    else if (typeof target.style.webkitUserSelect != "undefined") //Webkit route
        target.style.webkitUserSelect = "none"
    else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
        target.style.MozUserSelect = "none"
    else //All other route (ie: Opera)
        target.onmousedown = function() { return false }
}
</code>```

For IE, maybe this can help you: http://msdn.microsoft.com/en-us/library/ms534706(VS.85).aspx

ContentLicense: CC BY-SA 4.0

Body:
In Firefox seems fine, Chrome and Internet Explorer the text is still selectable, is there any way around this? The code was taken from another question, (which I can't find right now) so it may be out of date?

// Prevent selection
function disableSelection(target) {
    if (typeof target.onselectstart != "undefined") // Internet Explorer route
        target.onselectstart = function() { return false }
    else if (typeof target.style.MozUserSelect != "undefined") // Firefox route
        target.style.MozUserSelect = "none"
    else // All other routes (for example, Opera)
        target.onmousedown = function() { return false }
}

Used in code as:

disableSelection(document.getElementById("gBar"));

Body:
Like the MozUserSelect styling in Firefox you can use -webkit-user-select: none for Webkit based browser (like Safari and Chrome).

I think that you can use -o-user-select: none in Opera. But I have not tested it.

// Prevent selection
function disableSelection(target) {
    if (typeof target.onselectstart != "undefined") //IE route
        target.onselectstart = function() { return false }
    else if (typeof target.style.userSelect != "undefined") //Some day in the future?
        target.style.userSelect = "none"
    else if (typeof target.style.webkitUserSelect != "undefined") //Webkit route
        target.style.webkitUserSelect = "none"
    else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
        target.style.MozUserSelect = "none"
    else //All other route (ie: Opera)
        target.onmousedown = function() { return false }
}

For IE, maybe this can help you: http://msdn.microsoft.com/en-us/library/ms534706(VS.85).aspx

ContentLicense: CC BY-SA 2.5


问:
Conversion of class variable to method argument in recursive program
I have solved the leetcode problem to find Sum of left leaves in a tree with this code. I know using class vairables as a temp varible in recursion is a not good practice and some how the temp result need to be passed as the method argument. In this case I want to avoid using the class variable sum and make helper method sumOfLeftLeaves(TreeNode root,TreeNode parent,int sum) with additional argument. Please suggest me how to modify method. I tried different ways to do it but getting struck with returning the values.

```<code>//Find sum of all left nodes in a binary tree.
public class Solution {
        //Class variable to capture sum
        int sum = 0;
        public int sumOfLeftLeaves(TreeNode root) {
             sumOfLeftLeaves(root,null);
             return sum;
        }

        public void sumOfLeftLeaves(TreeNode root,TreeNode parent){
            if(root != null){
                sumOfLeftLeaves(root.left,root);
                //If the node is a leaft node and it is left node to the parent
                if(root.left == null && root.right == null && (parent != null && parent.left == root)){
                    sum += root.val;
                }
                sumOfLeftLeaves(root.right,root);
            }
        }
    }
</code>```

答:
Always define a recursive problem in terms of simpler versions of itself.

Call the function LL.

Base cases: LL( empty ) ≡ 0, LL( left leaf node ) ≡ node.val, LL( right leaf node ) ≡ 0

Inductive case: given LL( node.left ) and LL( node.right ) -> LL( node ) ≡ LL( node.left ) + LL( node.right )

```<code>public int sumOfLeftLeavesAux( TreeNode node, boolean flgIsLeftChild ) {
    // base case: empty tree
    if ( node == null )
        return 0;
    // base case: leaf node
    if ( node.left == null && node.right == null )
        return flgIsLeftChild ? node.val : 0;
    // inductive case
    return sumOfLeftLeavesAux( node.left, true ) + sumOfLeftLeavesAux( node.right, false );
}
</code>```

Body:
I have solved the leetcode problem to find Sum of left leaves in a tree with this code. I know using class vairables as a temp varible in recursion is a not good practice and some how the temp result need to be passed as the method argument. In this case I want to avoid using the class variable sum and make helper method sumOfLeftLeaves(TreeNode root,TreeNode parent,int sum) with additional argument. Please suggest me how to modify method. I tried different ways to do it but getting struck with returning the values.

//Find sum of all left nodes in a binary tree.
public class Solution {
        //Class variable to capture sum
        int sum = 0;
        public int sumOfLeftLeaves(TreeNode root) {
             sumOfLeftLeaves(root,null);
             return sum;
        }

        public void sumOfLeftLeaves(TreeNode root,TreeNode parent){
            if(root != null){
                sumOfLeftLeaves(root.left,root);
                //If the node is a leaft node and it is left node to the parent
                if(root.left == null && root.right == null && (parent != null && parent.left == root)){
                    sum += root.val;
                }
                sumOfLeftLeaves(root.right,root);
            }
        }
    }

Body:
Always define a recursive problem in terms of simpler versions of itself.

Call the function LL.

Base cases: LL( empty ) ≡ 0, LL( left leaf node ) ≡ node.val, LL( right leaf node ) ≡ 0

Inductive case: given LL( node.left ) and LL( node.right ) -> LL( node ) ≡ LL( node.left ) + LL( node.right )

public int sumOfLeftLeavesAux( TreeNode node, boolean flgIsLeftChild ) {
    // base case: empty tree
    if ( node == null )
        return 0;
    // base case: leaf node
    if ( node.left == null && node.right == null )
        return flgIsLeftChild ? node.val : 0;
    // inductive case
    return sumOfLeftLeavesAux( node.left, true ) + sumOfLeftLeavesAux( node.right, false );
}


问:
Toolbar title not visible with CollapsingToolBarLayout
```<code><android.support.design.widget.AppBarLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <!--    ******************    TOOLBAR    *******************    -->
    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_scrollFlags="scroll|snap"

        >
        <android.support.v7.widget.Toolbar
            app:layout_scrollFlags="scroll|enterAlways|snap"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/toolbar"
            >
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>
</code>```

Hello everyone.
My toolbar is not visible even though I have set it in my activity with:

```<code>(toolbar.setTitle("TITLE");
        toolbar.setTitleTextColor(0xFFFFFF);
</code>```

I have provided a snip of my .XML file.
Since I am a noob, I'm requesting the stackoverflow army for help.

Thanks a lot for helping me out.

答:
If you need to set in in your Activity  you can use support action bar like this.

on onCreate

```<code>     setSupportActionBar(toolbar);
</code>```

then later when you are going to set your title try this.

```<code>     if (getSupportActionBar() != null) {
        if (title!=null) {
            getSupportActionBar().setDisplayShowTitleEnabled(true);
            getSupportActionBar().setTitle(title);
        } else {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
    }
</code>```

If not you may use xml option too:

```<code>    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:title="TITLE"
    app:popupTheme="@style/AppTheme.PopupOverlay">
</code>```

Hope it helps.

Body:
<android.support.design.widget.AppBarLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_scrollFlags="scroll|snap"

        >
        <android.support.v7.widget.Toolbar
            app:layout_scrollFlags="scroll|enterAlways|snap"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/toolbar"
            >
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>

Hello everyone.
My toolbar is not visible even though I have set it in my activity with:

(toolbar.setTitle("TITLE");
        toolbar.setTitleTextColor(0xFFFFFF);

I have provided a snip of my .XML file.
Since I am a noob, I'm requesting the stackoverflow army for help.

Thanks a lot for helping me out.

Body:
If you need to set in in your Activity  you can use support action bar like this.

on onCreate

     setSupportActionBar(toolbar);

then later when you are going to set your title try this.

     if (getSupportActionBar() != null) {
        if (title!=null) {
            getSupportActionBar().setDisplayShowTitleEnabled(true);
            getSupportActionBar().setTitle(title);
        } else {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
    }

If not you may use xml option too:

    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:title="TITLE"
    app:popupTheme="@style/AppTheme.PopupOverlay">

Hope it helps.


问:
How to configure DateFormatter to capture microseconds
iOS Date() returns date with at least microsecond precision.

I checked this statement by calling Date().timeIntervalSince1970 which results in 1490891661.074981

Then I need to convert date into string with microsecond precision.

I am using DateFormatter in following way:

```<code>let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ"
print(formatter.string(from: date))
</code>```

which results in

"2017-03-30T16:34:21.075000Z"

Now if we compare two results:

1490891661.074981 and "2017-03-30T16:34:21.075000Z"

we can notice that DateFormatter rounds date to millisecond precision while still presenting zeros for microseconds.

Does anybody know how to configure DateFormatter so I can keep microseconds and get correct result: "2017-03-30T16:34:21.074981Z"?

答:
The resolution of (NS)DateFormatter is limited to milliseconds, compare
NSDateFormatter milliseconds bug. A possible solution is to retrieve all date components (up to
nanoseconds) as numbers and do a custom string formatting. The date formatter can still be used for the timezone string.

Example:

```<code>let date = Date(timeIntervalSince1970: 1490891661.074981)

let formatter = DateFormatter()
formatter.dateFormat = "ZZZZZ"
let tzString = formatter.string(from: date)

let cal = Calendar.current
let comps = cal.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond],
                               from: date)
let microSeconds = lrint(Double(comps.nanosecond!)/1000) // Divide by 1000 and round

let formatted = String(format: "%04ld-%02ld-%02ldT%02ld:%02ld:%02ld.%06ld",
                       comps.year!, comps.month!, comps.day!,
                       comps.hour!, comps.minute!, comps.second!,
                       microSeconds) + tzString

print(formatted) // 2017-03-30T18:34:21.074981+02:00
</code>```

Body:
iOS Date() returns date with at least microsecond precision.

I checked this statement by calling Date().timeIntervalSince1970 which results in 1490891661.074981

Then I need to convert date into string with microsecond precision.

I am using DateFormatter in following way:

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ"
print(formatter.string(from: date))

which results in

"2017-03-30T16:34:21.075000Z"

Now if we compare two results:

1490891661.074981 and "2017-03-30T16:34:21.075000Z"

we can notice that DateFormatter rounds date to millisecond precision while still presenting zeros for microseconds.

Does anybody know how to configure DateFormatter so I can keep microseconds and get correct result: "2017-03-30T16:34:21.074981Z"?

Body:
The resolution of (NS)DateFormatter is limited to milliseconds, compare
NSDateFormatter milliseconds bug. A possible solution is to retrieve all date components (up to
nanoseconds) as numbers and do a custom string formatting. The date formatter can still be used for the timezone string.

Example:

let date = Date(timeIntervalSince1970: 1490891661.074981)

let formatter = DateFormatter()
formatter.dateFormat = "ZZZZZ"
let tzString = formatter.string(from: date)

let cal = Calendar.current
let comps = cal.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond],
                               from: date)
let microSeconds = lrint(Double(comps.nanosecond!)/1000) // Divide by 1000 and round

let formatted = String(format: "%04ld-%02ld-%02ldT%02ld:%02ld:%02ld.%06ld",
                       comps.year!, comps.month!, comps.day!,
                       comps.hour!, comps.minute!, comps.second!,
                       microSeconds) + tzString

print(formatted) // 2017-03-30T18:34:21.074981+02:00


问:
Text wont center on phone
I have a weird problem here, the text and images aren't aligning to the center, I've been coding this site from scratch and it works pretty well when I test it on the computer, but when I try it on the phone it doesn't work. Here are the pictures (From the computer and the phone)

---------COMPUTER
Computer's resized Firefox windows 1

---------PHONE
Phone's screenshot 1 - Chrome

Here's my code, I've been using bootstrap and normal HTML, CSS and basic PHP and JavaScript

```<code><nav class="navbar navbar-default nav_menu_head">
<div class="container-fluid">
<div class="row">
    <nav class="navbar navbar-default nav_menu_head">
  <div class="container-fluid">
<div class="row">
   <div class="navbar-header">

      <div class="col-md-6 col-xs-10">
       <a href="index.php" class="navbar-brand" rel="home">
        <img class="img-responsive logo" src="img/logo2.png"></a>

      </div>
      <div class="col-xs-2">
  <button type="button" class="navbar-toggle navbar_colapse" data-toggle="collapse" data-target="#myNavbar">
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
     </div>

      <div class="collapse navbar-collapse col-md-6 text-justify-xs" id="myNavbar">
     <ul class="nav navbar-nav navbar-right nav_menu_head" >
  <li ><a href="index.php#empresa" >EMPRESA</a></li>
  <li ><a href="productos.php">PRODUCTO</a></li>
  <li><a href="index.php#contacto">CONTACTO</a></li>
<!--  <li ><a href="#">SOPORTE TÉCNICO</a></li -->
</ul>
</div>
</div>
 </nav>
</code>```

And here´s the CSS

```<code>.text_box{width: 100%;
height: 200px;}
.navbar-header{float: none;}

.text-justify-xs {
text-align: center;
}

.img-responsive.menu_image{margin: 0 auto;}
.collapse.navbar-collapse.col-md-6.text-justify-xs {border-width: 0px;}
</code>```

答:
try :

```<code>.text-justify-xs ul li a {
    text-align: center;
}
</code>```

in your css

Title: Text wont center on phone

Body:
I have a weird problem here, the text and images aren't aligning to the center, I've been coding this site from scratch and it works pretty well when I test it on the computer, but when I try it on the phone it doesn't work. Here are the pictures (From the computer and the phone)

---------COMPUTER
Computer's resized Firefox windows 1

---------PHONE
Phone's screenshot 1 - Chrome

Here's my code, I've been using bootstrap and normal HTML, CSS and basic PHP and JavaScript

  <button type="button" class="navbar-toggle navbar_colapse" data-toggle="collapse" data-target="#myNavbar">

  </button>

EMPRESA

PRODUCTO

CONTACTO

And here´s the CSS

.text_box{width: 100%;
height: 200px;}
.navbar-header{float: none;}

.text-justify-xs {
text-align: center;
}

.img-responsive.menu_image{margin: 0 auto;}
.collapse.navbar-collapse.col-md-6.text-justify-xs {border-width: 0px;}

Body:
try :

.text-justify-xs ul li a {
    text-align: center;
}

in your css


问:
Can you use math calculations on two alias columns in MySQL?
I want to do this:

```<code>SELECT SUM(currentbalance) AS 'current', SUM(principal) AS 'prin', 'current' + 'prin' AS 'total'
FROM dbase
</code>```

This doesn't work. I've also tried:

```<code>SELECT sum(currentbalance) AS 'current', sum(principal) AS 'prin', (SELECT 'current') + (SELECT 'prin') AS 'total'
FROM dbase
</code>```

@juergen-d @fqhv

Both answers worked perfectly. I thought that would be enough for me to understand how to add it to my current query. How can I implement this inside this query? I need to divide the "file_principal" by the "total_cash_cleared"? Thanks in Advance.

```<code>SELECT a.portfolio
       ,a.dateplaced
       ,(SELECT SUM(chargedoffprincipal) FROM Dbase WHERE portfolio = a.portfolio ) AS 'file_principal'
       ,SUM(IF(b.paymentstatus IN ('POSTED','PROCCESED'), paymentamount, 0)) AS 'total_cash_cleared'
       ,SUM(IF(b.paymentstatus = 'PENDING', paymentamount, 0)) AS 'total_cash_pending'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 1 MONTH),paymentamount, 0)) AS '30_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 2 MONTH),paymentamount, 0)) AS '60_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 3 MONTH),paymentamount, 0)) AS '90_days'
FROM dbase a
LEFT JOIN payments b
ON a.filenumber = b.filenumber
GROUP BY a.portfolio
ORDER BY STR_TO_DATE(a.dateplaced, '%m/%d/%Y') DESC
</code>```

I tried to add this in a comment but it was too long so I edited this post sorry.

答:
Thanks to my slack buddy here is the way to handle this. Makes all the sense now. </p>

```<code>SELECT
  portfolio,
  dateplaced,
  file_principal,
  total_cash_cleared,
  IF(total_cash_cleared <> 0, file_principal / total_cash_cleared, 0) AS div_result,
  total_cash_pending,
  30_days,
  60_days,
  90_days
FROM
  (SELECT a.portfolio
       ,a.dateplaced
         ,(SELECT SUM(chargedoffprincipal) FROM Dbase WHERE portfolio = a.portfolio ) AS 'file_principal'
         ,SUM(IF(b.paymentstatus IN ('POSTED','PROCCESED'), paymentamount, 0)) AS 'total_cash_cleared'
         ,SUM(IF(b.paymentstatus = 'PENDING', paymentamount, 0)) AS 'total_cash_pending'
         ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 1 MONTH),paymentamount, 0)) AS '30_days'
         ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 2 MONTH),paymentamount, 0)) AS '60_days'
         ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 3 MONTH),paymentamount, 0)) AS '90_days'
  FROM dbase a
  LEFT JOIN payments b
  ON a.filenumber = b.filenumber
  GROUP BY a.portfolio
) AS original_query
ORDER BY STR_TO_DATE(original_query.dateplaced, '%m/%d/%Y') DESC
</code>```

Body:
I want to do this:

SELECT SUM(currentbalance) AS 'current', SUM(principal) AS 'prin', 'current' + 'prin' AS 'total'
FROM dbase

This doesn't work. I've also tried:

SELECT sum(currentbalance) AS 'current', sum(principal) AS 'prin', (SELECT 'current') + (SELECT 'prin') AS 'total'
FROM dbase

@juergen-d @fqhv

Both answers worked perfectly. I thought that would be enough for me to understand how to add it to my current query. How can I implement this inside this query? I need to divide the "file_principal" by the "total_cash_cleared"? Thanks in Advance.

SELECT a.portfolio
       ,a.dateplaced
       ,(SELECT SUM(chargedoffprincipal) FROM Dbase WHERE portfolio = a.portfolio ) AS 'file_principal'
       ,SUM(IF(b.paymentstatus IN ('POSTED','PROCCESED'), paymentamount, 0)) AS 'total_cash_cleared'
       ,SUM(IF(b.paymentstatus = 'PENDING', paymentamount, 0)) AS 'total_cash_pending'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 1 MONTH),paymentamount, 0)) AS '30_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 2 MONTH),paymentamount, 0)) AS '60_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 3 MONTH),paymentamount, 0)) AS '90_days'
FROM dbase a
LEFT JOIN payments b
ON a.filenumber = b.filenumber
GROUP BY a.portfolio
ORDER BY STR_TO_DATE(a.dateplaced, '%m/%d/%Y') DESC

I tried to add this in a comment but it was too long so I edited this post sorry.

Body:
Thanks to my slack buddy here is the way to handle this. Makes all the sense now.

SELECT
  portfolio,
  dateplaced,
  file_principal,
  total_cash_cleared,
  IF(total_cash_cleared <> 0, file_principal / total_cash_cleared, 0) AS div_result,
  total_cash_pending,
  30_days,
  60_days,
  90_days
FROM
  (SELECT a.portfolio
       ,a.dateplaced
         ,(SELECT SUM(chargedoffprincipal) FROM Dbase WHERE portfolio = a.portfolio ) AS 'file_principal'
         ,SUM(IF(b.paymentstatus IN ('POSTED','PROCCESED'), paymentamount, 0)) AS 'total_cash_cleared'
         ,SUM(IF(b.paymentstatus = 'PENDING', paymentamount, 0)) AS 'total_cash_pending'
         ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 1 MONTH),paymentamount, 0)) AS '30_days'
         ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 2 MONTH),paymentamount, 0)) AS '60_days'
         ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 3 MONTH),paymentamount, 0)) AS '90_days'
  FROM dbase a
  LEFT JOIN payments b
  ON a.filenumber = b.filenumber
  GROUP BY a.portfolio
) AS original_query
ORDER BY STR_TO_DATE(original_query.dateplaced, '%m/%d/%Y') DESC


问:
Pass values from Hidden field to ActionLink then to Controller
I'm trying to dynamically set the StudentIds by letting the user select check boxes for the reports they want. When they click the ActionLink, I use jQuery to set the values of the ids in a hidden field.   I need the Action Link to read the ids from hidden field.

The values are getting set in the hidden field, but they are not being passed to the controller from the actionLink.

I need to pass the ReportIds to the controller.

```<code>        @Html.ActionLink("PrintMed", "GetMedEdVerificationReport", "Student", new { studentIdList = Model.ReportIds }, new { @class = "button print_selected print_selectedMedEd disabled" })

        @Html.HiddenFor(model => model.ReportIds)
</code>```

javascript

```<code>$('.print_selectedMedEd').bind('click', function () {
    var ids = getPrintIds();
    if (ids.length == 0) {
        return false;
    }

    $('#ReportIds').val(ids.toString());

    return true;
});
</code>```

答:
```<code>             @Html.HiddenFor(modelItem => item.OrderId)
            <td>

                <input type="button" value="Pickup" onclick="location.href='@Url.Action("Edit", "Assignment", new { ID = item.OrderId })'" />
</code>```

Body:
I'm trying to dynamically set the StudentIds by letting the user select check boxes for the reports they want. When they click the ActionLink, I use jQuery to set the values of the ids in a hidden field.   I need the Action Link to read the ids from hidden field.

The values are getting set in the hidden field, but they are not being passed to the controller from the actionLink.

I need to pass the ReportIds to the controller.

        @Html.ActionLink("PrintMed", "GetMedEdVerificationReport", "Student", new { studentIdList = Model.ReportIds }, new { @class = "button print_selected print_selectedMedEd disabled" })

        @Html.HiddenFor(model => model.ReportIds)

javascript

$('.print_selectedMedEd').bind('click', function () {
    var ids = getPrintIds();
    if (ids.length == 0) {
        return false;
    }

    $('#ReportIds').val(ids.toString());

    return true;
});


问:
Excel Substitute a substring in cell (sheet A) by the corresponding string in "lookup" (sheet B)

How to do this in MS Excel 15.4

I want to process Column A to become Column B

```<code>Column A                  | Column B
----------------------------------------------------------------------
one, 1, two, 2, three, 3  | one apple, two bananas, three strawberries
one, 1, four, 4           | one apple, four oranges
.......................
... many other rows ...
.......................
two, 2, four, 4, three, 3 | two bananas, four oranges, three strawberries
</code>```

The Column A can have n matching substrings in the lookup sheet.

I have another sheet (lookup table) with what to substitute the text in Column A with

```<code>Match col | Replace col
----------------------------
one, 1    | one apple
two, 2    | two bananas
three, 3  | three strawberries
four, 4   | four oranges
... and many more ...
</code>```

I want to replace all the substrings found in Column A with the Replace col value of the lookup table

It looks like I may be able to combine VLOOKUP with SUBSTITUTE, but I am struggling with it

答:
To do it in indivdual cells;

```<code>=IFERROR(VLOOKUP(TRIM(SUBSTITUTE(MID(SUBSTITUTE($A1,",",REPT(" ",999)),(COLUMN(A:A)-1)*2*999+1,2*999),REPT(" ",999),",")),Sheet2!$A:$B,2,FALSE),"")
</code>```

If you have a subscription to Office 3651 excel you can use this array formula to put it all in one cell:

```<code>=TEXTJOIN(",",TRUE,IFERROR(LOOKUP(TRIM(SUBSTITUTE(MID(SUBSTITUTE($A1,",",REPT(" ",999)),(ROW(INDIRECT("1:" & INT((LEN($A1)-LEN(SUBSTITUTE($A1,",","")))/2)+1))-1)*2*999+1,2*999),REPT(" ",999),",")),Sheet2!A:A,Sheet2!B:B),""))
</code>```

Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.

On caveat is that the reference data must be sorted on the lookup column:

1 If you do not have Office 365 but want to use this formula you can place the code from my answer HERE that will mimic the TEXTJOIN() in a module attached to the worksheet.  Then use the formula as described above

Body:
How to do this in MS Excel 15.4

I want to process Column A to become Column B

Column A                  | Column B
----------------------------------------------------------------------
one, 1, two, 2, three, 3  | one apple, two bananas, three strawberries
one, 1, four, 4           | one apple, four oranges
.......................
... many other rows ...
.......................
two, 2, four, 4, three, 3 | two bananas, four oranges, three strawberries

The Column A can have n matching substrings in the lookup sheet.

I have another sheet (lookup table) with what to substitute the text in Column A with

Match col | Replace col
----------------------------
one, 1    | one apple
two, 2    | two bananas
three, 3  | three strawberries
four, 4   | four oranges
... and many more ...

I want to replace all the substrings found in Column A with the Replace col value of the lookup table

It looks like I may be able to combine VLOOKUP with SUBSTITUTE, but I am struggling with it

Body:
To do it in indivdual cells;

=IFERROR(VLOOKUP(TRIM(SUBSTITUTE(MID(SUBSTITUTE($A1,",",REPT(" ",999)),(COLUMN(A:A)-1)*2*999+1,2*999),REPT(" ",999),",")),Sheet2!$A:$B,2,FALSE),"")

If you have a subscription to Office 3651 excel you can use this array formula to put it all in one cell:

=TEXTJOIN(",",TRUE,IFERROR(LOOKUP(TRIM(SUBSTITUTE(MID(SUBSTITUTE($A1,",",REPT(" ",999)),(ROW(INDIRECT("1:" & INT((LEN($A1)-LEN(SUBSTITUTE($A1,",","")))/2)+1))-1)*2*999+1,2*999),REPT(" ",999),",")),Sheet2!A:A,Sheet2!B:B),""))

Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done correctly then Excel will put {} around the formula.

On caveat is that the reference data must be sorted on the lookup column:

1 If you do not have Office 365 but want to use this formula you can place the code from my answer HERE that will mimic the TEXTJOIN() in a module attached to the worksheet.  Then use the formula as described above


问:
How to fix Application Loader Error: Invalid Bundle. The bundle ... contains disallowed file 'Frameworks'
I have a Swift project with three Swift custom frameworks. The App builds and runs successfully but when I try to upload to iTunes Connect using Application Loader I get the following error for all three frameworks:

ERROR ITMS-90206: "Invalid Bundle. The bundle at 'XXX.app/Frameworks/YYY.framework' contains disallowed file 'Frameworks'."

As discussed in this SO answer I have set the 'Embedded Content Contains Swift Code' to NO in the frameworks and YES in the App, but this error persists.

The three Frameworks are all my own (I am seriously considering reworking the project to avoid Frameworks altogether but that is a chore I would like to avoid right now).

I am not using cocoapods.

Any ideas on how to resolve this error?

答:
In (SE-0133) of the Xcode 8.3 Release note, there's a description about EMBEDDED_CONTENT_CONTAINS_SWIFT setting:

The new build setting ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES replaces the EMBEDDED_CONTENT_CONTAINS_SWIFT setting, which has been deprecated. This new setting indicates that Xcode should always embed Swift standard libraries in a target for which it has been set, whether or not the target contains Swift code. A typical scenario for using this setting is when a target directly uses or embeds another product that contains Swift code. (26158130)

which means ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES has replaced EMBEDDED_CONTENT_CONTAINS_SWIFT, thus you need to change the former one(ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES) to NO in the extension target.


问:
Which module is used for the effect ...?
At http://acquiaprosper.fusiondrupalthemes.com/, their is a sliding product show case at the top banner:

Which modules are required? Thanks!

答:
This video podcast from mustardseed details how to set-up a view like that using Views Slideshow module.

http://mustardseedmedia.com/podcast/episode42

drupal.org/project/views_slideshow


问:
evaluate mixed type with eval()
I have two date/time variables that contains list of the date/time values and another variable containing the list of operator to operate over the date/time variables. The format can be expressed as follows:

```<code>column1 = np.array([date1, date2,.......,dateN])
column2 = np.array([date1, date2,.......,dateN])
</code>```

Both of the above variables of type Date/Time. Then I have the following variable operator that has the same length of column1 and column2:

```<code>operator = np.array(['>=','<=','==','=!',......])
</code>```

I am getting "Invalid Token" with the following operation:

```<code>np.array([eval('{}{}{}'.format(v1,op,v2)) for v1,op,v2 in zip(column1,operator,column2)])
</code>```

Any hint to get around this issue ?

-------------------EDIT----------------------

With some sample data and without eval I get the following output:

```<code> np.array(['{} {} {}'.format(v1,op,v2) for v1,op,v2 in zip(datelist1,operator,datelist2)])

array(['2017-03-30 10:30:22.928000 <= 2012-05-23 00:00:00',
   '2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000'],
  dtype='|S49')
</code>```

Once I bring in eval(), I get the following error:

```<code>eval('2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000')
File "<string>", line 1
2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000
            ^
SyntaxError: invalid syntax
</code>```

----------------------EDIT & CORRECTIONS ----------------------------

Date/Time variables that I mentioned before are basically of type numpy datetime64 type and I am now getting the following issue while trying two date comparions with eval:

```<code>np.array([(repr(d1)+op+repr(d2)) for d1,op,d2 in zip(${Column Name1},${Operator},${Column Name2})])
</code>```

The above snippet is tried over a table with three columns where ${Column Name1} and ${Column Name2} is of numpy.datetime64 type and ${Operator} is of string type. The result is as follows for one of the rows:

```<code>numpy.datetime64('2014-08-13T02:00:00.000000+0200')>=numpy.datetime64('2014-08-13T02:00:00.000000+0200')
</code>```

Now I want to evaluate the above expression with function eval as follows:

```<code>np.array([eval(repr(d1)+op+repr(d2)) for d1,op,d2 in zip(${Column Name1},${Operator},${Column Name2})])
</code>```

Eventually I get the following error:

```<code>NameError:name 'numpy' is not defined
</code>```

I can assume the problem. The Open Source Tool that I am using is importing numpy as np whereas repr() returning numpy that it does not recognize. If this is the problem , how to fix this issue ?

答:
datetime objects can be compared:

```<code>In [506]: datetime.datetime.today()
Out[506]: datetime.datetime(2017, 3, 30, 10, 43, 18, 363747)
In [507]: t1=datetime.datetime.today()
In [508]: t2=datetime.datetime.today()
In [509]: t1 < t2
Out[509]: True
In [510]: t1 == t2
Out[510]: False
</code>```

Numpy's own version of datetime objects can also be compared

```<code>In [516]: nt1 = np.datetime64('2017-03-30 10:30:22.928000')
In [517]: nt2 = np.datetime64('2017-03-30 10:31:14.477000')
In [518]: nt1 < nt2
Out[518]: True
In [519]: nt3 = np.datetime64('2012-05-23 00:00:00')
In [520]: [nt1 <= nt2, nt2==nt3]
Out[520]: [True, False]
</code>```

Using the repr string version of a datetime object works:

```<code>In [524]: repr(t1)+'<'+repr(t2)
Out[524]: 'datetime.datetime(2017, 3, 30, 10, 47, 29, 69324)<datetime.datetime(2017, 3, 30, 10, 47, 33, 669494)'
In [525]: eval(repr(t1)+'<'+repr(t2))
Out[525]: True
</code>```

Not that I recommend that sort of construction.  I like the dictionary mapping to an operator better.

Title: evaluate mixed type with eval()

Body:
I have two date/time variables that contains list of the date/time values and another variable containing the list of operator to operate over the date/time variables. The format can be expressed as follows:

column1 = np.array([date1, date2,.......,dateN])
column2 = np.array([date1, date2,.......,dateN])

Both of the above variables of type Date/Time. Then I have the following variable operator that has the same length of column1 and column2:

operator = np.array(['>=','<=','==','=!',......])

I am getting "Invalid Token" with the following operation:

np.array([eval('{}{}{}'.format(v1,op,v2)) for v1,op,v2 in zip(column1,operator,column2)])

Any hint to get around this issue ?

-------------------EDIT----------------------

With some sample data and without eval I get the following output:

 np.array(['{} {} {}'.format(v1,op,v2) for v1,op,v2 in zip(datelist1,operator,datelist2)])

array(['2017-03-30 10:30:22.928000 <= 2012-05-23 00:00:00',
   '2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000'],
  dtype='|S49')

Once I bring in eval(), I get the following error:

eval('2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000')
File "<string>", line 1
2011-01-07 00:00:00 == 2017-03-30 10:31:14.477000
            ^
SyntaxError: invalid syntax

----------------------EDIT & CORRECTIONS ----------------------------

Date/Time variables that I mentioned before are basically of type numpy datetime64 type and I am now getting the following issue while trying two date comparions with eval:

np.array([(repr(d1)+op+repr(d2)) for d1,op,d2 in zip(${Column Name1},${Operator},${Column Name2})])

The above snippet is tried over a table with three columns where ${Column Name1} and ${Column Name2} is of numpy.datetime64 type and ${Operator} is of string type. The result is as follows for one of the rows:

numpy.datetime64('2014-08-13T02:00:00.000000+0200')>=numpy.datetime64('2014-08-13T02:00:00.000000+0200')

Now I want to evaluate the above expression with function eval as follows:

np.array([eval(repr(d1)+op+repr(d2)) for d1,op,d2 in zip(${Column Name1},${Operator},${Column Name2})])

Eventually I get the following error:

NameError:name 'numpy' is not defined

I can assume the problem. The Open Source Tool that I am using is importing numpy as np whereas repr() returning numpy that it does not recognize. If this is the problem , how to fix this issue ?

Body:
datetime objects can be compared:

In [506]: datetime.datetime.today()
Out[506]: datetime.datetime(2017, 3, 30, 10, 43, 18, 363747)
In [507]: t1=datetime.datetime.today()
In [508]: t2=datetime.datetime.today()
In [509]: t1 < t2
Out[509]: True
In [510]: t1 == t2
Out[510]: False

Numpy's own version of datetime objects can also be compared

In [516]: nt1 = np.datetime64('2017-03-30 10:30:22.928000')
In [517]: nt2 = np.datetime64('2017-03-30 10:31:14.477000')
In [518]: nt1 < nt2
Out[518]: True
In [519]: nt3 = np.datetime64('2012-05-23 00:00:00')
In [520]: [nt1 <= nt2, nt2==nt3]
Out[520]: [True, False]

Using the repr string version of a datetime object works:

In [524]: repr(t1)+'<'+repr(t2)
Out[524]: 'datetime.datetime(2017, 3, 30, 10, 47, 29, 69324)<datetime.datetime(2017, 3, 30, 10, 47, 33, 669494)'
In [525]: eval(repr(t1)+'<'+repr(t2))
Out[525]: True

Not that I recommend that sort of construction.  I like the dictionary mapping to an operator better.


问:
Azure Functions with PHP
I'm trying out Azure Functions using PHP.
Getting the request information is not working for me.

I've not been able to find any documentation at all with the information of how to use Azure Functions with PHP code.

According to the only couple of examples, it seems that in order to retrieve the input information you need to first get the content of the req variable (or whatever name you assign in the function configuration).
That has the path of the file containing the request information (in theory).

$input_path = getenv('req');

So far, if I check the content of it, I get something like this:

D:\local\Temp\Functions\Binding\e2b6e195-02f7-481b-a279-eef6f82bc7b4\req

If I check if the file exists it says true, but the file size is 0.

Do anyone knows what to do here? Anyone with an example? Does anyone know where the documentation is?

Thanks

答:
Ok, unfortunately there's pretty limited documentation out there for php as you have discovered.

At present, looking at the code might be the best doc. Here is the InitializeHttpRequestEnvironmentVariables function that adds request metadata to the environment for the script languages (node, powershell, php, python).

Important environment variables are:

REQ_ORIGINAL_URL

REQ_METHOD

REQ_QUERY

REQ_QUERY_<queryname>

REQ_HEADERS_<headername>

REQ_PARAMS_<paramname>

I'm assuming you've made a GET request, in which case there is no content (req is an empty file), but you will see that these other environment variables contain request data. If you were to make a POST request with a body then req would have data.

Title: Azure Functions with PHP


问:
Where can I share my benchmark results for elasticsearch php vendors
I've benchmarked several elasticsearch php vendors, and I would like to share my experience!

I would write a simple topic on some blog (or something else) related to elasticsearch or php.

Could someone please advise me where I can post such info?

答:
Create a repository on Github and push your test setup and a php shell to run the benchmark. Don't forget to add a meaningful readm.md.

Oh and, give me the URL of the repo, I would like to run them as well. :) I'm pretty sure other people have an interest in this as well.


问:
How do I identify language of a text document in Java?
Is there an existing Java library that could tell me whether a String contains English language text or not (e.g. I need to be able to distinguish French or Italian text -- the function needs to return false for French and Italian, and true for English)?</p>

答: You could try comparing each word to an English, French, or Italian dictionary.  Keep in mind though some words may appear in multiple dictionaries.</p>

OwnerDisplayName: anonymous coward

LastEditorDisplayName: Neil Coffey

OwnerDisplayName: Ying


问:
Load profile image from Facebook with Actionscript 3
I'm trying to load profile images (friend images) from Facebook with AS3 but I seem to be running into a security issue.

I'm currently using the "official" Adobe Facebook API for Actionscript 3 which works fine. However, I seem to be having trouble loading profile images when running my application in a browser. The images load fine when running in the Flash IDE.

The images are being loaded from https://graph.facebook.com and there seems to be a crossdomain.xml policy on that domain:

```<code><!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="*" secure="false" />
 <site-control permitted-cross-domain-policies="master-only" />
</cross-domain-policy>
</code>```

In other sources I found that adding a ContextLoader to my Loader object when loading the image should solve the problem but this doesn't seem to be the case either:

```<code>loader = new Loader();
// add some listeners here...
loader.load( new URLRequest( "imageurl" ), new LoaderContext(true) );
</code>```

I'm not quite sure how to proceed at the moment. I was hoping that the Adobe Facebook API would provide assistance in this but I can't seem to find anything that solves this issue.

Any help greatly appreciated.

UPDATE:

I just noticed that when I visit one of the images in a browser that I'm actually redirected to Facebook's CDN where the actual image is stored. When I hard-code the image url with the redirected URL I can load the image in the browser. It seems that this is not a security issue after all but a redirection issue.

If this is a redirection issue then the question would become; How can I have Flash Player load an image from a redirected URL?

UPDATE 2:

It seems that the URLRequest class has a followRedirects property which is only available in AIR.

UPDATE 3:

I'm currently using a PHP script to get me the redirected URL as a work around but this of course is far from ideal and potentially a big strain on my server.

答:
I had the same problem and it looks like you have to manually load the crossdomain file of the domain you are redirected to in actionscript. For now, it looks like all facebook profile images are finally loaded from the domain http://profile.ak.fbcdn.net/.

I just added this line before loading the images:

```<code>Security.loadPolicyFile("http://profile.ak.fbcdn.net/crossdomain.xml");
</code>```

This should allow for loading the redirected images, as long as the redirect domain does not change. ;)

Body:
I'm trying to load profile images (friend images) from Facebook with AS3 but I seem to be running into a security issue.

I'm currently using the "official" Adobe Facebook API for Actionscript 3 which works fine. However, I seem to be having trouble loading profile images when running my application in a browser. The images load fine when running in the Flash IDE.

The images are being loaded from https://graph.facebook.com and there seems to be a crossdomain.xml policy on that domain:

<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="*" secure="false" />
 <site-control permitted-cross-domain-policies="master-only" />
</cross-domain-policy>

In other sources I found that adding a ContextLoader to my Loader object when loading the image should solve the problem but this doesn't seem to be the case either:

loader = new Loader();
// add some listeners here...
loader.load( new URLRequest( "imageurl" ), new LoaderContext(true) );

I'm not quite sure how to proceed at the moment. I was hoping that the Adobe Facebook API would provide assistance in this but I can't seem to find anything that solves this issue.

Any help greatly appreciated.

UPDATE:

I just noticed that when I visit one of the images in a browser that I'm actually redirected to Facebook's CDN where the actual image is stored. When I hard-code the image url with the redirected URL I can load the image in the browser. It seems that this is not a security issue after all but a redirection issue.

If this is a redirection issue then the question would become; How can I have Flash Player load an image from a redirected URL?

UPDATE 2:

It seems that the URLRequest class has a followRedirects property which is only available in AIR.

UPDATE 3:

I'm currently using a PHP script to get me the redirected URL as a work around but this of course is far from ideal and potentially a big strain on my server.

Body:
I had the same problem and it looks like you have to manually load the crossdomain file of the domain you are redirected to in actionscript. For now, it looks like all facebook profile images are finally loaded from the domain http://profile.ak.fbcdn.net/.

I just added this line before loading the images:

Security.loadPolicyFile("http://profile.ak.fbcdn.net/crossdomain.xml");

This should allow for loading the redirected images, as long as the redirect domain does not change. ;)


问:
Parsing non-curly braced unicode emoji in Ruby
I'm receiving some text from an API that I don't have control over. When I receive emoji they are not encoded correctly for Ruby. Here's an example of what I'm receiving:

encoded: "\u1F44C"

decoded: "ὄC"

Ruby doesn't handle unicode with more than 4 hex characters unless you use curly braces. So "\u{1F44C}" would correctly be decoded as .

How can I convert the output of the API into a format that Ruby can correctly decode?

答:
What you're dealing with here is a broken API. This isn't a Ruby problem, it's a JSON encoder problem. Per the JSON spec:

If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. The hexadecimal letters A though F can be upper or lower case.  So, for example, a string containing only a single reverse solidus character may be represented as "\u005C".

...

To escape an extended character that is not in the Basic Multilingual Plane, the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair.  So, for example, a string containing only the G clef character (U+1D11E) may be represented as "\uD834\uDD1E".

So the correct encoding of  would be \uD83D\uDC4C. Any compliant JSON parser would produce the same output you're seeing. You should report a bug to the API vendor—you're almost certainly not their only customer experiencing this problem.

If you can't get the API vendor to fix their API, your only recourse short of implementing your own JSON parser (or ditching the vendor) is to attempt to fix the JSON response using regular expressions. Something like this works, but will be susceptible to false positives, meaning some valid JSON would get mangled:

```<code>require "json"

def mangle_json(str)
  str.gsub(/\\u([0-9a-f]{5,6})/i) do
    begin
      $1.to_i(16).chr(Encoding::UTF_8)
    rescue RangeError
      $&
    end
  end
end

bad_json = '{"text":"OK\u1F44C let me see."}'

puts JSON.parse(bad_json)["text"]
# => OKὄC let me see.

puts JSON.parse(mangle_json(bad_json))["text"]
# => OK let me see.
</code>```

See it on repl.it: https://repl.it/GnFp/1

Body:
What you're dealing with here is a broken API. This isn't a Ruby problem, it's a JSON encoder problem. Per the JSON spec:

If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. The hexadecimal letters A though F can be upper or lower case.  So, for example, a string containing only a single reverse solidus character may be represented as "\u005C".

...

To escape an extended character that is not in the Basic Multilingual Plane, the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair.  So, for example, a string containing only the G clef character (U+1D11E) may be represented as "\uD834\uDD1E".

So the correct encoding of  would be \uD83D\uDC4C. Any compliant JSON parser would produce the same output you're seeing. You should report a bug to the API vendor—you're almost certainly not their only customer experiencing this problem.

If you can't get the API vendor to fix their API, your only recourse short of implementing your own JSON parser (or ditching the vendor) is to attempt to fix the JSON response using regular expressions. Something like this works, but will be susceptible to false positives, meaning some valid JSON would get mangled:

require "json"

def mangle_json(str)
  str.gsub(/\\u([0-9a-f]{5,6})/i) do
    begin
      $1.to_i(16).chr(Encoding::UTF_8)
    rescue RangeError
      $&
    end
  end
end

bad_json = '{"text":"OK\u1F44C let me see."}'

puts JSON.parse(bad_json)["text"]
# => OKὄC let me see.

puts JSON.parse(mangle_json(bad_json))["text"]
# => OK let me see.

See it on repl.it: https://repl.it/GnFp/1


问:
How to create dynamic buttons in android?
I'm new to android, Can anyone tell me how to create a button like in the attached image where I can click on the star and it gets added to my favorites list in another fragment? ?

答:
1) Create a vector drawable under drawables.

/res/drawable/ic_star.xml

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#F00000"
        android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z"/>
</vector>
</code>```

2) Add ImageButton

Star ImageButton

```<code><ImageButton
        android:background="@android:color/transparent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_star"/>
</code>```

Body:
1) Create a vector drawable under drawables.

/res/drawable/ic_star.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#F00000"
        android:pathData="M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z"/>
</vector>

2) Add ImageButton

Star ImageButton

<ImageButton
        android:background="@android:color/transparent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_star"/>


问:
How to add multiple item to a ListView with each Button click
I found much on google but not able to get the answer.
I got How to add an item to a ListView with each Button click.
here we are learning to add single item..
thanks in advance</p>

答:
So if you want to do this statically

```<code>ListView<String> list = new ListView<String>();
    ObservableList<String> items = FXCollections.observableArrayList(
            "something1", "something2", "something3");
    list.setItems(items);
</code>```

But if you want to do this dinamically  you can use this code:

```<code>ListView<String> list = new ListView<String>();
    ObservableList<String> items = FXCollections.observableArrayList(
            "something1", "something2", "something3");
    list.setItems(items);

 list.setEditable(true);

    Button btn = new Button();
    btn.setText("Add String");
    btn.setOnAction((ActionEvent event) -> {
        list.getItems().add(i - 1, "something" + i);
        list.edit(i - 2);
        i++;
    });
</code>```

Body:
So if you want to do this statically

ListView<String> list = new ListView<String>();
    ObservableList<String> items = FXCollections.observableArrayList(
            "something1", "something2", "something3");
    list.setItems(items);

But if you want to do this dinamically  you can use this code:

ListView<String> list = new ListView<String>();
    ObservableList<String> items = FXCollections.observableArrayList(
            "something1", "something2", "something3");
    list.setItems(items);

 list.setEditable(true);

    Button btn = new Button();
    btn.setText("Add String");
    btn.setOnAction((ActionEvent event) -> {
        list.getItems().add(i - 1, "something" + i);
        list.edit(i - 2);
        i++;
    });