问:
AJAX Form Submitting (Only on Firefox)
I am running an AJAX contact form on my website (www.chrisanstey.co.uk), which is not submitting only in Firefox, but works absolute fine in every other browser. The form is uses the following PHP file:

```<code><?php

$to = "me@somewhere.com"; //This is the email address you want to send the email to

if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}

/* Now lets trim up the input before sending it */

$name = trim($_GET['name']); //The senders name
$email = trim($_GET['email']); //The senders email address
$subject = "A message sent from " . $name . " on Chris Anstey's portfolio"; //The senders subject
$message = trim($_GET['msg']); //The senders message

mail($to,$subject,$message,"From: ".$email.""); //a very simple send

echo 'contactarea|<p>Thank you '.$name.' for your message, I will reply to you as soon as I can.</p>'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>
</code>```

and also the following javascript file:

```<code>function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

var http = createRequestObject();

function sendemail() {
 var msg = document.contactform.msg.value;
 var name = document.contactform.name.value;
 var email = document.contactform.email.value;
 document.contactform.send.disabled=true;
 document.contactform.send.value='Sending....';

    http.open('get', 'contact.php?msg='+msg+'&name='+name+'&email='+email+'&action=send');
    http.onreadystatechange = handleResponse;
    http.send(null);
}

function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();

        if(response.indexOf('|' != -1)) {
            update = response.split('|');
            document.getElementById(update[0]).innerHTML = update[1];

        }
    }
}
</code>```

The form is within a Wordpress page, being called on the template by the following HTML:

```<code><div id="contactarea">
<form name="contactform" id="contactform">
<p>Full Name:<br />
    <span class="wpcf7-form-control-wrap your-name"><input type="text" name="name"></span></p>
<p>Email:<br />
    <span class="wpcf7-form-control-wrap your-email"><input type="text" name="email"></span></p>
<p>Message:<br />
    <span class="wpcf7-form-control-wrap your-message"><textarea name="msg" rows="6" id="textarea"></textarea></span></p>
<p><input type="submit" value="Send Email" name="send" id="submitbutton" onClick="sendemail();"></p>
</form>
</div>
</code>```

If anyone has any idea or has encountered similar problems with AJAX not working within Firefox, please could you reply. Any help would be much appreciated!

答: Well, your query could be cached, for one.  Is it calling the php, or not?  That code works for me in firefox, but after it works once, it should cache it, so it won't call it again.</p>

Title: AJAX Form Submitting (Only on Firefox)

Body:
I am running an AJAX contact form on my website (www.chrisanstey.co.uk), which is not submitting only in Firefox, but works absolute fine in every other browser. The form is uses the following PHP file:

<?php

$to = "me@somewhere.com"; //This is the email address you want to send the email to

if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}

/* Now lets trim up the input before sending it */

$name = trim($_GET['name']); //The senders name
$email = trim($_GET['email']); //The senders email address
$subject = "A message sent from " . $name . " on Chris Anstey's portfolio"; //The senders subject
$message = trim($_GET['msg']); //The senders message

mail($to,$subject,$message,"From: ".$email.""); //a very simple send

echo 'contactarea|
Thank you '.$name.' for your message, I will reply to you as soon as I can.
'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>

and also the following javascript file:

function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

var http = createRequestObject();

function sendemail() {
 var msg = document.contactform.msg.value;
 var name = document.contactform.name.value;
 var email = document.contactform.email.value;
 document.contactform.send.disabled=true;
 document.contactform.send.value='Sending....';

    http.open('get', 'contact.php?msg='+msg+'&name='+name+'&email='+email+'&action=send');
    http.onreadystatechange = handleResponse;
    http.send(null);
}

function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();

        if(response.indexOf('|' != -1)) {
            update = response.split('|');
            document.getElementById(update[0]).innerHTML = update[1];

        }
    }
}

The form is within a Wordpress page, being called on the template by the following HTML:

<form name="contactform" id="contactform">

Full Name:

    <input type="text" name="name">

Email:

    <input type="text" name="email">

Message:

    <textarea name="msg" rows="6" id="textarea"></textarea>

<input type="submit" value="Send Email" name="send" id="submitbutton" onClick="sendemail();">

</form>

If anyone has any idea or has encountered similar problems with AJAX not working within Firefox, please could you reply. Any help would be much appreciated!


来源: stackexchange

问:
Required capabilities when running BrowserStack Automate with a mobile device
Description

The BrowserStack documentation lists all capabilities you can set for their Automate product but does not describe which ones MUST be present in order to test on, for example a 'Google Nexus 5'.

Their code generator suggests this:

```<code>{
   "browserName" : "android",
   "platform" : "ANDROID",
   "device" : "Google Nexus 5"
}
</code>```

But I know from experience that this set of capabilities also works:

```<code>{"os":"android", "device": "Google Nexus 5"}
</code>```

Because of this I'm asking myself:

Question

Does {"device": "Google Nexus 5"} also work?

And if not, what is the minimum and correct set of capabilities when using BrowserStack Automate with a specific mobile device?

答:
Yes, when you request a webdriver session with only the capability 'device' set, BrowserStack will successfully create a session on that device with the default browser of the device.

Source: E-Mail conversation with a kind BrowserStack technical Support employee.

ContentLicense: CC BY-SA 3.0

Body:
Description

The BrowserStack documentation lists all capabilities you can set for their Automate product but does not describe which ones MUST be present in order to test on, for example a 'Google Nexus 5'.

Their code generator suggests this:

{
   "browserName" : "android",
   "platform" : "ANDROID",
   "device" : "Google Nexus 5"
}

But I know from experience that this set of capabilities also works:

{"os":"android", "device": "Google Nexus 5"}

Because of this I'm asking myself:

Question

Does {"device": "Google Nexus 5"} also work?

And if not, what is the minimum and correct set of capabilities when using BrowserStack Automate with a specific mobile device?


问:
My view is not being rendered (ASP. NET / Angular)
I have a controller that is sending an array with json objects.
Instead of showing me the view, only the contents of the array are shown in the browser.

thank you.

My controller:

```<code> public JsonResult IndexJson()
    {

        var equipas = db.Equipas.Select(t => new { Nome = t.Nome, Abreviatura = t.Abreviatura, Country = t.Country }).ToList();

        return Json(equipas, JsonRequestBehavior.AllowGet);
    }
</code>```

My view:

```<code>@{
ViewBag.Title = "getAll";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<div ng-app="ruyApp" ng-controller="equipasCtrl">

<table class="table">
<tr>
    <th>
        Nome
    </th>
    <th>
        País
    </th>
    <th>
       Abreviatura
    </th>

</tr>

<tr ng-repeat="x in myData">
    <td>
        {{x.Nome}}
    </td>
    <td>
        {{x.Country}}
    </td>
    <td>
        {{x.Abreviatura}}
    </td>

</tr>

</table>

</div>

<script src="~/Scripts/AngularScripts.js"></script>
</code>```

My script:

```<code>var app = angular.module('ruyApp', []);

app.controller('equipasCtrl', function ($scope, $http) {
$http.get('/Equipas/IndexJson').then(function (response) {
    $scope.myData = response.data;
    $scope.statustext = response.statusText;
    $scope.statuscode = response.status;

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

Browser output:

```<code>[{"Nome":"Real Madrid","Abreviatura":"RM","Country":"Espanha"},{"Nome":"Benfica","Abreviatura":"BEN","Country":"Portugal"},{"Nome":"FC Porto","Abreviatura":"FCP","Country":"Portugal"},{"Nome":"Barcelona","Abreviatura":"BAR","Country":"Espanha"},{"Nome":"PSG","Abreviatura":"PSG","Country":"França"},{"Nome":"Charlotte Hornets","Abreviatura":"CHA","Country":"EUA"},{"Nome":"Boston Celtics","Abreviatura":"BOS","Country":"EUA"},{"Nome":"Indiana Pacers","Abreviatura":"IND","Country":"EUA"}]
</code>```

答: I think that when you return other result than ViewResult, the ViewEngine is not triggered and no view is returned. I would return the json as a model to the view: ex. return this.View(jsonEquipas) Or pass the equipas as a property to the view model you pass to the view.</p>

Body:
I have a controller that is sending an array with json objects.
Instead of showing me the view, only the contents of the array are shown in the browser.

thank you.

My controller:

 public JsonResult IndexJson()
    {

        var equipas = db.Equipas.Select(t => new { Nome = t.Nome, Abreviatura = t.Abreviatura, Country = t.Country }).ToList();

        return Json(equipas, JsonRequestBehavior.AllowGet);
    }

My view:

@{
ViewBag.Title = "getAll";
Layout = "~/Views/Shared/_Layout.cshtml";
}

        Nome

        País

       Abreviatura

        {{x.Nome}}

        {{x.Country}}

        {{x.Abreviatura}}

My script:

var app = angular.module('ruyApp', []);

app.controller('equipasCtrl', function ($scope, $http) {
$http.get('/Equipas/IndexJson').then(function (response) {
    $scope.myData = response.data;
    $scope.statustext = response.statusText;
    $scope.statuscode = response.status;

});
});

Browser output:

[{"Nome":"Real Madrid","Abreviatura":"RM","Country":"Espanha"},{"Nome":"Benfica","Abreviatura":"BEN","Country":"Portugal"},{"Nome":"FC Porto","Abreviatura":"FCP","Country":"Portugal"},{"Nome":"Barcelona","Abreviatura":"BAR","Country":"Espanha"},{"Nome":"PSG","Abreviatura":"PSG","Country":"França"},{"Nome":"Charlotte Hornets","Abreviatura":"CHA","Country":"EUA"},{"Nome":"Boston Celtics","Abreviatura":"BOS","Country":"EUA"},{"Nome":"Indiana Pacers","Abreviatura":"IND","Country":"EUA"}]


问:
Cannot cons to a list in Haskell data structure
The code below has a data structure Bot which has a parameter values of type [Int]. The function giveValue retrieves the bot of a given index from a hashmap, adds a value to that bot's values parameter and returns the updated hashmap. However, it currently replaces the existing Int in values, rather than append to the array. Could someone explain to me why this is happening?</p>

```<code>import Data.List.Split
import Data.List
import Data.Map (Map)
import qualified Data.Map.Strict as Map

data Bot = Bot {values :: [Int], low :: Int, high :: Int}
instance Show (Bot) where
    show b = show (values b) ++ " " ++ show (low b) ++ " " ++ show (high b)

getBot :: Int -> Map Int (Bot)-> Bot
getBot i m
    | (length bots == 1) = bots !! 0
    | otherwise = Bot [] falseVal falseVal
    where
        falseVal = -1
        bots = [b | (i2, b) <- Map.toList m, i2==i]

giveValue :: Int -> Int -> Map Int (Bot) -> Map Int (Bot)
giveValue botInd val oldM = newM
    where
        bot = getBot val oldM
        newM = Map.insert botInd (Bot (val : values bot) (low bot) (high bot)) oldM

main = do
    let bot = Bot [17] 3 4
    let bots = Map.insert 0 bot (Map.empty)

    print $ giveValue 0 61 bots
    -- Prints fromList [(0, [12] -1 -1)]
</code>```

答:
I think you mean bot = getBot botInd oldM not bot = getBot val oldM.

The compiler could have caught this, except you're using Int as the type of both the value you want to put in and how you're looking up the bot.

Maybe if you pass in the whole Bot to giveValue instead, then you could be sure that you're giving the right value to the right bot?

You could also wrap the "bot id" in a newtype, like newtype BotId = BotId { unBotId :: Int }. getBot would take a BotId, and then ghc would've complained that you were passing in an integer instead of an id!

Also, consider using Maybe Int instead of Int for low and high. The fact that you're using a falseVal is a big red flag that you should be using Maybe instead.

Body:
The code below has a data structure Bot which has a parameter values of type [Int]. The function giveValue retrieves the bot of a given index from a hashmap, adds a value to that bot's values parameter and returns the updated hashmap. However, it currently replaces the existing Int in values, rather than append to the array. Could someone explain to me why this is happening?

import Data.List.Split
import Data.List
import Data.Map (Map)
import qualified Data.Map.Strict as Map

data Bot = Bot {values :: [Int], low :: Int, high :: Int}
instance Show (Bot) where
    show b = show (values b) ++ " " ++ show (low b) ++ " " ++ show (high b)

getBot :: Int -> Map Int (Bot)-> Bot
getBot i m
    | (length bots == 1) = bots !! 0
    | otherwise = Bot [] falseVal falseVal
    where
        falseVal = -1
        bots = [b | (i2, b) <- Map.toList m, i2==i]

giveValue :: Int -> Int -> Map Int (Bot) -> Map Int (Bot)
giveValue botInd val oldM = newM
    where
        bot = getBot val oldM
        newM = Map.insert botInd (Bot (val : values bot) (low bot) (high bot)) oldM

main = do
    let bot = Bot [17] 3 4
    let bots = Map.insert 0 bot (Map.empty)

    print $ giveValue 0 61 bots
    -- Prints fromList [(0, [12] -1 -1)]


问:
CTRL+C w/ Spring Boot & Gradle Kills Gradle Daemon
I use the Spring Boot Gradle plugin to start a Tomcat server & my app. I start the Tomcat server via gradle bootRun. I've also enabled the Gradle daemon, in hopes to make Gradle builds go faster.

However, enabling the daemon is for naught. Every time I stop the server via Ctrl + C, then start the server again with gradle bootRun, I encounter the message:

```<code>Starting a new Gradle Daemon for this build (subsequent builds will be faster).
</code>```

Ctrl + C not only stops the Tomcat server under the covers of Spring Boot, but also kills the Gradle daemon. Which defeats the purpose of Gradle's daemon mode.

Is there a better way I should be stopping the server, hopefully via command line interface in the same terminal for which I started tomcat with gradle bootRun, that keeps the Gradle daemon alive?

答:
I had the same problem. I started dropwizard application, and killing a daemon considerabely increased time to restart the application.

Easy Solution:
In the end I've simply searched for dropwizard process, and killed it in commandline (simple kill & ps aux & grep combination). This closes the app and fails the build, but preserves the daemon.

Body:
I use the Spring Boot Gradle plugin to start a Tomcat server & my app. I start the Tomcat server via gradle bootRun. I've also enabled the Gradle daemon, in hopes to make Gradle builds go faster.

However, enabling the daemon is for naught. Every time I stop the server via Ctrl + C, then start the server again with gradle bootRun, I encounter the message:

Starting a new Gradle Daemon for this build (subsequent builds will be faster).

Ctrl + C not only stops the Tomcat server under the covers of Spring Boot, but also kills the Gradle daemon. Which defeats the purpose of Gradle's daemon mode.

Is there a better way I should be stopping the server, hopefully via command line interface in the same terminal for which I started tomcat with gradle bootRun, that keeps the Gradle daemon alive?


问:
How to make an a tag border wrap around an image
I need the border to be applied to the a tag but when I do this the border doesn't wrap around the image how can I make this happen?

```<code><div>
  <a href="#">
    <img src="https://cdn.pixabay.com/photo/2015/04/23/17/41/javascript-736400_960_720.png">
  </a>
</div>
</code>```

css:

```<code>a{
  border: 5px solid blue;
}
</code>```

https://jsfiddle.net/b7qdcub1/

答:
You have to apply display: block to your a tag so that it behaves as a block level element. Also give it a fixed width and a height to encompass the image inside it.

Refer code:

a {
  border: 5px solid blue;
  display: block;
  width: 720px;
  height: 720px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

    <img src="https://cdn.pixabay.com/photo/2015/04/23/17/41/javascript-736400_960_720.png">

</div></code>```

Body:
I need the border to be applied to the a tag but when I do this the border doesn't wrap around the image how can I make this happen?

css:

a{
  border: 5px solid blue;
}

https://jsfiddle.net/b7qdcub1/

Body:
You have to apply display: block to your a tag so that it behaves as a block level element. Also give it a fixed width and a height to encompass the image inside it.

Refer code:

a {
  border: 5px solid blue;
  display: block;
  width: 720px;
  height: 720px;
}

<div>
  <a href="#">
    <img src="https://cdn.pixabay.com/photo/2015/04/23/17/41/javascript-736400_960_720.png">
  </a>
</div>


问:
jQuery - slideUp / slideDown not working on ul?
I have the following code in my masterpage:

jQuery:

```<code>$(window).load(function () {
    $("li.submenu").hover(
        function () { $(this).find("ul").slideDown("slow"); },
        function () { $(this).find("ul").slideUp("slow"); }
    );
});
</code>```

HTML:

```<code><ul class="menu" runat="server" id="Menu">
    <li class="first" runat="server"><asp:HyperLink runat="server" NavigateUrl="/index.aspx">Home</asp:HyperLink></li>
    <li class="submenu" runat="server">
        <asp:HyperLink runat="server" NavigateUrl="/categories/index.aspx">Products</asp:HyperLink>
        <ul runat="server">
            <li runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category1.aspx">Dogs</asp:HyperLink></li>
            <li runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category2.aspx">Category 2</asp:HyperLink></li>
            <li runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category3.aspx">Category 3</asp:HyperLink></li>
            <li runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category4.aspx">Category 4</asp:HyperLink></li>
            <li runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category5.aspx">Category 5</asp:HyperLink></li>
            <li class="last" runat="server"><asp:HyperLink runat="server" NavigateUrl="/categories/category6.aspx">Category 6</asp:HyperLink></li>
         </ul>
    </li>
    <li class="last" runat="server"><asp:HyperLink runat="server" NavigateUrl="/contact.aspx">Contact Us</asp:HyperLink></li>
</ul>
</code>```

If I changed this to toggle("slide") it slides in from one side and then exits on the same side when the mouse enters and leaves the li.submenu. This means that the elements exist for definite, and there are no typos. However the slideDown and slideUp functions do not seem to be functioning (unless slow means ultra fast...).

The files I am including for jQuery and jQuery UI are jquery-1.4.2.js and jquery-ui-1.7.2.custom.min.js. This is enough, isn't it?

I have CSS to specify that the submenu is displayed or hidden instantly (display: block; / display: none;) in case the user does not have JS. Is there any chance that this is causing the problem? Should I alter the class of the submenu using JS so that the CSS cannot act on it if JS is enabled? Or is there some other problem which is not caused by the CSS?

答:
I assume that ul is inside li item in your page. If you want to slide parent ul of current li, then try

```<code>$(window).load(function () {
    $("li.submenu").hover(
        function () { $(this).parents("ul").slideDown("slow"); },
        function () { $(this).parents("ul").slideUp("slow"); }
    );
});
</code>```

Body:
I have the following code in my masterpage:

jQuery:

$(window).load(function () {
    $("li.submenu").hover(
        function () { $(this).find("ul").slideDown("slow"); },
        function () { $(this).find("ul").slideUp("slow"); }
    );
});

HTML:

<asp:HyperLink runat="server" NavigateUrl="/index.aspx">Home</asp:HyperLink>

        <asp:HyperLink runat="server" NavigateUrl="/categories/index.aspx">Products</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category1.aspx">Dogs</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category2.aspx">Category 2</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category3.aspx">Category 3</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category4.aspx">Category 4</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category5.aspx">Category 5</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/categories/category6.aspx">Category 6</asp:HyperLink>

<asp:HyperLink runat="server" NavigateUrl="/contact.aspx">Contact Us</asp:HyperLink>

If I changed this to toggle("slide") it slides in from one side and then exits on the same side when the mouse enters and leaves the li.submenu. This means that the elements exist for definite, and there are no typos. However the slideDown and slideUp functions do not seem to be functioning (unless slow means ultra fast...).

The files I am including for jQuery and jQuery UI are jquery-1.4.2.js and jquery-ui-1.7.2.custom.min.js. This is enough, isn't it?

I have CSS to specify that the submenu is displayed or hidden instantly (display: block; / display: none;) in case the user does not have JS. Is there any chance that this is causing the problem? Should I alter the class of the submenu using JS so that the CSS cannot act on it if JS is enabled? Or is there some other problem which is not caused by the CSS?

Body:
I assume that ul is inside li item in your page. If you want to slide parent ul of current li, then try

$(window).load(function () {
    $("li.submenu").hover(
        function () { $(this).parents("ul").slideDown("slow"); },
        function () { $(this).parents("ul").slideUp("slow"); }
    );
});

ContentLicense: CC BY-SA 2.5


问:
Write ID3 tags python mutagen
Try to change ID3 tags in mp3 file using python3 & mutagen.
trackN.add(mutagen.id3.TIT2(encoding=3, text=dict['title']))
It works on Ubuntu, but on Windows7 all tags are disappear.
No errors in script.
How can i fix it?

答:
The problem is that you need to save the tags in the ID3 second version </p>

```<code>audio.save(v2_version=3)
</code>```

Title: Write ID3 tags python mutagen

Body:
The problem is that you need to save the tags in the ID3 second version

audio.save(v2_version=3)


答:
I'm guessing you are trying to clip image to its bounds. Try this</p>

```<code>a{
border: 5px solid blue;
overflow: hidden;
}
</code>```

Title: How to make an a tag border wrap around an image

Body:
I'm guessing you are trying to clip image to its bounds. Try this

a{
border: 5px solid blue;
overflow: hidden;
}


问:
Find if value exists in multiple lists
I have 4 list and each element on the list are unique across the 4 list. How do I find if the value exist in one of the list and return which list it exist?

Example list:

```<code>value = 'a'
a = ['a','b','c']
b = ['d','e','f']
d = ['g','h','i']
c = ['j','k','l']
</code>```

My expected output is the name of the list where the value is found:
For the example above my expected output would be:

a

答:
What you are trying to do is almost always a bad idea. Suppose you do get a string containing the name of the list you want. What do you do with it then? There's no nice way to get a variable if all you have is a string containing its name. You can do it with globals() or locals(), but those inevitably make your code messy and confusing.

The correct way to do this is to use a list or a dictionary to collect all of the lists you want to search through. Iterating through a single object is much better practice than iterating through every name in the global or local scope.

```<code>value = "a"
named_lists = {
    "a": ['a','b','c'],
    "b": ['d','e','f'],
    "d": ['g','h','i'],
    "c": ['j','k','l']
}

names = [name for name, seq in named_lists.items() if value in seq]
print(names)
if names: #there may be multiple lists that contain `value`, so let's just look at the first one, if it exists
    first_name = names[0]
    print(named_lists[first_name])
</code>```

Result:

```<code>['a']
['a', 'b', 'c']
</code>```

Title: Find if value exists in multiple lists

Body:
I have 4 list and each element on the list are unique across the 4 list. How do I find if the value exist in one of the list and return which list it exist?

Example list:

value = 'a'
a = ['a','b','c']
b = ['d','e','f']
d = ['g','h','i']
c = ['j','k','l']

My expected output is the name of the list where the value is found:
For the example above my expected output would be:

a

Body:
What you are trying to do is almost always a bad idea. Suppose you do get a string containing the name of the list you want. What do you do with it then? There's no nice way to get a variable if all you have is a string containing its name. You can do it with globals() or locals(), but those inevitably make your code messy and confusing.

The correct way to do this is to use a list or a dictionary to collect all of the lists you want to search through. Iterating through a single object is much better practice than iterating through every name in the global or local scope.

value = "a"
named_lists = {
    "a": ['a','b','c'],
    "b": ['d','e','f'],
    "d": ['g','h','i'],
    "c": ['j','k','l']
}

names = [name for name, seq in named_lists.items() if value in seq]
print(names)
if names: #there may be multiple lists that contain `value`, so let's just look at the first one, if it exists
    first_name = names[0]
    print(named_lists[first_name])

Result:

['a']
['a', 'b', 'c']


问:
Laravel redirect issue from blade template
I am new in laravel 5 .
I am working on larvel page security and i have to prevent open some page or Url
but when i use {{ Redirect::to('/dashboard') }} in view it is not working .

Please help me to find a way to use Redirect / Url in laravel view (Blade template)

I have already tried :-

{{ url('/dashboard') }}

{{ Redirect::to('/dashboard') }}

Code :-

```<code>@if(Auth::user()->role_id == 1)
{{ 'Page' }}
@else
{{ Redirect::to('/dashboard') }}
@endif
</code>```

答:
Your question is hard to understand, but I suppose you want to redirect the user on the view after check if he is login. I have bad news for you, logic goes on the Controller not on Views.

That means you need to check if the user is login on the Controller and after that you redirect to the proper view, on Laravel the most common way to do it is to create a Middleware that checks if the user is login and then apply the correct logic.

You have a lot of ways to do it, but at first you need  to understand how it works, you can check it on the Laravel Authentication docs.

ContentLicense: CC BY-SA 4.0

Body:
I am new in laravel 5 .
I am working on larvel page security and i have to prevent open some page or Url
but when i use {{ Redirect::to('/dashboard') }} in view it is not working .

Please help me to find a way to use Redirect / Url in laravel view (Blade template)

I have already tried :-

{{ url('/dashboard') }}

{{ Redirect::to('/dashboard') }}

Code :-

@if(Auth::user()->role_id == 1)
{{ 'Page' }}
@else
{{ Redirect::to('/dashboard') }}
@endif


问:
Android Studio SQLite Insert Data
I am creating a database and then trying to select some data from it. Below is my DBHelper file which successfully creates the database and tries to insert data into it:

```<code> package com.racecoursedatatechnologies.rdtstockmanagement;

 import android.content.Context;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.content.ContentValues;
 import android.util.Log;

 public class DBHelper  extends SQLiteOpenHelper {

//Version number
private static final int DATABASE_VERSION = 4;

//Database Name
private static final String DATABASE_NAME = "rdt.db";

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    //All tables are created here
    String CREATE_TABLE_USERS = "CREATE TABLE IF NOT EXISTS " + dbTables.userTABLE + "("
            + dbTables.uID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
            + dbTables.username + " TEXT, "
            + dbTables.userpassword + " TEXT );";

    String CREATE_TABLE_STOCK = "CREATE TABLE IF NOT EXISTS " + dbTables.stockTABLE + "("
            + dbTables.sID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
            + dbTables.itemname + " TEXT, "
            + dbTables.itemdescription + " TEXT, "
            + dbTables.itemamount + " INTEGER, "
            + dbTables.itemimage + " TEXT );";

    //Create tables using execute function
    db.execSQL(CREATE_TABLE_USERS);
    db.execSQL(CREATE_TABLE_STOCK);

    //Now add our first user automatically which is the administrator.
    ContentValues contentValues = new ContentValues();
    contentValues.put(dbTables.username, "Administrator");
    contentValues.put(dbTables.userpassword, "abc123");
    db.insert(dbTables.userTABLE, null, contentValues);
    db.close();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    //Drop older table if existed, all data will be gone
    db.execSQL("DROP TABLE IF EXISTS " + dbTables.userTABLE);
    db.execSQL("DROP TABLE IF EXISTS " + dbTables.stockTABLE);

    //Create tables again
    onCreate(db);

}

 }
</code>```

I am then trying to select the uID column that I have inserted into the database table to see if the user exists with the name and password and can login using the following code:

```<code>//Attempt the user login
public void attemptLogin(View v)
{

    EditText et1 = (EditText)findViewById(R.id.txtUsername);
    EditText et2 = (EditText)findViewById(R.id.txtPassword);

    String input_name = et1.getText().toString();
    String input_password = et2.getText().toString();
    dbhelper = new DBHelper(this);
    SQLiteDatabase db = dbhelper.getReadableDatabase();

  String selectQuery = "SELECT " +
            dbTables.uID +
            " FROM " + dbTables.userTABLE +
            " WHERE " + dbTables.username +
            " = " + "'" + input_name + "'" + " AND " +
            dbTables.userpassword + " = " + "'" + input_password + "'";

    Cursor c = db.rawQuery(selectQuery, null);

    if(c.moveToFirst()){

        Integer userID = c.getInt(0);

        Log.d("DATABASE", userID.toString());

    }

    c.close();
    db.close();
</code>```

However the application keeps crashing out when I press the button saying it cannot find the Column 'Administrator' but I am inserting the data upon creating the database??

答:
Rectify your Query

```<code> String selectQuery = "SELECT * FROM Users WHERE  username"+ " = '"+ input_name  +"'";
</code>```

FYI

Convert Integer to String

```<code>Log.d("DATABASE", String.valueOf(userID));
</code>```

Title: Android Studio SQLite Insert Data

Body:
I am creating a database and then trying to select some data from it. Below is my DBHelper file which successfully creates the database and tries to insert data into it:

 package com.racecoursedatatechnologies.rdtstockmanagement;

 import android.content.Context;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.content.ContentValues;
 import android.util.Log;

 public class DBHelper  extends SQLiteOpenHelper {

//Version number
private static final int DATABASE_VERSION = 4;

//Database Name
private static final String DATABASE_NAME = "rdt.db";

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    //All tables are created here
    String CREATE_TABLE_USERS = "CREATE TABLE IF NOT EXISTS " + dbTables.userTABLE + "("
            + dbTables.uID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
            + dbTables.username + " TEXT, "
            + dbTables.userpassword + " TEXT );";

    String CREATE_TABLE_STOCK = "CREATE TABLE IF NOT EXISTS " + dbTables.stockTABLE + "("
            + dbTables.sID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
            + dbTables.itemname + " TEXT, "
            + dbTables.itemdescription + " TEXT, "
            + dbTables.itemamount + " INTEGER, "
            + dbTables.itemimage + " TEXT );";

    //Create tables using execute function
    db.execSQL(CREATE_TABLE_USERS);
    db.execSQL(CREATE_TABLE_STOCK);

    //Now add our first user automatically which is the administrator.
    ContentValues contentValues = new ContentValues();
    contentValues.put(dbTables.username, "Administrator");
    contentValues.put(dbTables.userpassword, "abc123");
    db.insert(dbTables.userTABLE, null, contentValues);
    db.close();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    //Drop older table if existed, all data will be gone
    db.execSQL("DROP TABLE IF EXISTS " + dbTables.userTABLE);
    db.execSQL("DROP TABLE IF EXISTS " + dbTables.stockTABLE);

    //Create tables again
    onCreate(db);

}

 }

I am then trying to select the uID column that I have inserted into the database table to see if the user exists with the name and password and can login using the following code:

//Attempt the user login
public void attemptLogin(View v)
{

    EditText et1 = (EditText)findViewById(R.id.txtUsername);
    EditText et2 = (EditText)findViewById(R.id.txtPassword);

    String input_name = et1.getText().toString();
    String input_password = et2.getText().toString();
    dbhelper = new DBHelper(this);
    SQLiteDatabase db = dbhelper.getReadableDatabase();

  String selectQuery = "SELECT " +
            dbTables.uID +
            " FROM " + dbTables.userTABLE +
            " WHERE " + dbTables.username +
            " = " + "'" + input_name + "'" + " AND " +
            dbTables.userpassword + " = " + "'" + input_password + "'";

    Cursor c = db.rawQuery(selectQuery, null);

    if(c.moveToFirst()){

        Integer userID = c.getInt(0);

        Log.d("DATABASE", userID.toString());

    }

    c.close();
    db.close();

However the application keeps crashing out when I press the button saying it cannot find the Column 'Administrator' but I am inserting the data upon creating the database??

Body:
Rectify your Query

 String selectQuery = "SELECT * FROM Users WHERE  username"+ " = '"+ input_name  +"'";

FYI

Convert Integer to String

Log.d("DATABASE", String.valueOf(userID));


问:
Automatically reply to an email
I'm working on a project I'm Java with regards to outlook.

Here I'm able to do all the functions like Read a mail, write a mail, reply to a mail etc...

But now we've been thinking of taking it to the next level.

Our plan is as below.

We have an email address like info@myDomain.com, when ever an email is sent to this address, I need to reply them. Here basically customers send an email asking for some data, and we've the data available in our portal, and we just need to send it.
The response would be Like thank you for contacting us, we will get back to you soon. Mean while please look into this {URL}.

And this has to be done automatically when ever there is an email hit to this particular email address.

Couple of questions:
- should my machine be on the whole day to get this thing done.
- is  there a way that a Java application can automatically monitor my inbox to see for this case match.
- Also, can I have this running in the bg.

Can someone please point me into the right direction/approach where can I can start working on this task.

Thanks

答:
when ever an email is sent to this address, I need to reply them.

For this you need to monitor your email account fro incoming emails. Here is one of the way to do this

The response would be Like thank you for contacting us, we will get back to you soon. Mean while please look into this {URL}.

Once you receive an email (using above email monitoring approach), you need to call a method that sends the reply with above format

And this has to be done automatically when ever there is an email hit to this particular email address.

Above two steps accomplishes this task.

should my machine be on the whole day to get this thing done

Basically, you will need an application server (like tomcat) where your above java program is deployed. So, yes this server needs to be running and available all the time.

is there a way that a Java application can automatically monitor my inbox to see for this case match

Check point 1

Also, can I have this running in the bg
  You can run tomcat as a service in windows (more info). It has many advantages, automatic startup on boot being the one. Similar implementations are also available for other OS.

So, in short, this can be accomplished. It is bit complex but not much difficult. Cheers

Title: Automatically reply to an email


问:
Pass changed files path to another command
I have a versioning command and we have to manually run it with all the changed files.

Is it possible to pass the changed and added files to another command as argument?

I have tried solutions mentioned in this link: is it possible to `git status` only modified files?, but its not working.

For sample I have made a dummy command:

```<code>function notify(){
    echo "*****************************************************************"
    echo $1
    echo "*****************************************************************"
}
</code>```

And I try to use it as:

git status -s | notify

git ls-files -m | notify

Is there a way to send individual file path to such command?

Edit 1:

As rightly pointed by mallaudin, I was missing xargs. But adding that now throws another error.

xargs: notify: No such file or directory

Body:
I have a versioning command and we have to manually run it with all the changed files.

Is it possible to pass the changed and added files to another command as argument?

I have tried solutions mentioned in this link: is it possible to `git status` only modified files?, but its not working.

For sample I have made a dummy command:

function notify(){
    echo "*****************************************************************"
    echo $1
    echo "*****************************************************************"
}

And I try to use it as:

git status -s | notify

git ls-files -m | notify

Is there a way to send individual file path to such command?

Edit 1:

As rightly pointed by mallaudin, I was missing xargs. But adding that now throws another error.

xargs: notify: No such file or directory

Body:
Pipe output to bash function this can help you.

function notify(){
    echo "*****************************************************************"
    read foo
    echo "*****************************************************************"
}


问:
Django REST overrride destroy method to make user inactive
I'm trying to first access the users table via the user foreign key present in userinformations models and later override the RetriveUpdateDestroy API view's destroy method to change the status of the user to inactive instead of deleting them. I can't seem to access the is-active field of the in built User database.

views.py

```<code>class UserUpdateApiView(RetrieveUpdateDestroyAPIView):
queryset = UserInformation.objects.all()
serializer_class = UserInformationUpdateSerializer
lookup_field = 'pk'
lookup_url_kwarg = 'id'

def destroy(self, request, *args, **kwargs):
    try:
        user = User.objects.get(pk=self.kwargs["id"])
        deleteStatusVal = False
        user.is_active = deleteStatusVal
        user.save()
        return Response(UserSerializer(user).data)
    except:
        return Response("Nope")
</code>```

serializers.py

```<code>class UserSerializer(ModelSerializer):
password = serializers.CharField(style={'input_type': 'password'}, write_only=True)
email = serializers.EmailField(validators=[required])

class Meta:
    model = User
    fields = ['username', 'email', 'password', 'is_active']
    extra_kwargs = {'password': {'write_only': True},
                    'is_active': {'read_only': True}}

def validate(self, data):
    email = data.get('email', None)
    user = User.objects.filter(email=email).distinct()
    if user.exists():
        raise ValidationError("That email is already registered!")
    return data

class UserInformationUpdateSerializer(ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
    model = UserInformation
    fields = ['user', 'first_name', 'middle_name', 'last_name', 'phone', 'date_of_birth']
</code>```

models.py

```<code>class UserInformation(BaseModel):
user = models.OneToOneField(User, related_name='user_id')
first_name = models.CharField(max_length=45)
middle_name = models.CharField(max_length=45, null=True)
last_name = models.CharField(max_length=45)
vendor = models.BooleanField(default=False)
phone = models.CharField(max_length=100, validators=[
RegexValidator(regex=r'^\+?8801?\d{9}$', message="Phone number must be entered in the format: '+8801*********'")
], blank=False, unique=True)
date_of_birth = models.DateField()
confirmation_token = models.CharField(max_length=45, null=True)
confirmation_exp = models.DateTimeField(null=True)
pw_reminder_token = models.CharField(max_length=45, null=True)
pw_reminder_exp = models.DateTimeField(null=True)
profile_pic = models.ImageField(blank=True, null=True, upload_to='profile_images/', default='Images/none/no_images.jpg')
cover_photo = models.ImageField(blank=True, null=True, upload_to='cover_images/', default='Images/none/no_images.jpg')
thumbnail_pic = models.ImageField(blank=True, null=True, upload_to='thumbnail_images/', default='Images/none/no_images.jpg')
phone_verified = models.BooleanField(default=False)
email_verified = models.BooleanField(default=False)
reward_points = models.IntegerField(null=False)
ref_code = models.CharField(null=True, max_length=10)

def __str__(self):
    return self.user.username

def delete(self, *args, **kwargs):
    self.user.delete()
    super(UserInformation, self).delete(*args, **kwargs)
</code>```

答:
If you want to make User as in active while keeping the UserInformation object and Userobject un-deleted in database, you can do something like this:

```<code>def destroy(self, request, *args, **kwargs):
    user = self.get_object().user
    user.is_active = False
    user.save()
    return Response(UserInformationUpdateSerializer(self.get_object()).data)
</code>```

Body:
I'm trying to first access the users table via the user foreign key present in userinformations models and later override the RetriveUpdateDestroy API view's destroy method to change the status of the user to inactive instead of deleting them. I can't seem to access the is-active field of the in built User database.

views.py

class UserUpdateApiView(RetrieveUpdateDestroyAPIView):
queryset = UserInformation.objects.all()
serializer_class = UserInformationUpdateSerializer
lookup_field = 'pk'
lookup_url_kwarg = 'id'

def destroy(self, request, *args, **kwargs):
    try:
        user = User.objects.get(pk=self.kwargs["id"])
        deleteStatusVal = False
        user.is_active = deleteStatusVal
        user.save()
        return Response(UserSerializer(user).data)
    except:
        return Response("Nope")

serializers.py

class UserSerializer(ModelSerializer):
password = serializers.CharField(style={'input_type': 'password'}, write_only=True)
email = serializers.EmailField(validators=[required])

class Meta:
    model = User
    fields = ['username', 'email', 'password', 'is_active']
    extra_kwargs = {'password': {'write_only': True},
                    'is_active': {'read_only': True}}

def validate(self, data):
    email = data.get('email', None)
    user = User.objects.filter(email=email).distinct()
    if user.exists():
        raise ValidationError("That email is already registered!")
    return data

class UserInformationUpdateSerializer(ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
    model = UserInformation
    fields = ['user', 'first_name', 'middle_name', 'last_name', 'phone', 'date_of_birth']

models.py

class UserInformation(BaseModel):
user = models.OneToOneField(User, related_name='user_id')
first_name = models.CharField(max_length=45)
middle_name = models.CharField(max_length=45, null=True)
last_name = models.CharField(max_length=45)
vendor = models.BooleanField(default=False)
phone = models.CharField(max_length=100, validators=[
RegexValidator(regex=r'^\+?8801?\d{9}$', message="Phone number must be entered in the format: '+8801*********'")
], blank=False, unique=True)
date_of_birth = models.DateField()
confirmation_token = models.CharField(max_length=45, null=True)
confirmation_exp = models.DateTimeField(null=True)
pw_reminder_token = models.CharField(max_length=45, null=True)
pw_reminder_exp = models.DateTimeField(null=True)
profile_pic = models.ImageField(blank=True, null=True, upload_to='profile_images/', default='Images/none/no_images.jpg')
cover_photo = models.ImageField(blank=True, null=True, upload_to='cover_images/', default='Images/none/no_images.jpg')
thumbnail_pic = models.ImageField(blank=True, null=True, upload_to='thumbnail_images/', default='Images/none/no_images.jpg')
phone_verified = models.BooleanField(default=False)
email_verified = models.BooleanField(default=False)
reward_points = models.IntegerField(null=False)
ref_code = models.CharField(null=True, max_length=10)

def __str__(self):
    return self.user.username

def delete(self, *args, **kwargs):
    self.user.delete()
    super(UserInformation, self).delete(*args, **kwargs)

Body:
If you want to make User as in active while keeping the UserInformation object and Userobject un-deleted in database, you can do something like this:

def destroy(self, request, *args, **kwargs):
    user = self.get_object().user
    user.is_active = False
    user.save()
    return Response(UserInformationUpdateSerializer(self.get_object()).data)


问:
Wildcard to match files with two "dots"
This does not work:

```<code>del "folder\*.dll.config"
</code>```

However, it does work without specifying a folder

```<code>cd folder
del "*.dll.config"
</code>```

Why?

PS. Also, any workarounds? (beside the one mentioned - changing current dir and then going back)

EDIT: I'm an idiot I had a typo in my code, voting to close my own question now.

答:
On my Windows 10, it works:

```<code>C:\>dir folder
Volume in drive C is SYSTEM
Directory of C:\folder

30.03.2017  14.33    <DIR>          .
30.03.2017  14.33    <DIR>          ..
29.03.2017  13.33           549.341 my.dll.config
29.03.2017  13.33           549.341 my.foo.bar
           2 File(s)      1.098.682 bytes
           2 Dir(s) 363.317.178.368 bytes free

C:\>del "folder\*.dll.config"

C:\>dir folder
Volume in drive C is SYSTEM
Directory of C:\folder

30.03.2017  14.33    <DIR>          .
30.03.2017  14.33    <DIR>          ..
29.03.2017  13.33           549.341 my.foo.bar
           1 File(s)        549.341 bytes
           2 Dir(s) 363.317.809.152 bytes free

C:\>
</code>```

However, your misspelling of the error message in the comment above made me check something.

It may be completely irrelevant in your case, but sure enough, if I misspell the folder name, I get precisely the error you mentioned:

```<code>C:\>dir folder
Volume in drive C is SYSTEM
Directory of C:\folder

30.03.2017  14.33    <DIR>          .
30.03.2017  14.33    <DIR>          ..
29.03.2017  13.33           549.341 my.dll.config
29.03.2017  13.33           549.341 my.foo.bar
           2 File(s)      1.098.682 bytes
           2 Dir(s) 363.317.248.000 bytes free

C:\>del "dolder\*.dll.config"
The system cannot find the file specified.

C:\>
</code>```

Title: Wildcard to match files with two "dots"

Body:
This does not work:

del "folder\*.dll.config"

However, it does work without specifying a folder

cd folder
del "*.dll.config"

Why?

PS. Also, any workarounds? (beside the one mentioned - changing current dir and then going back)

EDIT: I'm an idiot I had a typo in my code, voting to close my own question now.

Body:
On my Windows 10, it works:

C:\>dir folder
Volume in drive C is SYSTEM
Directory of C:\folder

30.03.2017  14.33    <DIR>          .
30.03.2017  14.33    <DIR>          ..
29.03.2017  13.33           549.341 my.dll.config
29.03.2017  13.33           549.341 my.foo.bar
           2 File(s)      1.098.682 bytes
           2 Dir(s) 363.317.178.368 bytes free

C:\>del "folder\*.dll.config"

C:\>dir folder
Volume in drive C is SYSTEM
Directory of C:\folder

30.03.2017  14.33    <DIR>          .
30.03.2017  14.33    <DIR>          ..
29.03.2017  13.33           549.341 my.foo.bar
           1 File(s)        549.341 bytes
           2 Dir(s) 363.317.809.152 bytes free

C:\>

However, your misspelling of the error message in the comment above made me check something.

It may be completely irrelevant in your case, but sure enough, if I misspell the folder name, I get precisely the error you mentioned:

C:\>dir folder
Volume in drive C is SYSTEM
Directory of C:\folder

30.03.2017  14.33    <DIR>          .
30.03.2017  14.33    <DIR>          ..
29.03.2017  13.33           549.341 my.dll.config
29.03.2017  13.33           549.341 my.foo.bar
           2 File(s)      1.098.682 bytes
           2 Dir(s) 363.317.248.000 bytes free

C:\>del "dolder\*.dll.config"
The system cannot find the file specified.

C:\>


问:
Thread Safety in Concurrent Queue C#
I have a MessagesManager thread to which different threads may send messages and then this  MessagesManager thread is responsible to publish these messages inside SendMessageToTcpIP() (start point of MessagesManager thread ).

```<code>class MessagesManager : IMessageNotifier
{
    //private
    private readonly AutoResetEvent _waitTillMessageQueueEmptyARE = new AutoResetEvent(false);
    private ConcurrentQueue<string> MessagesQueue = new ConcurrentQueue<string>();

    public void PublishMessage(string Message)
    {
        MessagesQueue.Enqueue(Message);
        _waitTillMessageQueueEmptyARE.Set();
    }

    public void SendMessageToTcpIP()
    {
        //keep waiting till a new message comes
        while (MessagesQueue.Count() == 0)
        {
            _waitTillMessageQueueEmptyARE.WaitOne();
        }

        //Copy the Concurrent Queue into a local queue - keep dequeuing the item once it is inserts into the local Queue
        Queue<string> localMessagesQueue = new Queue<string>();

        while (!MessagesQueue.IsEmpty)
        {
            string message;
            bool isRemoved = MessagesQueue.TryDequeue(out message);
            if (isRemoved)
                localMessagesQueue.Enqueue(message);
        }

        //Use the Local Queue for further processing
        while (localMessagesQueue.Count() != 0)
        {
            TcpIpMessageSenderClient.ConnectAndSendMessage(localMessagesQueue.Dequeue().PadRight(80, ' '));
            Thread.Sleep(2000);
        }
    }
}
</code>```

The different threads (3-4) send their message by calling the PublishMessage(string Message) (using same object to MessageManager). Once the message comes, I push that message into a concurrent queue and notifies the  SendMessageToTcpIP() by setting _waitTillMessageQueueEmptyARE.Set();. Inside SendMessageToTcpIP(), I am copying the message from the concurrent queue inside a local queue and then publish one by one.

QUESTIONS: Is it thread safe to do enqueuing and dequeuing in this way? Could there be some strange effects due to it?

答:
.NET already provides ActionBlock< T> that allows posting messages to a buffer and processing them asynchronously. By default, only one message is processed at a time.

Your code could be rewritten as:

```<code>//In an initialization function
ActionBlock<string> _hmiAgent=new ActionBlock<string>(async msg=>{
        TcpIpMessageSenderClient.ConnectAndSendMessage(msg.PadRight(80, ' '));
        await Task.Delay(2000);
);

//In some other thread ...
foreach ( ....)
{
    _hmiAgent.Post(someMessage);
}

// When the application closes

_hmiAgent.Complete();
await _hmiAgent.Completion;
</code>```

ActionBlock offers many benefits - you can specify a limit to the number of items it can accept in a buffer and specify that multiple messages can be processed in parallel. You can also combine multiple blocks in a processing pipeline. In a desktop application, a message can be posted to a pipeline in response to an event, get processed by separate blocks and results posted to a final block that updates the UI.

Padding, for example, could be performed by an intermediary TransformBlock< TIn,TOut>. This transformation is trivial and the cost of using the block is greater than the method, but that's just an illustration:

```<code>//In an initialization function
TransformBlock<string> _hmiAgent=new TransformBlock<string,string>(
    msg=>msg.PadRight(80, ' '));

ActionBlock<string> _tcpBlock=new ActionBlock<string>(async msg=>{
        TcpIpMessageSenderClient.ConnectAndSendMessage());
        await Task.Delay(2000);
);

var linkOptions=new DataflowLinkOptions{PropagateCompletion = true};
_hmiAgent.LinkTo(_tcpBlock);
</code>```

The posting code doesn't change at all

```<code>    _hmiAgent.Post(someMessage);
</code>```

When the application terminates, we need to wait for the _tcpBlock to complete:

```<code>    _hmiAgent.Complete();
    await _tcpBlock.Completion;
</code>```

Visual Studio 2015+ itself uses TPL Dataflow for such scenarios

Bar Arnon provides a better example in TPL Dataflow Is The Best Library You're Not Using, that shows how both synchronous and asynchronous methods can be used in a block.

Title: Thread Safety in Concurrent Queue C#

Body:
I have a MessagesManager thread to which different threads may send messages and then this  MessagesManager thread is responsible to publish these messages inside SendMessageToTcpIP() (start point of MessagesManager thread ).

class MessagesManager : IMessageNotifier
{
    //private
    private readonly AutoResetEvent _waitTillMessageQueueEmptyARE = new AutoResetEvent(false);
    private ConcurrentQueue<string> MessagesQueue = new ConcurrentQueue<string>();

    public void PublishMessage(string Message)
    {
        MessagesQueue.Enqueue(Message);
        _waitTillMessageQueueEmptyARE.Set();
    }

    public void SendMessageToTcpIP()
    {
        //keep waiting till a new message comes
        while (MessagesQueue.Count() == 0)
        {
            _waitTillMessageQueueEmptyARE.WaitOne();
        }

        //Copy the Concurrent Queue into a local queue - keep dequeuing the item once it is inserts into the local Queue
        Queue<string> localMessagesQueue = new Queue<string>();

        while (!MessagesQueue.IsEmpty)
        {
            string message;
            bool isRemoved = MessagesQueue.TryDequeue(out message);
            if (isRemoved)
                localMessagesQueue.Enqueue(message);
        }

        //Use the Local Queue for further processing
        while (localMessagesQueue.Count() != 0)
        {
            TcpIpMessageSenderClient.ConnectAndSendMessage(localMessagesQueue.Dequeue().PadRight(80, ' '));
            Thread.Sleep(2000);
        }
    }
}

The different threads (3-4) send their message by calling the PublishMessage(string Message) (using same object to MessageManager). Once the message comes, I push that message into a concurrent queue and notifies the  SendMessageToTcpIP() by setting _waitTillMessageQueueEmptyARE.Set();. Inside SendMessageToTcpIP(), I am copying the message from the concurrent queue inside a local queue and then publish one by one.

QUESTIONS: Is it thread safe to do enqueuing and dequeuing in this way? Could there be some strange effects due to it?

Body:
.NET already provides ActionBlock< T> that allows posting messages to a buffer and processing them asynchronously. By default, only one message is processed at a time.

Your code could be rewritten as:

//In an initialization function
ActionBlock<string> _hmiAgent=new ActionBlock<string>(async msg=>{
        TcpIpMessageSenderClient.ConnectAndSendMessage(msg.PadRight(80, ' '));
        await Task.Delay(2000);
);

//In some other thread ...
foreach ( ....)
{
    _hmiAgent.Post(someMessage);
}

// When the application closes

_hmiAgent.Complete();
await _hmiAgent.Completion;

ActionBlock offers many benefits - you can specify a limit to the number of items it can accept in a buffer and specify that multiple messages can be processed in parallel. You can also combine multiple blocks in a processing pipeline. In a desktop application, a message can be posted to a pipeline in response to an event, get processed by separate blocks and results posted to a final block that updates the UI.

Padding, for example, could be performed by an intermediary TransformBlock< TIn,TOut>. This transformation is trivial and the cost of using the block is greater than the method, but that's just an illustration:

//In an initialization function
TransformBlock<string> _hmiAgent=new TransformBlock<string,string>(
    msg=>msg.PadRight(80, ' '));

ActionBlock<string> _tcpBlock=new ActionBlock<string>(async msg=>{
        TcpIpMessageSenderClient.ConnectAndSendMessage());
        await Task.Delay(2000);
);

var linkOptions=new DataflowLinkOptions{PropagateCompletion = true};
_hmiAgent.LinkTo(_tcpBlock);

The posting code doesn't change at all

    _hmiAgent.Post(someMessage);

When the application terminates, we need to wait for the _tcpBlock to complete:

    _hmiAgent.Complete();
    await _tcpBlock.Completion;

Visual Studio 2015+ itself uses TPL Dataflow for such scenarios

Bar Arnon provides a better example in TPL Dataflow Is The Best Library You're Not Using, that shows how both synchronous and asynchronous methods can be used in a block.


问:
Transfer array of bytes (gcroot<System::Byte []> cosbuf;) from /oldsyntax to /clr
I have now updated my c++ project from /oldsyntax to /clr, but I have problems to run it.

The old program (which runs fine has this)

```<code>gcroot<System::Byte []> cosbuf;  (in header file)
</code>```

And this in the constructor

```<code>cosbuf = new System::Byte[4096];  // This will not compile
</code>```

and then this in the cpp file

```<code>System::Byte __pin *cosbuf_pin = &cosbuf[0];
char *cosbuf_ptr = reinterpret_cast<char*>(cosbuf_pin);
</code>```

I tried to convert it to :

```<code>gcroot<array<System::Byte>^> cosbuf;  // in .h file

array< System::Byte >^ cosbuf = gcnew array< System::Byte >(4096); // in constructor

pin_ptr<unsigned char> cosbuf_pin = &cosbuf[0];     // in cpp program
char *cosbuf_ptr = reinterpret_cast<char*>(cosbuf_pin);
</code>```

This compile, but the cosbuf_pin assignement with pin_ptr throw exception with "Object reference not set to an instance of the object".

Either I need other ways of having a cosbuf_ptr to the cosbuf or some other data structures is needed. Basically an array of 4096 bytes is needed for this buffer.

答:
You are declaring a new variable in the Constructor instead of using the one defined in the class.

Replace

array< System::Byte >^ cosbuf = gcnew array< System::Byte >(4096); // in constructor

with

cosbuf = gcnew array< System::Byte >(4096); // in constructor

Body:
I have now updated my c++ project from /oldsyntax to /clr, but I have problems to run it.

The old program (which runs fine has this)

gcroot<System::Byte []> cosbuf;  (in header file)

And this in the constructor

cosbuf = new System::Byte[4096];  // This will not compile

and then this in the cpp file

System::Byte __pin *cosbuf_pin = &cosbuf[0];
char *cosbuf_ptr = reinterpret_cast<char*>(cosbuf_pin);

I tried to convert it to :

gcroot<array<System::Byte>^> cosbuf;  // in .h file

array< System::Byte >^ cosbuf = gcnew array< System::Byte >(4096); // in constructor

pin_ptr<unsigned char> cosbuf_pin = &cosbuf[0];     // in cpp program
char *cosbuf_ptr = reinterpret_cast<char*>(cosbuf_pin);

This compile, but the cosbuf_pin assignement with pin_ptr throw exception with "Object reference not set to an instance of the object".

Either I need other ways of having a cosbuf_ptr to the cosbuf or some other data structures is needed. Basically an array of 4096 bytes is needed for this buffer.


问:
Using external react component missing react
Imagine i have large reactjs project lets call it A and i want to use external component residing in another project which consist only of pure components (.jsx & .css  files) without node_modules folder lets call that project B.
Problem component from project B cannot find react.

Module build failed: Error: Couldn't find preset "react" relative to directory

Logically because there is no node_modules folder in project.

Is there a way to instruct components from project B to use node_modules from project A

I was thinkning somehow utilize webpack but no idea how ?

答:
You can create a root folder that contains a node_modules folder that will be shared to all your sub-projects (A and B). Inside this folder you can drop all the "common" components, modules, libraries, etc.

When you require a module, NodeJS will look for the node_modules folder on that project, if doesn't find the module there, it will look for it in a directory above and so long.


问:
How to create a custom DateTime in php?
Hi here I have a scenario that i have two strings in two variables,

```<code>$a = '2017-03-09';
$b = '16:00';
</code>```

these are like date part and time part of datetime in php
i want to join these part and create a datetime
and want to perform diff operation , for example i have created this datetime as a variable $custom_datetime

my output should be as

```<code>$interval = $custom_datetime->diff(date());
die($interval->format('%H:%I:%s'));
</code>```

this operation should give a proper time difference but i am unable to make this $custom_datetime

答:
Use the  DateTime::createFromFormat()   static  method  to  create  a    DateTime   instance    with
a   date    and time    string  that    uses    a   custom  format. This    method’s    first   argument    is  the date
and time    string  format. The second  argument    is  the date    and time    string  that    uses    said
format :

```<code>$a = '2017-03-09';
$b = '16:00';

$datetime   =   DateTime::createFromFormat('Y-m-d H:i', $a.$b);
print_r($datetime);
</code>```

The  DateTime::createFromFormat()   static  method  accepts the same    date    and time
formats as  the  date()     function.   Valid   date    and time    formats are available   at
http://php.net/manual/datetime.createfromformat.php.

Title: How to create a custom DateTime in php?

Body:
Hi here I have a scenario that i have two strings in two variables,

$a = '2017-03-09';
$b = '16:00';

these are like date part and time part of datetime in php
i want to join these part and create a datetime
and want to perform diff operation , for example i have created this datetime as a variable $custom_datetime

my output should be as

$interval = $custom_datetime->diff(date());
die($interval->format('%H:%I:%s'));

this operation should give a proper time difference but i am unable to make this $custom_datetime

Body:
Use the  DateTime::createFromFormat()   static  method  to  create  a    DateTime   instance    with
a   date    and time    string  that    uses    a   custom  format. This    method’s    first   argument    is  the date
and time    string  format. The second  argument    is  the date    and time    string  that    uses    said
format :

$a = '2017-03-09';
$b = '16:00';

$datetime   =   DateTime::createFromFormat('Y-m-d H:i', $a.$b);
print_r($datetime);

The  DateTime::createFromFormat()   static  method  accepts the same    date    and time
formats as  the  date()     function.   Valid   date    and time    formats are available   at
http://php.net/manual/datetime.createfromformat.php.


问:
Alternative to HtmlUnit
I have been researching about the headless browsers available till to date and found HtmlUnit being used pretty extensively. Do we have any alternative to HtmlUnit with possible advantage compared to HtmlUnit?

Thanks
Nayn

答:
I am going to use Selenium for my use case, since it offers me to use the real browser and no deviation from what it would render in real world as compared to HtmlUnit.
I am planning to use Selenium2 which has WebDriver integration and offers great API and cool fixes.
Thanks
Nayn</p>

Title: Alternative to HtmlUnit


问:
Capybara/Poltergeist - Resource request error: QNetworkReply::NetworkError
I'm trying to visit an Instagram Location Page:

```<code>https://www.instagram.com/explore/locations/213385402/london-united-kingdom/
</code>```

Although Capybara succeeds with other pages like, individual Posts or Profiles, when it comes to any location page I get ContentOperationNotPermittedError

I tried debugging but I exhausted all my options.

What am I missing?

EDIT: This is working fine on Development, running it on Heroku brings up that problem.

```<code>irb(main):004:0> b.visit 'https://www.instagram.com/explore/locations/213385402/london-united-kingdom/'
2017-03-30T08:45:17 [DEBUG] WebPage - evaluateJavaScript "(function() { return (function () {\n      return typeof __poltergeist;\n    })(); })()"
2017-03-30T08:45:17 [DEBUG] WebPage - evaluateJavaScript result QVariant(QString, "object")
2017-03-30T08:45:17 [DEBUG] WebPage - evaluateJavaScript "(function() { return (function() { var page_id = arguments[0]; var args = []; for(var i=1; i < arguments.length; i++){ if ((typeof(arguments[i]) == 'object') && (typeof(arguments[i]['ELEMENT']) == 'object')){ args.push(window.__poltergeist.get(arguments[i]['ELEMENT']['id']).element); } else { args.push(arguments[i]) } } var _result = (function (name, args) {\n      return __poltergeist.externalCall(name, args);\n    }).apply(this, args); return window.__poltergeist.wrapResults(_result, page_id); })(2,\"currentUrl\",[]); })()"
2017-03-30T08:45:17 [DEBUG] WebPage - evaluateJavaScript result QVariant(QVariantMap, QMap(("value", QVariant(QString, "https://www.instagram.com/p/BSQR9Aggzm3/"))))
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "mid=WNzFfwAEAAHnUL139bDA-GgqTnzo; expires=Wed, 25-Mar-2037 08:44:47 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "s_network=\"\"; expires=Thu, 30-Mar-2017 09:44:57 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_vw=1024; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "fr=0FPrmAjBunUIn2CMi..BY3MWK...1.0.BY3MWK.; HttpOnly; expires=Wed, 28-Jun-2017 08:44:58 GMT; domain=.facebook.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "rur=PRN; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "csrftoken=yymkEesbNZEzwrlL42HJeyNmFIghmOf1; secure; expires=Thu, 29-Mar-2018 08:44:59 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_pr=1; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "mid=WNzFfwAEAAHnUL139bDA-GgqTnzo; expires=Wed, 25-Mar-2037 08:44:47 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "s_network=\"\"; expires=Thu, 30-Mar-2017 09:44:57 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "fr=0FPrmAjBunUIn2CMi..BY3MWK...1.0.BY3MWK.; HttpOnly; expires=Wed, 28-Jun-2017 08:44:58 GMT; domain=.facebook.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "rur=PRN; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "csrftoken=yymkEesbNZEzwrlL42HJeyNmFIghmOf1; secure; expires=Thu, 29-Mar-2018 08:44:59 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_pr=1; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_vw=1024; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] WebPage - updateLoadingProgress: 10
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "mid=WNzFfwAEAAHnUL139bDA-GgqTnzo; expires=Wed, 25-Mar-2037 08:44:47 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "s_network=\"\"; expires=Thu, 30-Mar-2017 09:44:57 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "fr=0FPrmAjBunUIn2CMi..BY3MWK...1.0.BY3MWK.; HttpOnly; expires=Wed, 28-Jun-2017 08:44:58 GMT; domain=.facebook.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "csrftoken=yymkEesbNZEzwrlL42HJeyNmFIghmOf1; secure; expires=Thu, 29-Mar-2018 08:44:59 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_pr=1; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_vw=1024; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "rur=PRN; domain=www.instagram.com; path=/"
==> 2017-03-30T08:45:17 [DEBUG] Network - Resource request error: QNetworkReply::NetworkError(ContentOperationNotPermittedError) ( "Error downloading https://www.instagram.com/explore/locations/213385402/london-united-kingdom/ - server replied: Forbidden" ) URL: "https://www.instagram.com/explore/locations/213385402/london-united-kingdom/"
2017-03-30T08:45:17 [DEBUG] WebPage - updateLoadingProgress: 100
2017-03-30T08:45:17 [DEBUG] WebPage - setupFrame ""
=> {"status"=>"fail"}
</code>```

Thats my Capybara/Poltergeist setup:

```<code>def setup_session
  driver_options = { js_errors: false,
                    logger: NilLogger.new,
                    phantomjs_logger: STDOUT,
                    phantomjs: Phantomjs.path,
                    phantomjs_options: [
                      '--debug=true',
                      '--ignore-ssl-errors=true',
                      '--ssl-protocol=ANY',
                      '--web-security=false',
                      '--local-to-remote-url-access=true'
                    ],
                    debug: false  }

  Capybara.configure do |config|
    config.register_driver :poltergeist do |app|
      driver = Capybara::Poltergeist::Driver.new(app, driver_options)
      driver.headers = { 'User-Agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36" }
      driver
    end

    config.run_server = false
    config.app_host = 'https://appname.herokuapp.com/'
    config.default_driver = :poltergeist
    config.default_max_wait_time = 60
  end

  Capybara.current_session
end
</code>```

答:
Apparently Instagram ban the Heroku. You should use a proxy to go to the Instagram from Heroku. How configure Capybara to use a proxy answered in this question - Using poltergeist with a proxy?
A proxy you may find in any proxy list for exmaple - https://free-proxy-list.net/</p>

Body:
I'm trying to visit an Instagram Location Page:

https://www.instagram.com/explore/locations/213385402/london-united-kingdom/

Although Capybara succeeds with other pages like, individual Posts or Profiles, when it comes to any location page I get ContentOperationNotPermittedError

I tried debugging but I exhausted all my options.

What am I missing?

EDIT: This is working fine on Development, running it on Heroku brings up that problem.

irb(main):004:0> b.visit 'https://www.instagram.com/explore/locations/213385402/london-united-kingdom/'
2017-03-30T08:45:17 [DEBUG] WebPage - evaluateJavaScript "(function() { return (function () {\n      return typeof __poltergeist;\n    })(); })()"
2017-03-30T08:45:17 [DEBUG] WebPage - evaluateJavaScript result QVariant(QString, "object")
2017-03-30T08:45:17 [DEBUG] WebPage - evaluateJavaScript "(function() { return (function() { var page_id = arguments[0]; var args = []; for(var i=1; i < arguments.length; i++){ if ((typeof(arguments[i]) == 'object') && (typeof(arguments[i]['ELEMENT']) == 'object')){ args.push(window.__poltergeist.get(arguments[i]['ELEMENT']['id']).element); } else { args.push(arguments[i]) } } var _result = (function (name, args) {\n      return __poltergeist.externalCall(name, args);\n    }).apply(this, args); return window.__poltergeist.wrapResults(_result, page_id); })(2,\"currentUrl\",[]); })()"
2017-03-30T08:45:17 [DEBUG] WebPage - evaluateJavaScript result QVariant(QVariantMap, QMap(("value", QVariant(QString, "https://www.instagram.com/p/BSQR9Aggzm3/"))))
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "mid=WNzFfwAEAAHnUL139bDA-GgqTnzo; expires=Wed, 25-Mar-2037 08:44:47 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "s_network=\"\"; expires=Thu, 30-Mar-2017 09:44:57 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_vw=1024; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "fr=0FPrmAjBunUIn2CMi..BY3MWK...1.0.BY3MWK.; HttpOnly; expires=Wed, 28-Jun-2017 08:44:58 GMT; domain=.facebook.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "rur=PRN; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "csrftoken=yymkEesbNZEzwrlL42HJeyNmFIghmOf1; secure; expires=Thu, 29-Mar-2018 08:44:59 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_pr=1; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "mid=WNzFfwAEAAHnUL139bDA-GgqTnzo; expires=Wed, 25-Mar-2037 08:44:47 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "s_network=\"\"; expires=Thu, 30-Mar-2017 09:44:57 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "fr=0FPrmAjBunUIn2CMi..BY3MWK...1.0.BY3MWK.; HttpOnly; expires=Wed, 28-Jun-2017 08:44:58 GMT; domain=.facebook.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "rur=PRN; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "csrftoken=yymkEesbNZEzwrlL42HJeyNmFIghmOf1; secure; expires=Thu, 29-Mar-2018 08:44:59 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_pr=1; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_vw=1024; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] WebPage - updateLoadingProgress: 10
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "mid=WNzFfwAEAAHnUL139bDA-GgqTnzo; expires=Wed, 25-Mar-2037 08:44:47 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "s_network=\"\"; expires=Thu, 30-Mar-2017 09:44:57 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "fr=0FPrmAjBunUIn2CMi..BY3MWK...1.0.BY3MWK.; HttpOnly; expires=Wed, 28-Jun-2017 08:44:58 GMT; domain=.facebook.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "csrftoken=yymkEesbNZEzwrlL42HJeyNmFIghmOf1; secure; expires=Thu, 29-Mar-2018 08:44:59 GMT; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_pr=1; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "ig_vw=1024; domain=www.instagram.com; path=/"
2017-03-30T08:45:17 [DEBUG] CookieJar - Saved "rur=PRN; domain=www.instagram.com; path=/"
==> 2017-03-30T08:45:17 [DEBUG] Network - Resource request error: QNetworkReply::NetworkError(ContentOperationNotPermittedError) ( "Error downloading https://www.instagram.com/explore/locations/213385402/london-united-kingdom/ - server replied: Forbidden" ) URL: "https://www.instagram.com/explore/locations/213385402/london-united-kingdom/"
2017-03-30T08:45:17 [DEBUG] WebPage - updateLoadingProgress: 100
2017-03-30T08:45:17 [DEBUG] WebPage - setupFrame ""
=> {"status"=>"fail"}

Thats my Capybara/Poltergeist setup:

def setup_session
  driver_options = { js_errors: false,
                    logger: NilLogger.new,
                    phantomjs_logger: STDOUT,
                    phantomjs: Phantomjs.path,
                    phantomjs_options: [
                      '--debug=true',
                      '--ignore-ssl-errors=true',
                      '--ssl-protocol=ANY',
                      '--web-security=false',
                      '--local-to-remote-url-access=true'
                    ],
                    debug: false  }

  Capybara.configure do |config|
    config.register_driver :poltergeist do |app|
      driver = Capybara::Poltergeist::Driver.new(app, driver_options)
      driver.headers = { 'User-Agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36" }
      driver
    end

    config.run_server = false
    config.app_host = 'https://appname.herokuapp.com/'
    config.default_driver = :poltergeist
    config.default_max_wait_time = 60
  end

  Capybara.current_session
end


问:
Array returns 43 instances of the same row - CodeIgniter PHP MySQL
We have tables (details omitted):

```<code>project {
    projectID,
    addressID
}

address {
    addressID,
    postcode,
    streetName,
    buildingNumber
}
</code>```

And a query to return the row of the address of the project.

```<code>   $this->db->select('a.postcode, p.projectID, p.addressID');
   $this->db->from('address AS a , project as p');
   $this->db->join('project', 'p.addressID = a.addressID');
   $this->db->where('p.projectID', $projectID);

   /* RETURNS SEVERAL INSTANCES OF THE SAME ROW! ... */

   $projectAddress = $this->db->get()->result_array();
   echo sizeof($projectAddress).' -- ';
   print_r($projectAddress[0]['postcode']);
</code>```

We have checked the database and it only contains the one projectID in the project table and the one address record with that projectID. There absolutely cannot be more addresses per project because we have accounted for this in the database.

Output:

```<code>43 -- PA73 6LT
</code>```

NOTE: we know we can limit the result set to be one row, but we're curious as to why it's returning this arbitrary number - 43.

Cheers!

答:
You duplicate join, try this:</p>

```<code>$this->db->select('a.postcode, project.projectID, project.addressID');
$this->db->from('address AS a');
$this->db->join('project', 'project.addressID = a.addressID');
$this->db->where('project.projectID', $projectID);
</code>```

Body:
We have tables (details omitted):

project {
    projectID,
    addressID
}

address {
    addressID,
    postcode,
    streetName,
    buildingNumber
}

And a query to return the row of the address of the project.

   $this->db->select('a.postcode, p.projectID, p.addressID');
   $this->db->from('address AS a , project as p');
   $this->db->join('project', 'p.addressID = a.addressID');
   $this->db->where('p.projectID', $projectID);

   /* RETURNS SEVERAL INSTANCES OF THE SAME ROW! ... */

   $projectAddress = $this->db->get()->result_array();
   echo sizeof($projectAddress).' -- ';
   print_r($projectAddress[0]['postcode']);

We have checked the database and it only contains the one projectID in the project table and the one address record with that projectID. There absolutely cannot be more addresses per project because we have accounted for this in the database.

Output:

43 -- PA73 6LT

NOTE: we know we can limit the result set to be one row, but we're curious as to why it's returning this arbitrary number - 43.

Cheers!

Body:
You duplicate join, try this:

$this->db->select('a.postcode, project.projectID, project.addressID');
$this->db->from('address AS a');
$this->db->join('project', 'project.addressID = a.addressID');
$this->db->where('project.projectID', $projectID);


问:
Convert value number key to string php?
Here is my code :

```<code> foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$key.'_'.md5(uniqid(rand(), true)).'.png';

    }
</code>```

The key value is incremented, I want to change the key number to a string like:

```<code>if $key=1 i want $key=white
if $key=2 i want $key=black
</code>```

答:
Try this one

```<code>$keys = ['white','black','blue','pink'];
$urlImages = ['photo1','photo2','photo3','photo4'];

print_r($urlImages);
$urlImages= array_combine($keys, array_values($urlImages));

print_r($urlImages);
</code>```

first print_r Array ( [0] => photo1 [1] => photo2 [2] => photo3 [3] => photo4 )

second print_r will return Array ( [white] => photo1 [black] => photo2 [blue] => photo3 [pink] => photo4 )

Title: Convert value number key to string php?

Body:
Here is my code :

 foreach($urlImages as $key => $u){

        $nameImg = $id_product.'_'.$key.'_'.md5(uniqid(rand(), true)).'.png';

    }

The key value is incremented, I want to change the key number to a string like:

if $key=1 i want $key=white
if $key=2 i want $key=black

Body:
Try this one

$keys = ['white','black','blue','pink'];
$urlImages = ['photo1','photo2','photo3','photo4'];

print_r($urlImages);
$urlImages= array_combine($keys, array_values($urlImages));

print_r($urlImages);

first print_r Array ( [0] => photo1 [1] => photo2 [2] => photo3 [3] => photo4 )

second print_r will return Array ( [white] => photo1 [black] => photo2 [blue] => photo3 [pink] => photo4 )


问:
how to continue requesting when first response is not accepted in php?
I am a new for using Guzzle package i want to send data via  web api when response coming with status OK or NOT i do some action  otherwise status equal waiting i request again after 5second or status equal not yet sleep for 30 second.
this is my code

```<code>$client = new Client();
  $headers= [
            'Accept' => 'application/x-www-form-urlencoded',
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];
        $body = [
            'phone2'=>'723457481',
            'amount'=>'200'
        ];
        $url = "http://192.168.31.51:8080/requesttrafic/";

       $response = $client->Request("POST", $url, [
            'handler'  => $stack,
            'headers'=>$headers,
            'form_params'=>$body
        ]);
        $contents = (string) $response->getBody();
       // this $contents can be  status 'ok','not' anything
</code>```

So how can I send again according response status ?
Thanks

答:
if you want to send it again if status is not 'ok' then:

```<code>if($contents!=='ok'){
    $response = $client->Request("POST", $url, [
        'handler'  => $stack,
        'headers'=>$headers,
        'form_params'=>$body
    ]);
    $contents = (string) $response->getBody();
}
</code>```

if by status you meant http status then you can verify that like this:

```<code>$status = $response->getStatusCode();
if($status!==200){
 //your request again
}
</code>```

or maybe i understood your question wrong. In that case please elaborate.

Body:
I am a new for using Guzzle package i want to send data via  web api when response coming with status OK or NOT i do some action  otherwise status equal waiting i request again after 5second or status equal not yet sleep for 30 second.
this is my code

$client = new Client();
  $headers= [
            'Accept' => 'application/x-www-form-urlencoded',
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];
        $body = [
            'phone2'=>'723457481',
            'amount'=>'200'
        ];
        $url = "http://192.168.31.51:8080/requesttrafic/";

       $response = $client->Request("POST", $url, [
            'handler'  => $stack,
            'headers'=>$headers,
            'form_params'=>$body
        ]);
        $contents = (string) $response->getBody();
       // this $contents can be  status 'ok','not' anything

So how can I send again according response status ?
Thanks

Body:
if you want to send it again if status is not 'ok' then:

if($contents!=='ok'){
    $response = $client->Request("POST", $url, [
        'handler'  => $stack,
        'headers'=>$headers,
        'form_params'=>$body
    ]);
    $contents = (string) $response->getBody();
}

if by status you meant http status then you can verify that like this:

$status = $response->getStatusCode();
if($status!==200){
 //your request again
}

or maybe i understood your question wrong. In that case please elaborate.


问:
various div contained in parent div and responsive to parent size
I would like to have all the div(1..7) inside the parent div next to each other and that when the size of the screen changes (portrait,landscape, scale) the organization of the div1..7 is done automatically so that they are always contained in the parent div.

So far I succeeded in:

have a centered parent which is responsive to any screen situation

all the div1..7 inside the parent div (but they are on top of each other)

What I miss:

div1..7 next to each other

div1..7 re-organized/resized automatically when the size of parent div change due to screen change.

html {background: #eee;}
* {padding: 0; margin: 0;}
html, body {height: 100%;text-align: center;}
.container{display: inline-block; vertical-align: middle; margin-top: 10vh; background: rgba(200,200,200,0.5);}
@media screen and (orientation:landscape) {.container {width: 60vw; height: 80vh;}}
@media screen and (orientation:portrait) {.container {width: 80vw; height: 80vh;}}

.div1 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}
.div2 {display: block; background: rgba(0,80,0,0.5); width:200px; height:100px;float:left;}
.div3 {display: block; background: rgba(0,0,80,0.5); width:100px; height:200px;float:left;}
.div4 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}
.div5 {display: block; background: rgba(0,80,0,0.5); width:200px; height:100px;float:left;}
.div6 {display: block; background: rgba(0,0,80,0.5); width:100px; height:200px;float:left;}
.div7 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 <div class="div1"></div>
 <div class="div2"></div>
 <div class="div3"></div>
 <div class="div4"></div>
 <div class="div5"></div>
 <div class="div6"></div>
 <div class="div7"></div>
</div></code>```

答:
the div close tag is missing...

and you can use flexbox in order to put your divbs next to each other

html {background: #eee;}
* {padding: 0; margin: 0;}
html, body {height: 100%;text-align: center;}
.container{display: inline-block; vertical-align: middle; margin-top: 10vh; background: rgba(200,200,200,0.5);
display:flex;}
@media screen and (orientation:landscape) {.container {width: 60vw; height: 80vh;}}
@media screen and (orientation:portrait) {.container {width: 80vw; height: 80vh;}}

.div1 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}
.div2 {display: block; background: rgba(0,80,0,0.5); width:200px; height:100px;float:left;}
.div3 {display: block; background: rgba(0,0,80,0.5); width:100px; height:200px;float:left;}
.div4 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}
.div5 {display: block; background: rgba(0,80,0,0.5); width:200px; height:100px;float:left;}
.div6 {display: block; background: rgba(0,0,80,0.5); width:100px; height:200px;float:left;}
.div7 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 <div class="div1"></div>
 <div class="div2"></div>
 <div class="div3"></div>
 <div class="div4"></div>
 <div class="div5"></div>
 <div class="div6"></div>
 <div class="div7"></div>
</div></code>```

Body:
the div close tag is missing...

and you can use flexbox in order to put your divbs next to each other

html {background: #eee;}
* {padding: 0; margin: 0;}
html, body {height: 100%;text-align: center;}
.container{display: inline-block; vertical-align: middle; margin-top: 10vh; background: rgba(200,200,200,0.5);
display:flex;}
@media screen and (orientation:landscape) {.container {width: 60vw; height: 80vh;}}
@media screen and (orientation:portrait) {.container {width: 80vw; height: 80vh;}}

.div1 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}
.div2 {display: block; background: rgba(0,80,0,0.5); width:200px; height:100px;float:left;}
.div3 {display: block; background: rgba(0,0,80,0.5); width:100px; height:200px;float:left;}
.div4 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}
.div5 {display: block; background: rgba(0,80,0,0.5); width:200px; height:100px;float:left;}
.div6 {display: block; background: rgba(0,0,80,0.5); width:100px; height:200px;float:left;}
.div7 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}

<div class="container">
 <div class="div1"></div>
 <div class="div2"></div>
 <div class="div3"></div>
 <div class="div4"></div>
 <div class="div5"></div>
 <div class="div6"></div>
 <div class="div7"></div>
</div>


问:
Linq to objects List in list
I have a list of movies

```<code>List<Movie> MovieList
</code>```

and I have a list of selected categories

```<code>List<string> SelCat
</code>```

And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get kinda close with linq like so:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.

BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.

How do I achieve this with Linq to Objects?

答:
```<code>var result = from movie in movieList
             where selCat.All(selectedCategory => movie.Categories.Contains(selectedCategory))
             select movie;
</code>```

remember the difference between .All() and .Any()

Title: Linq to objects List in list

Body:
I have a list of movies

List<Movie> MovieList

and I have a list of selected categories

List<string> SelCat

And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get kinda close with linq like so:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.

BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.

How do I achieve this with Linq to Objects?

Body:
var result = from movie in movieList
             where selCat.All(selectedCategory => movie.Categories.Contains(selectedCategory))
             select movie;

remember the difference between .All() and .Any()


问:
Spout is not reading/emitting data in storm cluster mode
I am using apache storm 1.0.0 both in local as well as cluster mode. For the spout, I am reading the data from kafka topic (I am using kafka 2.11-0.8.2.1). Spout is reading the data from kafka topic and also emitting the data when I am using storm in local mode but the storm spout is not emitting any data when I am running storm in cluster mode.

My topology implementation for reading kafka data is as follow:

```<code>brokerHosts = new ZkHosts(kafkaZookeeper);
SpoutConfig kafkaConfig = new SpoutConfig(brokerHosts, kafkaTopicIn, "", "storm");
kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme());
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("spout", new KafkaSpout(kafkaConfig), 2);
</code>```

My storm configuration file (conf/storm.yaml):

```<code>storm.zookeeper.servers:
- "localhost"
storm.zookeeper.port: 2181
nimbus.seeds: ["localhost"]

storm.local.dir: "/tmp/storm"
</code>```

I am also not getting any error while submitting Storm topology in cluster mode.

Any idea why topology spout is not emitting any data in cluster mode ??
Any help would be greatly appreciated.

答:
Thanks all for your valuable suggestion.
It's working now. There was some issue with the log4j logger API version that I was using with storm-1.0.0 topology. This log4j was not causing any issue in local mode but was causing the issue in cluster mode. </p>

Body:
I am using apache storm 1.0.0 both in local as well as cluster mode. For the spout, I am reading the data from kafka topic (I am using kafka 2.11-0.8.2.1). Spout is reading the data from kafka topic and also emitting the data when I am using storm in local mode but the storm spout is not emitting any data when I am running storm in cluster mode.

My topology implementation for reading kafka data is as follow:

brokerHosts = new ZkHosts(kafkaZookeeper);
SpoutConfig kafkaConfig = new SpoutConfig(brokerHosts, kafkaTopicIn, "", "storm");
kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme());
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("spout", new KafkaSpout(kafkaConfig), 2);

My storm configuration file (conf/storm.yaml):

storm.zookeeper.servers:
- "localhost"
storm.zookeeper.port: 2181
nimbus.seeds: ["localhost"]

storm.local.dir: "/tmp/storm"

I am also not getting any error while submitting Storm topology in cluster mode.

Any idea why topology spout is not emitting any data in cluster mode ??
Any help would be greatly appreciated.


问:
Android firebase append existing data with new data
I am new to firebase. I just want to append new data with old data without retriveing data to android eg:-

i want append data to gTopics like add music etc...

答:
I strongly advise you to read Firebase docs about how to read and write your data.
https://firebase.google.com/docs/database/android/read-and-write</p>


问:
Angular2 Material md-icon size
How do I get the icon size to work with the relative size of the font in angular2?</p>

```<code><div style="font-size: 3em;">
<md-icon>highlight</md-icon>
Title
</div>
</code>```

答:
There are two ways to approach this.

You can influence the ligature itself:

```<code><md-icon><h1>highlight</h1></md-icon>
</code>```

This will resize the icon, but it will be influenced by styles set on the header elements (like font-weight). So, I would recommend resizing using CSS:

```<code><md-icon style="font-size:24px">highlight<md-icon>
</code>```

This will resize the icon crisply. You can of course also add classes to do that (which is even better!):

```<code><md-icon class="large">highlight<md-icon>
</code>```

Title: Angular2 Material md-icon size

Body:
How do I get the icon size to work with the relative size of the font in angular2?

<md-icon>highlight</md-icon>
Title

Body:
There are two ways to approach this.

You can influence the ligature itself:

<md-icon><h1>highlight</h1></md-icon>

This will resize the icon, but it will be influenced by styles set on the header elements (like font-weight). So, I would recommend resizing using CSS:

<md-icon style="font-size:24px">highlight<md-icon>

This will resize the icon crisply. You can of course also add classes to do that (which is even better!):

<md-icon class="large">highlight<md-icon>


问:
C# Linq .Find() return many results
I am trying to create a simple search function for my application. I am using Linq's .Find() method to search through a list of objects. It all works very well, the only problem I'm currently having is that I only get the first result. I know for a fact that there are more than one results to be had, but I only get one. Here is my code:

```<code>case 5: {
    //Search for Price

    Product searchResult = tempList.Find(x => x.getPrice() == searchPrice);
    if (searchResult != null) {
        //Present Result
        searchTable.Rows.Add(convertIDValue(searchResult.getProductID()), searchResult.getTitle(), searchResult.getYear(), searchResult.getAmount(), searchResult.getPrice());
    }
    else {
        MessageBox.Show("No product with that price", "0 results");
    }

    break;
}
</code>```

I thought I could change Product searchResult into List<Product> searchResults in order to get a list of Products, then loop through that list. But that gave me an error saying:

Cannot implicitly convert type '.Product' to 'System.Collections.Generic.List<.Product>

Is there any way to get Linq's .Find() to return multiple results?

答:
Use Where() and ToList() to get all objects, matching the condition into a List

replace

```<code>Product searchResult = tempList.Find(x => x.getPrice() == searchPrice);
</code>```

with

```<code>List<Product> searchResult = tempList.Where(x => x.getPrice() == searchPrice).ToList();
</code>```

Title: C# Linq .Find() return many results

Body:
I am trying to create a simple search function for my application. I am using Linq's .Find() method to search through a list of objects. It all works very well, the only problem I'm currently having is that I only get the first result. I know for a fact that there are more than one results to be had, but I only get one. Here is my code:

case 5: {
    //Search for Price

    Product searchResult = tempList.Find(x => x.getPrice() == searchPrice);
    if (searchResult != null) {
        //Present Result
        searchTable.Rows.Add(convertIDValue(searchResult.getProductID()), searchResult.getTitle(), searchResult.getYear(), searchResult.getAmount(), searchResult.getPrice());
    }
    else {
        MessageBox.Show("No product with that price", "0 results");
    }

    break;
}

I thought I could change Product searchResult into List<Product> searchResults in order to get a list of Products, then loop through that list. But that gave me an error saying:

Cannot implicitly convert type '.Product' to 'System.Collections.Generic.List<.Product>

Is there any way to get Linq's .Find() to return multiple results?

Body:
Use Where() and ToList() to get all objects, matching the condition into a List

replace

Product searchResult = tempList.Find(x => x.getPrice() == searchPrice);

with

List<Product> searchResult = tempList.Where(x => x.getPrice() == searchPrice).ToList();