问:
I have issue while automating Odoo application
i am automating Odoo pos application. but while adding product to the cart, i got error like "Element is not clickable at point (659,166)". i have already created 1 item and trying to add that in cart but element is not found. need help.</p>

```<code>      package odoo1;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

public class odoo {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);

        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

        // for Log in functionality
        driver.get("https://www.odoo.com/trial?selected_app=point_of_sale");
        driver.findElement(By.id("username")).sendKeys("mark");
        driver.findElement(By.id("email")).sendKeys("mark@gmail.com");
        driver.findElement(By.id("company-name")).sendKeys("odooo");
        driver.findElement(By.id("phone")).sendKeys("561234897");
        driver.findElement(By.id("country-id")).sendKeys("India");
        driver.findElement(By.name("lang")).sendKeys("English");
        Select sell=new Select(driver.findElement(By.name("company_size")));
        sell.selectByIndex(2);;
        Select sell1=new Select(driver.findElement(By.id("plan")));
        sell1.selectByIndex(2);
        driver.findElement(By.xpath(".//*[@id='wrapwrap']/main/div/div/div[2]/div[2]/div/form/input[8]")).click();

        // for creating product

    driver.findElement(By.xpath("html/body/div[3]/div[3]/div[1]/a[2]/div[2]")).click();
    driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[2]/a")).click();
    driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[2]/ul/li[3]/a/span")).click();
    driver.findElement(By.xpath("html/body/div[3]/div[2]/div[1]/div/button")).click();
    driver.findElement(By.xpath(".//*[@id='o_field_input_4']")).sendKeys("iphone");
    driver.findElement(By.xpath(".//*[@id='o_field_input_4']")).click();
    driver.findElement(By.xpath(".//*[@id='o_field_input_13']")).sendKeys("abcd");
    driver.findElement(By.xpath(".//*[@id='o_field_input_14']")).sendKeys("123456");
    driver.findElement(By.xpath(".//*[@id='o_field_input_15']"));
    driver.findElement(By.xpath(".//*[@id='o_field_input_16']")).clear();
    driver.findElement(By.xpath(".//*[@id='o_field_input_16']")).sendKeys("25000");
    driver.findElement(By.xpath(".//*[@id='o_field_input_20']")).clear();
    driver.findElement(By.xpath(".//*[@id='o_field_input_20']")).sendKeys("25000");
    Thread.sleep(1000);
    driver.findElement(By.xpath("html/body/div[3]/div[2]/div[1]/div/div[2]/button[1]")).click();

    Thread.sleep(900);
    driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[1]/a/span")).click();

    driver.findElement(By.xpath("html/body/div[4]/div/div/div[1]/div[2]/div/div[1]/button")).click();
    Thread.sleep(500);
    driver.findElement(By.xpath("html/body/div[1]/div[2]/div/div[2]/div[1]/div/div/div/div[2]/div[2]/table/tbody/tr[2]/td/div/div/div/div/span[2]/div[1]")).click();

    Thread.sleep(700);
    driver.findElement(By.xpath("//button")).click();

    Thread.sleep(5000);

    driver.findElement(By.xpath("html/body/div[1]/div[2]/div/div[2]/div[1]/div/div/div/div[2]/div[2]/table/tbody/tr[2]/td/div/div/div/div/span[2]/div[1]/img")).click();

   }

    }
</code>```

答:
By looking at the exception, it looks like the right path is not selected.
I have just checked the website which you are trying to automate.

Steps I have followed:

Click on Open Cart tab.

Select Shipping option.

Click on Add to Cart for the product which you want to add in your path.

Xpath Used for Add To Cart button:

//h3[normalize-space()="Opencart Marketplace"]/../div[3]//button

I have selected the product "Opencart Marketplace". You can select any product you want. Just replace Opencart Marketplace with the product which you want to select.

Code:

System.setProperty("webdriver.gecko.driver", "src/geckodriver");

WebDriver driver = new FirefoxDriver();

driver.get("https://store.webkul.com/OpenCart-Modules.html");

Thread.sleep(2);

driver.findElement(By.xpath("//h3[normalize-space()='Opencart Marketplace']/../div[3]//button")).click();

driver.findElement(By.xpath("//div[@class='product_cart_container']/button")).click();

Body:
i am automating Odoo pos application. but while adding product to the cart, i got error like "Element is not clickable at point (659,166)". i have already created 1 item and trying to add that in cart but element is not found. need help.

      package odoo1;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

public class odoo {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);

        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

        // for Log in functionality
        driver.get("https://www.odoo.com/trial?selected_app=point_of_sale");
        driver.findElement(By.id("username")).sendKeys("mark");
        driver.findElement(By.id("email")).sendKeys("mark@gmail.com");
        driver.findElement(By.id("company-name")).sendKeys("odooo");
        driver.findElement(By.id("phone")).sendKeys("561234897");
        driver.findElement(By.id("country-id")).sendKeys("India");
        driver.findElement(By.name("lang")).sendKeys("English");
        Select sell=new Select(driver.findElement(By.name("company_size")));
        sell.selectByIndex(2);;
        Select sell1=new Select(driver.findElement(By.id("plan")));
        sell1.selectByIndex(2);
        driver.findElement(By.xpath(".//*[@id='wrapwrap']/main/div/div/div[2]/div[2]/div/form/input[8]")).click();

        // for creating product

    driver.findElement(By.xpath("html/body/div[3]/div[3]/div[1]/a[2]/div[2]")).click();
    driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[2]/a")).click();
    driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[2]/ul/li[3]/a/span")).click();
    driver.findElement(By.xpath("html/body/div[3]/div[2]/div[1]/div/button")).click();
    driver.findElement(By.xpath(".//*[@id='o_field_input_4']")).sendKeys("iphone");
    driver.findElement(By.xpath(".//*[@id='o_field_input_4']")).click();
    driver.findElement(By.xpath(".//*[@id='o_field_input_13']")).sendKeys("abcd");
    driver.findElement(By.xpath(".//*[@id='o_field_input_14']")).sendKeys("123456");
    driver.findElement(By.xpath(".//*[@id='o_field_input_15']"));
    driver.findElement(By.xpath(".//*[@id='o_field_input_16']")).clear();
    driver.findElement(By.xpath(".//*[@id='o_field_input_16']")).sendKeys("25000");
    driver.findElement(By.xpath(".//*[@id='o_field_input_20']")).clear();
    driver.findElement(By.xpath(".//*[@id='o_field_input_20']")).sendKeys("25000");
    Thread.sleep(1000);
    driver.findElement(By.xpath("html/body/div[3]/div[2]/div[1]/div/div[2]/button[1]")).click();

    Thread.sleep(900);
    driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[1]/a/span")).click();

    driver.findElement(By.xpath("html/body/div[4]/div/div/div[1]/div[2]/div/div[1]/button")).click();
    Thread.sleep(500);
    driver.findElement(By.xpath("html/body/div[1]/div[2]/div/div[2]/div[1]/div/div/div/div[2]/div[2]/table/tbody/tr[2]/td/div/div/div/div/span[2]/div[1]")).click();

    Thread.sleep(700);
    driver.findElement(By.xpath("//button")).click();

    Thread.sleep(5000);

    driver.findElement(By.xpath("html/body/div[1]/div[2]/div/div[2]/div[1]/div/div/div/div[2]/div[2]/table/tbody/tr[2]/td/div/div/div/div/span[2]/div[1]/img")).click();

   }

    }


来源: stackexchange

问:
Facebook redirect url issue OAuthException
My app was working well for long time, but now I am getting the error from Facebook saying:

Content: {"error":{"message":"Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request","type":"OAuthException","code":100}}

https://www.facebook.com/dialog/oauth/?client_id=163840537126360&redirect_uri=http://mycloud.niranjan.com/facebook/callback//empty/?vTitle=Facebook&scope=email,sms,user_about_me,friends_about_me,user_activities,friends_activities,user_birthday,friends_birthday,user_education_history,friends_education_history,user_events,friends_events,user_likes,friends_likes,user_location,friends_location,user_photos,friends_photos,user_videos,friends_videos,user_relationships,friends_relationships,user_status,friends_status,user_checkins,friends_checkins,read_stream,publish_stream

Can anyone suggest a solution for this one?

答:
Mo Hrad A is right, I didn't even manage to use $ character.

I wrote 2 simple functions that allows me to use complex return urls with parameters:

```<code>public static string EncodeFacebookReturnUrl(string url)
{
    return Regex.Replace(HttpUtility.UrlEncode(url), "%", "_-_");
}

public static string DecodeFacebookReturnUrl(string url)
{
    return HttpUtility.UrlDecode(Regex.Replace(url, "_-_", "%"));
}
</code>```

Translating with UrlEncode results in only 1 "illegal" character (%), which I'm replacing with the legal string _-_.
Makes it simple to decode too.

ContentLicense: CC BY-SA 3.0

Body:
Mo Hrad A is right, I didn't even manage to use $ character.

I wrote 2 simple functions that allows me to use complex return urls with parameters:

public static string EncodeFacebookReturnUrl(string url)
{
    return Regex.Replace(HttpUtility.UrlEncode(url), "%", "_-_");
}

public static string DecodeFacebookReturnUrl(string url)
{
    return HttpUtility.UrlDecode(Regex.Replace(url, "_-_", "%"));
}

Translating with UrlEncode results in only 1 "illegal" character (%), which I'm replacing with the legal string _-_.
Makes it simple to decode too.


问:
php DOMXpath, help getting node value
I have this XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante >
<cfdi:Conceptos>
<cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51571 CADENA ORO AMRILLO 45CMTS FAVOR DE SOLDAR EL ESLABON DE LADO DEL BROCHE" valorUnitario="81.90" importe="81.90" />
<cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51570 CADENA ORO BLANCO C/CORAZON FAVOR DE SOLDAR A 16 CMTS DEL BROCHE" valorUnitario="206.90" importe="206.90" />
<cfdi:/Conceptos>
<cfdi:Impuestos>
<cfdi:Traslados>
<cfdi:Traslado impuesto="IVA" tasa="16" importe="46.20" />
</cfdi:Traslados>
</cfdi:Impuestos>
</cfdi:Comprobante>
</code>```

and I need to get the "46.20" value of Traslado / importe. how can I do it? I tried something like this:

```<code>$xp = new DOMXpath($xml);
$data['IVA']= getpath("//@Traslados[@impuesto='IVA']/@importe");
</code>```

but didn't work.

答:
There are a couple of corrections to the XML ( adding the name space and moving the / to the start of <cfdi:/Conceptos>.

In the XML, you have to register the namespace in the xpath object so it can work with it and the xpath expression itself is updated...

```<code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$xml= <<< XML
<?xml version="1.0" encoding="utf-8"?>
<Comprobante xmlns:cfdi="cfdi">
    <cfdi:Conceptos>
        <cfdi:Concepto cantidad="1.00" unidad="PZA"
            noIdentificacion="RRGARACION"
            descripcion="51571 CADENA ORO AMRILLO 45CMTS FAVOR DE SOLDAR EL ESLABON DE LADO DEL BROCHE" valorUnitario="81.90" importe="81.90" />
        <cfdi:Concepto cantidad="1.00" unidad="PZA"
            noIdentificacion="RRGARACION"
            descripcion="51570 CADENA ORO BLANCO C/CORAZON FAVOR DE SOLDAR A 16 CMTS DEL BROCHE" valorUnitario="206.90" importe="206.90" />
    </cfdi:Conceptos>
    <cfdi:Impuestos>
        <cfdi:Traslados>
            <cfdi:Traslado impuesto="IVA" tasa="16" importe="46.20" />
        </cfdi:Traslados>
    </cfdi:Impuestos>
</Comprobante>
XML;

$doc = new DOMDocument();
$doc->loadXML($xml);
$xp = new DOMXpath($doc);
$xp->registerNamespace('cfdi', 'cfdi');
print_r( $xp->query("//cfdi:Traslados/*[@impuesto='IVA']/@importe"));
</code>```

Title: php DOMXpath, help getting node value

Body:
I have this XML:

<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante >
<cfdi:Conceptos>
<cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51571 CADENA ORO AMRILLO 45CMTS FAVOR DE SOLDAR EL ESLABON DE LADO DEL BROCHE" valorUnitario="81.90" importe="81.90" />
<cfdi:Concepto cantidad="1.00" unidad="PZA" noIdentificacion="RRGARACION" descripcion="51570 CADENA ORO BLANCO C/CORAZON FAVOR DE SOLDAR A 16 CMTS DEL BROCHE" valorUnitario="206.90" importe="206.90" />
<cfdi:/Conceptos>
<cfdi:Impuestos>
<cfdi:Traslados>
<cfdi:Traslado impuesto="IVA" tasa="16" importe="46.20" />
</cfdi:Traslados>
</cfdi:Impuestos>
</cfdi:Comprobante>

and I need to get the "46.20" value of Traslado / importe. how can I do it? I tried something like this:

$xp = new DOMXpath($xml);
$data['IVA']= getpath("//@Traslados[@impuesto='IVA']/@importe");

but didn't work.

Body:
There are a couple of corrections to the XML ( adding the name space and moving the / to the start of <cfdi:/Conceptos>.

In the XML, you have to register the namespace in the xpath object so it can work with it and the xpath expression itself is updated...

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$xml= <<< XML
<?xml version="1.0" encoding="utf-8"?>
<Comprobante xmlns:cfdi="cfdi">
    <cfdi:Conceptos>
        <cfdi:Concepto cantidad="1.00" unidad="PZA"
            noIdentificacion="RRGARACION"
            descripcion="51571 CADENA ORO AMRILLO 45CMTS FAVOR DE SOLDAR EL ESLABON DE LADO DEL BROCHE" valorUnitario="81.90" importe="81.90" />
        <cfdi:Concepto cantidad="1.00" unidad="PZA"
            noIdentificacion="RRGARACION"
            descripcion="51570 CADENA ORO BLANCO C/CORAZON FAVOR DE SOLDAR A 16 CMTS DEL BROCHE" valorUnitario="206.90" importe="206.90" />
    </cfdi:Conceptos>
    <cfdi:Impuestos>
        <cfdi:Traslados>
            <cfdi:Traslado impuesto="IVA" tasa="16" importe="46.20" />
        </cfdi:Traslados>
    </cfdi:Impuestos>
</Comprobante>
XML;

$doc = new DOMDocument();
$doc->loadXML($xml);
$xp = new DOMXpath($doc);
$xp->registerNamespace('cfdi', 'cfdi');
print_r( $xp->query("//cfdi:Traslados/*[@impuesto='IVA']/@importe"));


问:
Need to call gtk_init function, but not from main function - C++
Im using GTK3 to create something. In tutorials there is

```<code>#include <gtk/gtk.h>
int main(int argc, char* argv[])
{
    GtkWidget *window;
    gtk_init(&argc, &argv);

gtk_window, gtk_container etc...
</code>```

I want to create MainProgram that will be handling the drawings outside this main function. So I delete the code above and make a new one:

main.cpp

```<code>#include "MainProgram.h"
int main(int argc, char* argv[])
{
    MainProgram mainProgram;
    mainProgram.run(); // the magic is now happening inside this run method
</code>```

MainProgram.h

```<code>#include <gtk/gtk.h>
#include "MainProgram.h"
class MainProgram
{
public:
    MainProgram();
    ~MainProgram();

    void run();

    void initSystems();
...other not so important code goes inside
</code>```

finally, the MainProgram.cpp

```<code>#include "MainProgram.h"

MainProgram::MainProgram()
{
...
}

MainProgram::~MainProgram(){}

void MainProgram::run()
{
// about that magic we were talking about
    initSystems();
}

void MainProgram::initSystems(){

    gtk_init(&argc, &argv); // here it is.

    _window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

    gtk_window_set_position(GTK_WINDOW(_window), GTK_WIN_POS_CENTER);
    gtk_window_set_default_size(GTK_WINDOW(_window), _screenWidth, _screenHeigth);
    gtk_window_set_title(GTK_WINDOW(_window), "Fill & stroke");
    // ************** FIX OF THE PROBLEM
    gtk_widget_show_all(_window); // DIDNT CALL
    gtk_main();                   // These two functions
}
</code>```

Now when I do try and compile the program with:

```<code>g++ main.cpp MainProgram.cpp `pkg-config --cflags --libs gtk+-3.0`
</code>```

I get the following warning:

```<code>MainProgram.cpp: In member function ‘void MainProgram::initSystems()’:
MainProgram.cpp:22:12: error: ‘argc’ was not declared in this scope
  gtk_init(&argc, &argv);
            ^
MainProgram.cpp:22:19: error: ‘argv’ was not declared in this scope
  gtk_init(&argc, &argv);
</code>```

Is there a simple way to pass those addresses from main function from main.cpp inside this? Im doing this to make my code look cleaner and trying not to overload the main.cpp file  :)

答: I forgot to put two functions to display my app, you can see in MainProgram.cpp file, I made markings. Its last few lines in that 'file'.</p>

Body:
Im using GTK3 to create something. In tutorials there is

#include <gtk/gtk.h>
int main(int argc, char* argv[])
{
    GtkWidget *window;
    gtk_init(&argc, &argv);

gtk_window, gtk_container etc...

I want to create MainProgram that will be handling the drawings outside this main function. So I delete the code above and make a new one:

main.cpp

#include "MainProgram.h"
int main(int argc, char* argv[])
{
    MainProgram mainProgram;
    mainProgram.run(); // the magic is now happening inside this run method

MainProgram.h

#include <gtk/gtk.h>
#include "MainProgram.h"
class MainProgram
{
public:
    MainProgram();
    ~MainProgram();

    void run();

    void initSystems();
...other not so important code goes inside

finally, the MainProgram.cpp

#include "MainProgram.h"

MainProgram::MainProgram()
{
...
}

MainProgram::~MainProgram(){}

void MainProgram::run()
{
// about that magic we were talking about
    initSystems();
}

void MainProgram::initSystems(){

    gtk_init(&argc, &argv); // here it is.

    _window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

    gtk_window_set_position(GTK_WINDOW(_window), GTK_WIN_POS_CENTER);
    gtk_window_set_default_size(GTK_WINDOW(_window), _screenWidth, _screenHeigth);
    gtk_window_set_title(GTK_WINDOW(_window), "Fill & stroke");
    // ************** FIX OF THE PROBLEM
    gtk_widget_show_all(_window); // DIDNT CALL
    gtk_main();                   // These two functions
}

Now when I do try and compile the program with:

g++ main.cpp MainProgram.cpp `pkg-config --cflags --libs gtk+-3.0`

I get the following warning:

MainProgram.cpp: In member function ‘void MainProgram::initSystems()’:
MainProgram.cpp:22:12: error: ‘argc’ was not declared in this scope
  gtk_init(&argc, &argv);
            ^
MainProgram.cpp:22:19: error: ‘argv’ was not declared in this scope
  gtk_init(&argc, &argv);

Is there a simple way to pass those addresses from main function from main.cpp inside this? Im doing this to make my code look cleaner and trying not to overload the main.cpp file  :)


问:
Why does my loop use 100% CPU and never end?
I have this method:

```<code>    private delegate void watcherReader(StreamReader sr);
    private void watchProc(StreamReader sr) {
        while (true) {
            string line = sr.ReadLine();
            while (line != null) {
                if (stop) {
                    return;
                }
                //Console.WriteLine(line);
                line = stripColors(line);
                txtOut.Text += line + "\n";

                line = sr.ReadLine();
            }
        }
    }
</code>```

And it reads the streams from a Process (cmd.exe). When the user closes the cmd.exe window, it causes the CPU usage to jump to 100%. When playing with the debugger I see that it stops on the sr.ReadLine() and never returns. Because this is watching both the StandardErrorStream and the StandardOutputStream it uses 100% on both cores.

Here's some more code of the project if you need it.

```<code>    [DllImport("User32")]
    private static extern int ShowWindow(int hwnd, int nCmdShow);   //this will allow me to hide a window

    public ConsoleForm(Process p) {
        this.p = p;
        p.Start();
        ShowWindow((int)p.MainWindowHandle, 0);   //0 means to hide the window.

        this.inStream = p.StandardInput;
        this.outStream = p.StandardOutput;
        this.errorStream = p.StandardError;

        InitializeComponent();

        wr = new watcherReader(watchProc);
        wr.BeginInvoke(this.outStream, null, null);
        wr.BeginInvoke(this.errorStream, null, null);
    }

    public void start(string[] folders, string serverPath) {

        this.inStream.WriteLine("chdir C:\\cygwin\\bin");
        this.inStream.WriteLine("bash --login -i");
        this.inStream.WriteLine("");
    }

    //code example from http://geekswithblogs.net/Waynerds/archive/2006/01/29/67506.aspx it is
    //to make the textbox autoscroll I don't understand what it does, but it works.
    #region autoscroll
    [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    const int WM_VSCROLL = 277;
    const int SB_BOTTOM = 7;

    private void txtOut_TextChanged(object sender, EventArgs e) {
        IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
        IntPtr ptrLparam = new IntPtr(0);
        SendMessage(((RichTextBox)sender).Handle, WM_VSCROLL, ptrWparam, ptrLparam);
    }
    #endregion

    private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
        this.stop = true;
        try {
            this.p.Kill();
        } catch (InvalidOperationException) {
            return;
        }
    }
</code>```

Another interesting this is that it doesn't always hide the cmd window like it's supposed to. It hides it the first time, and then the second (or after) it won't hide it. This is when the user can close the cmd.exe window and cause the readline to act funny. It also never reads the last line outputted to cmd unless it exits.

Any suggestions on how to fix this?

答: Whenever you have a while(true) loop in your code you're going to peg your cpu (or at least one core) at 100%, unless you also have a way to break out of the loop.  In your case, you do have a return statement, but at no point in the loop do you ever do anything to the stop variable guarding it.

OwnerDisplayName: Malfist

ContentLicense: CC BY-SA 2.5

Body:
I have this method:

    private delegate void watcherReader(StreamReader sr);
    private void watchProc(StreamReader sr) {
        while (true) {
            string line = sr.ReadLine();
            while (line != null) {
                if (stop) {
                    return;
                }
                //Console.WriteLine(line);
                line = stripColors(line);
                txtOut.Text += line + "\n";

                line = sr.ReadLine();
            }
        }
    }

And it reads the streams from a Process (cmd.exe). When the user closes the cmd.exe window, it causes the CPU usage to jump to 100%. When playing with the debugger I see that it stops on the sr.ReadLine() and never returns. Because this is watching both the StandardErrorStream and the StandardOutputStream it uses 100% on both cores.

Here's some more code of the project if you need it.

    [DllImport("User32")]
    private static extern int ShowWindow(int hwnd, int nCmdShow);   //this will allow me to hide a window

    public ConsoleForm(Process p) {
        this.p = p;
        p.Start();
        ShowWindow((int)p.MainWindowHandle, 0);   //0 means to hide the window.

        this.inStream = p.StandardInput;
        this.outStream = p.StandardOutput;
        this.errorStream = p.StandardError;

        InitializeComponent();

        wr = new watcherReader(watchProc);
        wr.BeginInvoke(this.outStream, null, null);
        wr.BeginInvoke(this.errorStream, null, null);
    }

    public void start(string[] folders, string serverPath) {

        this.inStream.WriteLine("chdir C:\\cygwin\\bin");
        this.inStream.WriteLine("bash --login -i");
        this.inStream.WriteLine("");
    }

    //code example from http://geekswithblogs.net/Waynerds/archive/2006/01/29/67506.aspx it is
    //to make the textbox autoscroll I don't understand what it does, but it works.
    #region autoscroll
    [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    const int WM_VSCROLL = 277;
    const int SB_BOTTOM = 7;

    private void txtOut_TextChanged(object sender, EventArgs e) {
        IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
        IntPtr ptrLparam = new IntPtr(0);
        SendMessage(((RichTextBox)sender).Handle, WM_VSCROLL, ptrWparam, ptrLparam);
    }
    #endregion

    private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
        this.stop = true;
        try {
            this.p.Kill();
        } catch (InvalidOperationException) {
            return;
        }
    }

Another interesting this is that it doesn't always hide the cmd window like it's supposed to. It hides it the first time, and then the second (or after) it won't hide it. This is when the user can close the cmd.exe window and cause the readline to act funny. It also never reads the last line outputted to cmd unless it exits.

Any suggestions on how to fix this?

LastEditorDisplayName: Rich B

OwnerDisplayName: Joel Coehoorn


问:
php array from checkbox into mysql
I found some code to help me with an issue I was having..it is so that if a form does not pass validation, it will retain my checkbox selections. Now I am wondering how do I get the selections in a form that i can put in mysql ?
in my form

```<?php

$a = array("1*","2*","3*","4*","5*+");

foreach($a as $key => $value)
{
    echo `"<input type='checkbox' name='rating[]' value='$value' `";

    if(is_array($_POST['rating']) && in_array($value,$_POST['rating']))
        echo " checked ";

    echo ">$value";
}
?>

<INPUT TYPE="SUBMIT" name="submitted" VALUE="Submit" class="submit">
</form>
</code>
</code>```

答:
Is this what you were asking for?

```<code>foreach($_POST['rating'] as $checked_value)
{
    //do what you want to do with here like INSERT or UPDATE
    echo $checked_value.'<br />';
}
</code>```

EDIT:
Perhaps too this will help if you are looking to do arithmetic or analysis on the ratings

```<code>    $a = array( "1" => "1*", "2" => "2*", "3" => "3*", "4" => "4*", "5" => "5*+");

    foreach($a as $key => $value)
    {
        echo '<input type="checkbox" name="rating[]" value="'.$key.'"';

    /* replaced
        if(is_array($_POST['rating']) && in_array($value,$_POST['rating']))
    with below */
        if(is_array($_POST['rating']) && in_array($key,$_POST['rating']))
            echo " checked ";

        echo " />$value";
    }
</code>```

Not sure as to your implementation of this code but are you sure a checkbox is the correct input type?  Perhaps a radio button would be better as users could only choose 1 rating.  As it is currently set up, a user could choose 1, 3, and 5 as their rating.

Title: php array from checkbox into mysql

Body:
I found some code to help me with an issue I was having..it is so that if a form does not pass validation, it will retain my checkbox selections. Now I am wondering how do I get the selections in a form that i can put in mysql ?
in my form

<?php

$a = array("1*","2*","3*","4*","5*+");

foreach($a as $key => $value)
{
    echo `"<input type='checkbox' name='rating[]' value='$value' `";

    if(is_array($_POST['rating']) && in_array($value,$_POST['rating']))
        echo " checked ";

    echo ">$value";
}
?>

<INPUT TYPE="SUBMIT" name="submitted" VALUE="Submit" class="submit">
</form>

Body:
Is this what you were asking for?

foreach($_POST['rating'] as $checked_value)
{
    //do what you want to do with here like INSERT or UPDATE
    echo $checked_value.'<br />';
}

EDIT:
Perhaps too this will help if you are looking to do arithmetic or analysis on the ratings

    $a = array( "1" => "1*", "2" => "2*", "3" => "3*", "4" => "4*", "5" => "5*+");

    foreach($a as $key => $value)
    {
        echo '<input type="checkbox" name="rating[]" value="'.$key.'"';

    /* replaced
        if(is_array($_POST['rating']) && in_array($value,$_POST['rating']))
    with below */
        if(is_array($_POST['rating']) && in_array($key,$_POST['rating']))
            echo " checked ";

        echo " />$value";
    }

Not sure as to your implementation of this code but are you sure a checkbox is the correct input type?  Perhaps a radio button would be better as users could only choose 1 rating.  As it is currently set up, a user could choose 1, 3, and 5 as their rating.


问:
Cannot read property of "undefined" even though the object IS defined! [React]
I am trying to generate the markup for a dropdown menu that will allow users to change the language/locale of the site.

But my component will not render because the browser is telling me the object (language) I'm trying to pull country names (locales) off of is undefined.

What I don't understand is that when I console log that same language object and the key that I'm passing to it (selectedLang) in the lines above, they both print out just fine.

Here is my code:

```<code>compileAvailableLocales() {
        let locales = availableLangs;
        let selectedLang = this.props.lang;
        console.log("selectedLang: ", selectedLang, typeof selectedLang);
        console.log("availableLangs: ", availableLangs);
        console.log("language: ", language);

        let markup = locales.map( (loc) => {
            let readableName = language[ selectedLang ].navigation.locales[ loc ];

            return (
                <li
                  key={ loc }
                  value={ loc }
                  onMouseDown={ this.handleLangChange }>
                    { readableName }
                </li>
            );
        });

        return markup;
    }
</code>```

I think the problem may be the way that I am importing the language object from my essential_lang.js file.

I'm importing into the index.jsx file (see code above) with this line:

```<code>import { language } from '../../constants/essential_lang'
</code>```

And here is some of the code from that file:

```<code>   export const language = {
    'de_de': {
        footer: {
            links: [
                {
                    title: 'KUNDENSERVICE',
                    endpoint: 'mailto:kundenservice@spinmaster.com'
                },
                {
                    title: 'Datenschutz',
                    endpoint: '/de_de/privacy'
                },
                {
                    title: 'Impressum und Allgemeine Geschäftsbedingungen',
                    endpoint: '/de_de/terms'
                }
            ],
            copyright: 'Spin Master Ltd. All Rights Reserved.'
        },
        fourohfour: {
            heading: 'Oh Noes!',
            message: 'This page doesn\'t exist.',
            gohome: 'Back Home'
        },
        loading: "Loading",
        navigation: {
            menuitems: [
                {
                    title: 'Videos',
                    endpoint: '/de_de/videos/'
                },
                {
                    title: 'Colleggtibles',
                    endpoint: '/de_de/colleggtibles'
                },
                {
                    title: 'Produkte',
                    endpoint: '/de_de/toys/'
                },
                {
                    title: 'Hilfe/Häufig gestellte Fragen',
                    endpoint: 'https://spinmastersupport.helpshift.com/a/hatchimals/?p=web&l=de'
                },
                {
                    title: 'Eltern',
                    endpoint: '/de_de/parents/'
                },
                {
                    title: 'Spiele',
                    endpoint: '/de_de/activities/'
                },
                {
                    title: 'Wo erhältlich',
                    endpoint: '/de_de/where-to-buy/'
                }
            ],
            locales: {
                de_de: 'Deutschland',
                en_au: 'Australia',
                en_ca: 'Canada',
                en_uk: 'United Kingdom',
                en_us: 'United States',
                es_es: 'España',
                es_mx: 'México',
                fr_fr: 'France',
                it_it: 'Italia',
                nl_nl: 'Dutch',
                tr_tr: 'Türkiye'
            }
        }
    },
    'en_au': { ...
</code>```

Here is output for the console.logs:

答:
Is it as simple as returning a string?

```<code>return "
            <li
              key={ loc }
              value={ loc }
              onMouseDown={ this.handleLangChange }>
                { readableName }
            </li>
        ";
</code>```

Difficult without seeing all the code.

Body:
I am trying to generate the markup for a dropdown menu that will allow users to change the language/locale of the site.

But my component will not render because the browser is telling me the object (language) I'm trying to pull country names (locales) off of is undefined.

What I don't understand is that when I console log that same language object and the key that I'm passing to it (selectedLang) in the lines above, they both print out just fine.

Here is my code:

compileAvailableLocales() {
        let locales = availableLangs;
        let selectedLang = this.props.lang;
        console.log("selectedLang: ", selectedLang, typeof selectedLang);
        console.log("availableLangs: ", availableLangs);
        console.log("language: ", language);

        let markup = locales.map( (loc) => {
            let readableName = language[ selectedLang ].navigation.locales[ loc ];

            return (

                    { readableName }

            );
        });

        return markup;
    }

I think the problem may be the way that I am importing the language object from my essential_lang.js file.

I'm importing into the index.jsx file (see code above) with this line:

import { language } from '../../constants/essential_lang'

And here is some of the code from that file:

   export const language = {
    'de_de': {
        footer: {
            links: [
                {
                    title: 'KUNDENSERVICE',
                    endpoint: 'mailto:kundenservice@spinmaster.com'
                },
                {
                    title: 'Datenschutz',
                    endpoint: '/de_de/privacy'
                },
                {
                    title: 'Impressum und Allgemeine Geschäftsbedingungen',
                    endpoint: '/de_de/terms'
                }
            ],
            copyright: 'Spin Master Ltd. All Rights Reserved.'
        },
        fourohfour: {
            heading: 'Oh Noes!',
            message: 'This page doesn\'t exist.',
            gohome: 'Back Home'
        },
        loading: "Loading",
        navigation: {
            menuitems: [
                {
                    title: 'Videos',
                    endpoint: '/de_de/videos/'
                },
                {
                    title: 'Colleggtibles',
                    endpoint: '/de_de/colleggtibles'
                },
                {
                    title: 'Produkte',
                    endpoint: '/de_de/toys/'
                },
                {
                    title: 'Hilfe/Häufig gestellte Fragen',
                    endpoint: 'https://spinmastersupport.helpshift.com/a/hatchimals/?p=web&l=de'
                },
                {
                    title: 'Eltern',
                    endpoint: '/de_de/parents/'
                },
                {
                    title: 'Spiele',
                    endpoint: '/de_de/activities/'
                },
                {
                    title: 'Wo erhältlich',
                    endpoint: '/de_de/where-to-buy/'
                }
            ],
            locales: {
                de_de: 'Deutschland',
                en_au: 'Australia',
                en_ca: 'Canada',
                en_uk: 'United Kingdom',
                en_us: 'United States',
                es_es: 'España',
                es_mx: 'México',
                fr_fr: 'France',
                it_it: 'Italia',
                nl_nl: 'Dutch',
                tr_tr: 'Türkiye'
            }
        }
    },
    'en_au': { ...

Here is output for the console.logs:

Body:
Is it as simple as returning a string?

return "
            <li
              key={ loc }
              value={ loc }
              onMouseDown={ this.handleLangChange }>
                { readableName }
            </li>
        ";

Difficult without seeing all the code.


问:
Css positioning button at center of Overlay with image in background

.msg-ex {
  display: flex;
  align-items: center;
  justify-content: center;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

.msg-ex .msg-ex-overlay {
  position: relative;
  background-color: rgba(0, 0, 0, 0.4);
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 2;
}

.msg-ex .msg-ex-overlay .msg-ex-cta {
  position: absolute;
  color: red;
  background-color: #DCE0E3;
  font-size: 1.1em;
  font-weight: 700;
  border-radius: 18px;
  height: 38px;
  width: 100px;
  cursor: pointer;
  top: 50%;
  left: 50%;
  transform: translateX(-48%) translateY(-47%);
}

.msg-ex .msg-ex-overlay:hover {
  opacity: 1;
}

.msg-ex-box {
  position: relative;
  background-color: $voiceColor;
}

.msg-ex-box::after {
  content: '';
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background-image: url(../pics/data/img1.png);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  z-index: 1;
}

}
.msg-ex-voice:hover {
  background-color: rgba(0, 0, 0, 0.4);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="msg-ex msg-ex-box">
  <div class="msg-ex-overlay">
    <button class="msg-ex-cta">Show</button>
  </div>
</div></code>```

I am positioning my "Show" button at the center using transform: translateX(-48%) translateY(-47%); but ideally it should be transform: translateX(50%) translateY(50%); which centers it - cannot figure out what I am doing wrong. Please help.

答:
That's because the parent elements of .msg-ex-cta don't have a height. When you used height: 100%; for .msg-ex-overlay that percentage height needs a value to inherit from, no height is defined for it's parent so 100% of 0 is 0.

While adding width: 100vw; and height: 100vh; to .msg-ex-overlay likely gets you what you want, there's a chance that how the modal/overlay is being triggered might need to change. Though I'm not privy to your exact goals so I'll leave it as is until further notice.

body {
  margin: 0;
}

.msg-ex {
  display: flex;
  align-items: center;
  justify-content: center;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

.msg-ex .msg-ex-overlay {
  position: relative;
  background-color: rgba(0, 0, 0, 0.4);
  width: 100vw;
  height: 100vh;
  opacity: 0;
  z-index: 2;
}

.msg-ex .msg-ex-overlay .msg-ex-cta {
  position: absolute;
  color: red;
  background-color: #DCE0E3;
  font-size: 1.1em;
  font-weight: 700;
  border-radius: 18px;
  height: 38px;
  width: 100px;
  cursor: pointer;
  top: 50%;
  left: 50%;
  transform: translateX(-48%) translateY(-47%);
}

.msg-ex .msg-ex-overlay:hover {
  opacity: 1;
}

.msg-ex-box {
  position: relative;
  background-color: $voiceColor;
}

.msg-ex-box::after {
  content: '';
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background-image: url(../pics/data/img1.png);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  z-index: 1;
}

}
.msg-ex-voice:hover {
  background-color: rgba(0, 0, 0, 0.4);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="msg-ex msg-ex-box">
  <div class="msg-ex-overlay">
    <button class="msg-ex-cta">Show</button>
  </div>
</div></code>```

Body:
.msg-ex {
  display: flex;
  align-items: center;
  justify-content: center;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

.msg-ex .msg-ex-overlay {
  position: relative;
  background-color: rgba(0, 0, 0, 0.4);
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 2;
}

.msg-ex .msg-ex-overlay .msg-ex-cta {
  position: absolute;
  color: red;
  background-color: #DCE0E3;
  font-size: 1.1em;
  font-weight: 700;
  border-radius: 18px;
  height: 38px;
  width: 100px;
  cursor: pointer;
  top: 50%;
  left: 50%;
  transform: translateX(-48%) translateY(-47%);
}

.msg-ex .msg-ex-overlay:hover {
  opacity: 1;
}

.msg-ex-box {
  position: relative;
  background-color: $voiceColor;
}

.msg-ex-box::after {
  content: '';
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background-image: url(../pics/data/img1.png);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  z-index: 1;
}

}
.msg-ex-voice:hover {
  background-color: rgba(0, 0, 0, 0.4);
}

    <button class="msg-ex-cta">Show</button>

I am positioning my "Show" button at the center using transform: translateX(-48%) translateY(-47%); but ideally it should be transform: translateX(50%) translateY(50%); which centers it - cannot figure out what I am doing wrong. Please help.

Body:
That's because the parent elements of .msg-ex-cta don't have a height. When you used height: 100%; for .msg-ex-overlay that percentage height needs a value to inherit from, no height is defined for it's parent so 100% of 0 is 0.

While adding width: 100vw; and height: 100vh; to .msg-ex-overlay likely gets you what you want, there's a chance that how the modal/overlay is being triggered might need to change. Though I'm not privy to your exact goals so I'll leave it as is until further notice.

body {
  margin: 0;
}

.msg-ex {
  display: flex;
  align-items: center;
  justify-content: center;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

.msg-ex .msg-ex-overlay {
  position: relative;
  background-color: rgba(0, 0, 0, 0.4);
  width: 100vw;
  height: 100vh;
  opacity: 0;
  z-index: 2;
}

.msg-ex .msg-ex-overlay .msg-ex-cta {
  position: absolute;
  color: red;
  background-color: #DCE0E3;
  font-size: 1.1em;
  font-weight: 700;
  border-radius: 18px;
  height: 38px;
  width: 100px;
  cursor: pointer;
  top: 50%;
  left: 50%;
  transform: translateX(-48%) translateY(-47%);
}

.msg-ex .msg-ex-overlay:hover {
  opacity: 1;
}

.msg-ex-box {
  position: relative;
  background-color: $voiceColor;
}

.msg-ex-box::after {
  content: '';
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background-image: url(../pics/data/img1.png);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  z-index: 1;
}

}
.msg-ex-voice:hover {
  background-color: rgba(0, 0, 0, 0.4);
}

<div class="msg-ex msg-ex-box">
  <div class="msg-ex-overlay">
    <button class="msg-ex-cta">Show</button>
  </div>
</div>


问:
Unescaped left brace in regex is deprecated, passed through in regex;
I am trying to write a program to find the sum of a list using recursion in python and my code is this

```<code>value = 0

def sum_list(alist):
    global value
    if len(alist) == 0:
        return value
    value += alist.pop()
    return sum_list(alist)

print sum_list(range(10))
</code>```

But when i am executing this script I am getting a weired error.

```<code>Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/%{ <-- HERE (.*?)}/ at /usr/bin/print line 528.
Error: no "print" mailcap rules found for type "text/x-python"
</code>```

I searched for it but couldn't get why this error is coming.
Help will be appreciated

答:
The error message comes from Perl. No idea how you managed to call it with this Python code.

6 years later ...

As it turned out did the OP call print instead of python (look into the error message)

And /usr/bin/print is a Perl script, at least on Ubuntu.

Body:
I am trying to write a program to find the sum of a list using recursion in python and my code is this

value = 0

def sum_list(alist):
    global value
    if len(alist) == 0:
        return value
    value += alist.pop()
    return sum_list(alist)

print sum_list(range(10))

But when i am executing this script I am getting a weired error.

Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/%{ <-- HERE (.*?)}/ at /usr/bin/print line 528.
Error: no "print" mailcap rules found for type "text/x-python"

I searched for it but couldn't get why this error is coming.
Help will be appreciated

ContentLicense: CC BY-SA 4.0


问:
One liner for extend loop python
I have the following code lines:

```<code>records = []

for future in futures:
  records.extends(future.result())
</code>```

each future returns a list.

How can I write the above code but in one liner?

```<code>records = [future.result() for future in futures]
</code>```

would result in a list inside list.

I have millions of records, i would rather not flat it after creating lists inside list

答:
```<code>records = [r for future in futures for r in future.result()]
</code>```

Title: One liner for extend loop python

Body:
I have the following code lines:

records = []

for future in futures:
  records.extends(future.result())

each future returns a list.

How can I write the above code but in one liner?

records = [future.result() for future in futures]

would result in a list inside list.

I have millions of records, i would rather not flat it after creating lists inside list


问:
Implementing drag and drop for TreeView nodes in Avalonia
How to implement drag and drop behavior in TreeView control? An example would be a file explorer where user can move file from one folder to another by dragging.

I have the following code in my XAML:

```<code><TreeView Items="{Binding RootFiles}">
   <TreeView.ItemTemplate>
     <TreeDataTemplate ItemsSource="{Binding Files}">
         <TextBlock Text="{Binding Name}"/>
     </TreeDataTemplate>
   </TreeView.ItemTemplate>
</TreeView>
</code>```

How do I make the nodes draggable?

答:
We don't have a proper drag-n-drop support yet, unfortunately, so you have to implement it manually.

I'll describe how I did something similar with adaptations for your case.

You can handle mouse events on TreeView control level. When MouseDown fires, you need to check PointerOverElement property to detect if mouse is currently inside one of the nodes of the tree (use Parent property to traverse the tree or simply check DataContext), if it is, you need to save said node somewhere.
When MouseMove event fires when one of mouse buttons is pressed, you need to capture mouse and from this point your code is in "drag" state. You can change TreeView's Cursor property to provide some feedback to the user
When MouseUp is triggered, you need to detect the position of the cursor relatively to other nodes and make changes in the model backing TreeView accordingly.

Body:
How to implement drag and drop behavior in TreeView control? An example would be a file explorer where user can move file from one folder to another by dragging.

I have the following code in my XAML:

<TreeView Items="{Binding RootFiles}">
   <TreeView.ItemTemplate>
     <TreeDataTemplate ItemsSource="{Binding Files}">
         <TextBlock Text="{Binding Name}"/>
     </TreeDataTemplate>
   </TreeView.ItemTemplate>
</TreeView>

How do I make the nodes draggable?


问:
Check if SQL Connection is Open or Closed
How do you check if it is open or closed I was using

```<code> if (SQLOperator.SQLCONNECTION.State.Equals("Open"))
</code>```

however, even the State is 'Open' it fails on this check.

答:
This code is a little more defensive, before opening a connection, check state.
If connection state is Broken then we should try to close it. Broken means that the connection was previously opened and not functioning correctly.
The second condition determines that connection state must be closed before attempting to open it again so the code can be called repeatedly.</p>

```<code>// Defensive database opening logic.

if (_databaseConnection.State == ConnectionState.Broken) {
    _databaseConnection.Close();
}

if (_databaseConnection.State == ConnectionState.Closed) {
    _databaseConnection.Open();
}
</code>```

Body:
How do you check if it is open or closed I was using

 if (SQLOperator.SQLCONNECTION.State.Equals("Open"))

however, even the State is 'Open' it fails on this check.

Body:
This code is a little more defensive, before opening a connection, check state.
If connection state is Broken then we should try to close it. Broken means that the connection was previously opened and not functioning correctly.
The second condition determines that connection state must be closed before attempting to open it again so the code can be called repeatedly.

// Defensive database opening logic.

if (_databaseConnection.State == ConnectionState.Broken) {
    _databaseConnection.Close();
}

if (_databaseConnection.State == ConnectionState.Closed) {
    _databaseConnection.Open();
}


问:
c# messenger, send commands over network, protocol?
I'm making a c# messenger application just for fun, but I wanna do it good.
I want the possibility to send commands like a chat message, kick comand etc, but i dont know a good way to control it.

I could send an object over the networkstream, or I could send a string like: stream.write("command##");

maybe you know another way to fix this things, but I'm in stackoverflow atm.
Thanks.

答:
Just have some sort of control character (like ) ... when the server sees that character, it starts to record until it receives a space character. Once it hits the space, it looks at the string and compares it against a list of available commands (\kick, etc.).

That's but one technique to tackle this problem. Honestly, if you're doing it for fun, implement it whatever way is the most fun to code :-)


问:
how to get same geo code for an address which is in bing map through bing map API?
I have an address which shows correct correct place in bingmap. When I request geo code for same address using Unstructured URL API, it sends different geo location

address:
86 Oakleaf Dr Meadow Valley, CA 95956

when I request through bing map api

https://dev.virtualearth.net/REST/v1/Locations?CountryRegion=us&adminDistrict=CA&locality=Meadow%20Valley&postalCode=95956&addressLine=86%20Oakleaf%20Dr&output=json&key=BingmapKey

It result somewhere here

am I missing anything in API request? (I have valid bing key)

答:
```<code>https://dev.virtualearth.net/REST/v1/Locations?CountryRegion=us&adminDistrict=CA&locality=Meadow%20Valley&postalCode=95956&addressLine=86%20Oakleaf%20Dr.&output=json&key=BingMapsKey
</code>```

<p>What you have seems right, I just added a period after the 'Dr' and it changed it to the correct location you wanted. </p>

Body:
https://dev.virtualearth.net/REST/v1/Locations?CountryRegion=us&adminDistrict=CA&locality=Meadow%20Valley&postalCode=95956&addressLine=86%20Oakleaf%20Dr.&output=json&key=BingMapsKey

What you have seems right, I just added a period after the 'Dr' and it changed it to the correct location you wanted.


问:
PHP array_map not returning resultant array
I am trying to replace an array value's spacing with hypen and then recollect back all values of the same array but with hypen in spaces.

INPUT:

```<code>$gFontsList = array("-1", "Agency FB", "28", "Aharoni Bold", "Bookshelf Symbol", "100", "Bookshelf Symbol", "111", "Browallia New Bol");

function toReplaceSpacing($gFontsListValues, $gFontsListIndex){
   if (gettype($gFontsListValues) === 'string'){
      if(preg_match('/ /',$gFontsListValues)){
        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
        $gFontsChoiceOrder[] = $gFontsListValues;
      }
    } else {
      $gFontsChoiceOrder[] = $gFontsListValues;
    }
}
$gFontsChoiceOrder = array_map('toReplaceSpacing',$gFontsList);
print_r($gFontsChoiceOrder);
</code>```

If I print it's just NULL. I don't know Why I am not getting resultant array?.

答:
Remove that second parameter $gFontsListIndex and then just return a value gFontsListValues.

```<code>$gFontsList = array("-1", "Agency FB", "28", "Aharoni Bold", "Bookshelf Symbol", "100", "Bookshelf Symbol", "111", "Browallia New Bol");

function toReplaceSpacing($gFontsListValues){

   $gFontsChoiceOrder = array();

   if (gettype($gFontsListValues) === 'string'){

      if(preg_match('/ /',$gFontsListValues)){

        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
      }
   }

   return $gFontsListValues;
}

$gFontsChoiceOrder = array_map('toReplaceSpacing',$gFontsList);
print_r($gFontsChoiceOrder);
</code>```

Body:
I am trying to replace an array value's spacing with hypen and then recollect back all values of the same array but with hypen in spaces.

INPUT:

$gFontsList = array("-1", "Agency FB", "28", "Aharoni Bold", "Bookshelf Symbol", "100", "Bookshelf Symbol", "111", "Browallia New Bol");

function toReplaceSpacing($gFontsListValues, $gFontsListIndex){
   if (gettype($gFontsListValues) === 'string'){
      if(preg_match('/ /',$gFontsListValues)){
        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
        $gFontsChoiceOrder[] = $gFontsListValues;
      }
    } else {
      $gFontsChoiceOrder[] = $gFontsListValues;
    }
}
$gFontsChoiceOrder = array_map('toReplaceSpacing',$gFontsList);
print_r($gFontsChoiceOrder);

If I print it's just NULL. I don't know Why I am not getting resultant array?.

Body:
Remove that second parameter $gFontsListIndex and then just return a value gFontsListValues.

$gFontsList = array("-1", "Agency FB", "28", "Aharoni Bold", "Bookshelf Symbol", "100", "Bookshelf Symbol", "111", "Browallia New Bol");

function toReplaceSpacing($gFontsListValues){

   $gFontsChoiceOrder = array();

   if (gettype($gFontsListValues) === 'string'){

      if(preg_match('/ /',$gFontsListValues)){

        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
      }
   }

   return $gFontsListValues;
}

$gFontsChoiceOrder = array_map('toReplaceSpacing',$gFontsList);
print_r($gFontsChoiceOrder);


问:
User does not have permission to RESTORE database
I am using the below code to backup a Database on my local SqlExpress database.

```<code>  procedure RestoreScoreDb(DBName,OldName,BackName : String);
    var
    cmd : WideString;
    SqlBackupDir : String;
    SqlDataDir : String;
    begin
    Try
    ConnectionMaster.Connected := False;
    ConnectionMaster.Close;
    ConnectionMaster.ConnectionString := 'Provider=SQLNCLI11.1;Integrated      Security="";Persist Security Info=False;User ID=SA;Password=Tccc1234;OLE DB Services=-2;Initial Catalog="master";Data Source=\SQLEXPRESS;Initial File Name="";Packet Size=4096;Auto Translate=True;Server SPN=""';
    SqlBackupDir := ReadIniStr(IniCfg,'Dir','SqlBackup');
    SqlDataDir := ReadIniStr(IniCfg,'Dir','SqlData');
    cmd := 'RESTORE DATABASE '+DBName;
    cmd := Cmd + ' FROM DISK = N'''+SqlBackupDir+'\'+BackName+'''';
    cmd := Cmd + ' WITH FILE = 1';
    cmd := cmd + ' , MOVE N'''+OldName+''' TO N'''+SqlDataDir+'\'+DBName+'.mdf''';
    cmd := cmd + ' , MOVE N'''+OldName+'_log'' TO N'''+SqlDataDir+'\'+DBName+'.ldf''';
    cmd := cmd + ' , NOUNLOAD, REPLACE, STATS = 10';
    CmdRestore.CommandText := cmd;
    CmdRestore.Connection := ConnectionMaster;
    CmdRestore.Execute;
    except
    on E: Exception do
    writeln(LogFile,'RestoreScoreDb = '+E.Message);
    end;
  end;
</code>```

The Restore command is

```<code>cmd ='RESTORE DATABASE score_import FROM DISK =
N''C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\Backup\score_import.bak''
WITH FILE = 1 , MOVE N''score_import'' TO
N''C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\score_import.mdf'' ,
MOVE N''score_import_log'' TO N''C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\score_import.ldf'' ,
NOUNLOAD, REPLACE, STATS = 10'
</code>```

When I copy and paste into management studio it restore the table without trouble. but when I run this code I get an Error:

User does not have permission to RESTORE database "score_import"

SA has full permission. Any idea what I am missing? Delphi XE6, Windows 10 Sql 2012.

答: Thanks to Embarcadero support. They could reproduce my problem and resolved it by removing Integrated Security="" from the connection string. If you are interested in why, do a Google search for "ADO Integrated Security".

Body:
I am using the below code to backup a Database on my local SqlExpress database.

  procedure RestoreScoreDb(DBName,OldName,BackName : String);
    var
    cmd : WideString;
    SqlBackupDir : String;
    SqlDataDir : String;
    begin
    Try
    ConnectionMaster.Connected := False;
    ConnectionMaster.Close;
    ConnectionMaster.ConnectionString := 'Provider=SQLNCLI11.1;Integrated      Security="";Persist Security Info=False;User ID=SA;Password=Tccc1234;OLE DB Services=-2;Initial Catalog="master";Data Source=\SQLEXPRESS;Initial File Name="";Packet Size=4096;Auto Translate=True;Server SPN=""';
    SqlBackupDir := ReadIniStr(IniCfg,'Dir','SqlBackup');
    SqlDataDir := ReadIniStr(IniCfg,'Dir','SqlData');
    cmd := 'RESTORE DATABASE '+DBName;
    cmd := Cmd + ' FROM DISK = N'''+SqlBackupDir+'\'+BackName+'''';
    cmd := Cmd + ' WITH FILE = 1';
    cmd := cmd + ' , MOVE N'''+OldName+''' TO N'''+SqlDataDir+'\'+DBName+'.mdf''';
    cmd := cmd + ' , MOVE N'''+OldName+'_log'' TO N'''+SqlDataDir+'\'+DBName+'.ldf''';
    cmd := cmd + ' , NOUNLOAD, REPLACE, STATS = 10';
    CmdRestore.CommandText := cmd;
    CmdRestore.Connection := ConnectionMaster;
    CmdRestore.Execute;
    except
    on E: Exception do
    writeln(LogFile,'RestoreScoreDb = '+E.Message);
    end;
  end;

The Restore command is

cmd ='RESTORE DATABASE score_import FROM DISK =
N''C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\Backup\score_import.bak''
WITH FILE = 1 , MOVE N''score_import'' TO
N''C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\score_import.mdf'' ,
MOVE N''score_import_log'' TO N''C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\score_import.ldf'' ,
NOUNLOAD, REPLACE, STATS = 10'

When I copy and paste into management studio it restore the table without trouble. but when I run this code I get an Error:

User does not have permission to RESTORE database "score_import"

SA has full permission. Any idea what I am missing? Delphi XE6, Windows 10 Sql 2012.


问:
How to build a docker image within jenkins
I have a jenkins maven job and trying to build a docker image. When I build the image with this command:

```<code>docker build ./docker/ -t containers.test.com/78/tools
</code>```

I get this error:

docker: "build" requires 1 argument. See 'docker build --help'

I have rechecked and checked this command dozens of times. I've even tried running it directly in the terminal. It works in the terminal but not in jenkins. Is there something I am missing?

I am using Docker version 1.12.6

答:
Normally it is

```<code>docker build -t foo/bar .
</code>```

^ the dot (.) at the end of the line designates current path to use as Docker context.
Try a cd to docker folder?

Body:
I have a jenkins maven job and trying to build a docker image. When I build the image with this command:

docker build ./docker/ -t containers.test.com/78/tools

I get this error:

docker: "build" requires 1 argument. See 'docker build --help'

I have rechecked and checked this command dozens of times. I've even tried running it directly in the terminal. It works in the terminal but not in jenkins. Is there something I am missing?

I am using Docker version 1.12.6

Body:
Normally it is

docker build -t foo/bar .

^ the dot (.) at the end of the line designates current path to use as Docker context.
Try a cd to docker folder?


问:
Filter records based on date in Rails
I am trying to filer records based on date from created_at.

For this I am passing from_date and to_date from date-picker in Date Format (e.g. "%y/%m/%d").

Please help me with how to write query in the controller to fetch the records between dates.

```<code>@users = User.where(['created_at = ? and created_at = ?',from_date,to_date])
</code>```

Thanks.

答:
This will work 100%.</p>

```<code>starting_date_month = params[:date_from].split("-")[0].to_i
starting_date_year = params[:date_from].split("-")[1].to_i
ending_date_month = params[:date_to].split("-")[0].to_i
ending_date_year = params[:date_to].split("-")[1].to_i

records = self.where("extract(month from created_at) BETWEEN ? AND ? AND extract(year from created_at) between ? AND ? AND status = ? AND v_id = ?", starting_date_month,ending_date_month,starting_date_year,ending_date_year,6,params[:v_id])
</code>```

Title: Filter records based on date in Rails

Body:
I am trying to filer records based on date from created_at.

For this I am passing from_date and to_date from date-picker in Date Format (e.g. "%y/%m/%d").

Please help me with how to write query in the controller to fetch the records between dates.

@users = User.where(['created_at = ? and created_at = ?',from_date,to_date])

Thanks.

Body:
This will work 100%.

starting_date_month = params[:date_from].split("-")[0].to_i
starting_date_year = params[:date_from].split("-")[1].to_i
ending_date_month = params[:date_to].split("-")[0].to_i
ending_date_year = params[:date_to].split("-")[1].to_i

records = self.where("extract(month from created_at) BETWEEN ? AND ? AND extract(year from created_at) between ? AND ? AND status = ? AND v_id = ?", starting_date_month,ending_date_month,starting_date_year,ending_date_year,6,params[:v_id])


问:
How to copy a large file in Windows XP?
I have a large file in windows XP - its 38GB. (a VM image)

I cannot seem to copy it.

Dragging on the desktop - gives error of "Insufficient system resources exist to complete the requested service"

Using Java - FileChannel.transferTo(0, fileSize, dest) fails for all files > 2GB

Using Java - FileChannel.transferTo() in chunks of 100Mb fails after ~18Gb

```<code>java.io.IOException: Insufficient system resources exist to complete the requested service
at sun.nio.ch.FileDispatcher.write0(Native Method)
at sun.nio.ch.FileDispatcher.write(FileDispatcher.java:44)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:72)
at sun.nio.ch.IOUtil.write(IOUtil.java:28)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:198)
at sun.nio.ch.FileChannelImpl.transferToTrustedChannel(FileChannelImpl.java:439)
at sun.nio.ch.FileChannelImpl.transferTo(FileChannelImpl.java:510)
</code>```

I mean - the computer has 3GB of RAM. A 100GB buffer should be enough!?!?

Apparently the DOS commands "copy" and "xcopy" also fail.

(edit) I've tried COPY & XCOPY - these fail with the same error. XCOPY seems to take a really really long time about it too.

I've heard of Robocopy, but it doesn't copy single files?

I'm really feeling that Windows is for the lose right now. Surely microsoft have heard of files larger than a few GB?

Thanks!

答:
In Java, don't try to copy the whole file in a single operation. The transferTo() method works on chunks of a file; wasn't intended as a high-level file copy method. Invoke transferTo() in a loop, and assume that count bytes of data will be in RAM (i.e., lower that parameter to be comfortable fitting in RAM).

```<code>FileChannel src = ...
FileChannel dst = ...
final long CHUNK = 16 * 1024 * 1024; /* 16 Mb */
for (long pos = 0; pos < fileSize; ) {
  pos += src.transferTo(pos, CHUNK, dst);
}
</code>```

The comment in the transferTo() JavaDoc about it being "more efficient than a simple loop" refers to the fact that channel-to-channel communication can be optimized more than channel-to-user-space-to-channel. It doesn't mean that all looping can be avoided.

Title: How to copy a large file in Windows XP?

Body:
I have a large file in windows XP - its 38GB. (a VM image)

I cannot seem to copy it.

Dragging on the desktop - gives error of "Insufficient system resources exist to complete the requested service"

Using Java - FileChannel.transferTo(0, fileSize, dest) fails for all files > 2GB

Using Java - FileChannel.transferTo() in chunks of 100Mb fails after ~18Gb

java.io.IOException: Insufficient system resources exist to complete the requested service
at sun.nio.ch.FileDispatcher.write0(Native Method)
at sun.nio.ch.FileDispatcher.write(FileDispatcher.java:44)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:72)
at sun.nio.ch.IOUtil.write(IOUtil.java:28)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:198)
at sun.nio.ch.FileChannelImpl.transferToTrustedChannel(FileChannelImpl.java:439)
at sun.nio.ch.FileChannelImpl.transferTo(FileChannelImpl.java:510)

I mean - the computer has 3GB of RAM. A 100GB buffer should be enough!?!?

Apparently the DOS commands "copy" and "xcopy" also fail.

(edit) I've tried COPY & XCOPY - these fail with the same error. XCOPY seems to take a really really long time about it too.

I've heard of Robocopy, but it doesn't copy single files?

I'm really feeling that Windows is for the lose right now. Surely microsoft have heard of files larger than a few GB?

Thanks!

Body:
In Java, don't try to copy the whole file in a single operation. The transferTo() method works on chunks of a file; wasn't intended as a high-level file copy method. Invoke transferTo() in a loop, and assume that count bytes of data will be in RAM (i.e., lower that parameter to be comfortable fitting in RAM).

FileChannel src = ...
FileChannel dst = ...
final long CHUNK = 16 * 1024 * 1024; /* 16 Mb */
for (long pos = 0; pos < fileSize; ) {
  pos += src.transferTo(pos, CHUNK, dst);
}

The comment in the transferTo() JavaDoc about it being "more efficient than a simple loop" refers to the fact that channel-to-channel communication can be optimized more than channel-to-user-space-to-channel. It doesn't mean that all looping can be avoided.


问:
Multidimentions array asp.net core
In php I could do this

```<code>$result=mysql_fetch_assoc($query);
$_SESSION['details']=$result;
</code>```

and Access it like this

```<code>$_SESSION['details']['name'];
</code>```

How do you do this in ASP.NET CORE if you have something like this

```<code> var user = await _context.Users.SingleOrDefaultAsync(u => u.Username == model.Username && u.Password==password);
</code>```

Please help!

答:
Your above code will return whatever you have set up in your Startup.cs class's ConfigureServices method.  In my case I have done the following:

```<code>services.AddIdentity<ApplicationUser, ApplicationRole>()
  .AddEntityFrameworkStores<AlmanacDb, int>()
  .AddDefaultTokenProviders();
</code>```

So your above code:

```<code>var user = await _context.Users.SingleOrDefaultAsync(u => u.Username == model.Username && u.Password == password);
</code>```

Would technically return an ApplicationUser object.  This is not per-say multi-dimensional object but it can have child objects which you could access properties like the following:

```<code>string UsersName = user.UserName;
</code>```

A more "multi-dimensional" property would be something like the following:

```<code>var SomeClaim = user.Claims.FirstOrDefault(x => x.ClaimType == "SomeClaimType");
</code>```

Which I suppose is similar to what you are used to of:

```<code>user[Claims][SomeClaimType];
</code>```

Hope that helps.

Title: Multidimentions array asp.net core

Body:
In php I could do this

$result=mysql_fetch_assoc($query);
$_SESSION['details']=$result;

and Access it like this

$_SESSION['details']['name'];

How do you do this in ASP.NET CORE if you have something like this

 var user = await _context.Users.SingleOrDefaultAsync(u => u.Username == model.Username && u.Password==password);

Please help!

Body:
Your above code will return whatever you have set up in your Startup.cs class's ConfigureServices method.  In my case I have done the following:

services.AddIdentity<ApplicationUser, ApplicationRole>()
  .AddEntityFrameworkStores<AlmanacDb, int>()
  .AddDefaultTokenProviders();

So your above code:

var user = await _context.Users.SingleOrDefaultAsync(u => u.Username == model.Username && u.Password == password);

Would technically return an ApplicationUser object.  This is not per-say multi-dimensional object but it can have child objects which you could access properties like the following:

string UsersName = user.UserName;

A more "multi-dimensional" property would be something like the following:

var SomeClaim = user.Claims.FirstOrDefault(x => x.ClaimType == "SomeClaimType");

Which I suppose is similar to what you are used to of:

user[Claims][SomeClaimType];

Hope that helps.


问:
How can I exit the program when user type E and or else V (view)?
I want to end this code in the beginning IF the user enters E or e or else V or v to the question:

Are you sure want to view the Result? If no type 'E' to exit \nIf you want to View Type 'V'

How to do this when the user enters e it'll exit and if enters v it'll show the grades?

Code:

```<code>#include <stdio.h>

int main(void)
{
    int marks;
    printf("Enter The Marks:");
    scanf("%d", &marks);
    printf("Are you sure want to view the Result? if no Type 'E'\nIf you want to view Type 'V'");
    if(marks>=90) {
        printf("%d, A+\n");
    }
    else if(marks>=80) {
        printf("%d, A\n");
    }
    else if(marks>=70) {
        printf("%d, B\n");
    }
    else if(marks>=60) {
        printf("%d, C\n");
    }
    else if(marks>=50) {
        printf("%d, S\n");
    }
    else if(marks>=40) {
        printf("%d, W\n");
    }
    else if(marks>=30) {
        printf("%d,Try getting more marks for your exams\n");
    }
    return 0;
}
</code>```

答:
You only need to read a simple int variable since you only want a character. Every character has a ASCII Code so you can use them as an integer.</p>

```<code>#include <stdio.h>
int main()
{
  int marks;
  int opc;

  printf("Enter The Marks:");
  scanf("%d", &marks);

  printf("Are you sure want to view the Result? if no Type 'E'\nIf you want to view Type 'V'");

  scanf("%d", &opc);

 if(opc == 'V' || opc == 'v'){
            if(marks>=90)
            {
                printf("%d, A+\n");
            }
            else
            if(marks>=80)
            {
                printf("%d, A\n");
            }

            else
            if(marks>=70)
            {
                printf("%d, B\n");
            }
            else
            if(marks>=60)
            {
                printf("%d, C\n");
            }
            else
            if(marks>=50)
            {
            printf("%d, S\n");
            }
            else
            if(marks>=40)
            {
                printf("%d, W\n");
            }
            else
            if(marks>=30)
            {
                printf("%d,Try getting more marks for your exams\n");
            }
}

return 0;
}
</code>```

Body:
I want to end this code in the beginning IF the user enters E or e or else V or v to the question:

Are you sure want to view the Result? If no type 'E' to exit \nIf you want to View Type 'V'

How to do this when the user enters e it'll exit and if enters v it'll show the grades?

Code:

#include <stdio.h>

int main(void)
{
    int marks;
    printf("Enter The Marks:");
    scanf("%d", &marks);
    printf("Are you sure want to view the Result? if no Type 'E'\nIf you want to view Type 'V'");
    if(marks>=90) {
        printf("%d, A+\n");
    }
    else if(marks>=80) {
        printf("%d, A\n");
    }
    else if(marks>=70) {
        printf("%d, B\n");
    }
    else if(marks>=60) {
        printf("%d, C\n");
    }
    else if(marks>=50) {
        printf("%d, S\n");
    }
    else if(marks>=40) {
        printf("%d, W\n");
    }
    else if(marks>=30) {
        printf("%d,Try getting more marks for your exams\n");
    }
    return 0;
}

Body:
You only need to read a simple int variable since you only want a character. Every character has a ASCII Code so you can use them as an integer.

#include <stdio.h>
int main()
{
  int marks;
  int opc;

  printf("Enter The Marks:");
  scanf("%d", &marks);

  printf("Are you sure want to view the Result? if no Type 'E'\nIf you want to view Type 'V'");

  scanf("%d", &opc);

 if(opc == 'V' || opc == 'v'){
            if(marks>=90)
            {
                printf("%d, A+\n");
            }
            else
            if(marks>=80)
            {
                printf("%d, A\n");
            }

            else
            if(marks>=70)
            {
                printf("%d, B\n");
            }
            else
            if(marks>=60)
            {
                printf("%d, C\n");
            }
            else
            if(marks>=50)
            {
            printf("%d, S\n");
            }
            else
            if(marks>=40)
            {
                printf("%d, W\n");
            }
            else
            if(marks>=30)
            {
                printf("%d,Try getting more marks for your exams\n");
            }
}

return 0;
}


问:
Display only some of the page numbers by django pagination
I am using the django paginator in the template. Its working ok, but not good when there's large numbers of pages.

views.py:

```<code>def blog(request):
    blogs_list = Blog.objects.all()

    paginator = Paginator(blogs_list, 1)

    try:
        page = int(request.GET.get('page', '1'))
    except:
        page = 1

    try:
        blogs = paginator.page(page)
    except(EmptyPage, InvalidPage):
        blogs = paginator.page(page)
    return render(request, 'blogs.html', {
        'blogs':blogs
        })
</code>```

snippet of the template:

```<code>  <div class="prev_next">

    {% if blogs.has_previous %}
      <a class="prev btn btn-info" href="?page={{blogs.previous_page_number}}">Prev</a>
    {% endif %}
    {% if blogs.has_next %}
      <a class="next btn btn-info" href="?page={{blogs.next_page_number}}">Next</a>
    {% endif %}
    <div class="pages">
      <ul>
      {% for pg in blogs.paginator.page_range %}
        {% if blogs.number == pg %}
          <li><a href="?page={{pg}}" class="btn btn-default">{{pg}}</a></li>
        {% else %}
          <li><a href="?page={{pg}}" class="btn">{{pg}}</a></li>
        {% endif %}
      {% endfor %}
      </ul>
    </div>
    <span class="clear_both"></span>

  </div>
</code>```

Now it looks like this:

What do I do to display only 7 page numbers and not all of it ranging from the current page number, like this:

```<code>Prev 1 (2) 3 4 5 Next
</code>```

I hope I was clear, if not please ask. Your help and guidance will be very much appreciated. Thank you.

答:
I did it only on templates with expressions:

```<code>{% if is_paginated %}
    <div class="text-center">
        <ul class="pagination pagination-sm">
            {% if page_obj.number >= 5 %}
            <li><a href="?page=1">1</a></li>
            <li><span>...</span></li>
            {% elif page_obj.number == 4 %}
            <li><a href="?page=1">1</a></li>
            {% endif %}
            {% if page_obj.number|add:"-2" >= 1  %}
            <li><a href="?page={{ page_obj.number|add:"-2" }}">{{ page_obj.number|add:"-2" }}</a></li>
            {% endif %}
            {% if page_obj.number|add:"-1" >= 1  %}
            <li><a href="?page={{ page_obj.number|add:"-1" }}">{{ page_obj.number|add:"-1" }}</a></li>
            {% endif %}
            <li class="active"><a href="?page={{ page_obj.number }}">{{ page_obj.number }}</a></li>
            {% if page_obj.number|add:"1" <= paginator.num_pages  %}
            <li><a href="?page={{ page_obj.number|add:"1" }}">{{ page_obj.number|add:"1" }}</a></li>
            {% endif %}
            {% if page_obj.number|add:"2" <= paginator.num_pages %}
            <li><a href="?page={{ page_obj.number|add:"2" }}">{{ page_obj.number|add:"2" }}</a></li>
            {% endif %}
            {% if page_obj.number|add:"2" <= paginator.num_pages|add:"-2" %}
            <li><span>...</span></li>
            <li><a href="?page={{ paginator.num_pages }}">{{ paginator.num_pages }}</a></li>
            {% elif page_obj.number|add:"1" <= paginator.num_pages|add:"-2" %}
            <li><a href="?page={{ paginator.num_pages }}">{{ paginator.num_pages }}</a></li>
            {% endif %}
        </ul>
    </div>
{% endif %}
</code>```

I know django is like "dont write your code again" but i found this easier for me to understand right now. Hope i helped.

Body:
I am using the django paginator in the template. Its working ok, but not good when there's large numbers of pages.

views.py:

def blog(request):
    blogs_list = Blog.objects.all()

    paginator = Paginator(blogs_list, 1)

    try:
        page = int(request.GET.get('page', '1'))
    except:
        page = 1

    try:
        blogs = paginator.page(page)
    except(EmptyPage, InvalidPage):
        blogs = paginator.page(page)
    return render(request, 'blogs.html', {
        'blogs':blogs
        })

snippet of the template:

    {% if blogs.has_previous %}
      Prev
    {% endif %}
    {% if blogs.has_next %}
      Next
    {% endif %}

      {% for pg in blogs.paginator.page_range %}
        {% if blogs.number == pg %}

{{pg}}

        {% else %}

{{pg}}

        {% endif %}
      {% endfor %}

Now it looks like this:

What do I do to display only 7 page numbers and not all of it ranging from the current page number, like this:

Prev 1 (2) 3 4 5 Next

I hope I was clear, if not please ask. Your help and guidance will be very much appreciated. Thank you.

Body:
I did it only on templates with expressions:

{% if is_paginated %}
    <div class="text-center">
        <ul class="pagination pagination-sm">
            {% if page_obj.number >= 5 %}
            <li><a href="?page=1">1</a></li>
            <li><span>...</span></li>
            {% elif page_obj.number == 4 %}
            <li><a href="?page=1">1</a></li>
            {% endif %}
            {% if page_obj.number|add:"-2" >= 1  %}
            <li><a href="?page={{ page_obj.number|add:"-2" }}">{{ page_obj.number|add:"-2" }}</a></li>
            {% endif %}
            {% if page_obj.number|add:"-1" >= 1  %}
            <li><a href="?page={{ page_obj.number|add:"-1" }}">{{ page_obj.number|add:"-1" }}</a></li>
            {% endif %}
            <li class="active"><a href="?page={{ page_obj.number }}">{{ page_obj.number }}</a></li>
            {% if page_obj.number|add:"1" <= paginator.num_pages  %}
            <li><a href="?page={{ page_obj.number|add:"1" }}">{{ page_obj.number|add:"1" }}</a></li>
            {% endif %}
            {% if page_obj.number|add:"2" <= paginator.num_pages %}
            <li><a href="?page={{ page_obj.number|add:"2" }}">{{ page_obj.number|add:"2" }}</a></li>
            {% endif %}
            {% if page_obj.number|add:"2" <= paginator.num_pages|add:"-2" %}
            <li><span>...</span></li>
            <li><a href="?page={{ paginator.num_pages }}">{{ paginator.num_pages }}</a></li>
            {% elif page_obj.number|add:"1" <= paginator.num_pages|add:"-2" %}
            <li><a href="?page={{ paginator.num_pages }}">{{ paginator.num_pages }}</a></li>
            {% endif %}
        </ul>
    </div>
{% endif %}

I know django is like "dont write your code again" but i found this easier for me to understand right now. Hope i helped.


问:
Exception (nullreferenceexception) on datagridview - C#
My code is always entering the exception, does not matter if I try to "treat" the cell with NULL using IF/ELSE clauses.

My catch System.Exception error is:
"Object reference not set to an instance of an object"

Situation:
If I enter a NULL value on the Datagrid, an error will occur and the rest of the data is not saved.

```<code>       private void ExportToExcel()
    {
        // Creating a Excel object.
        Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

        try
        {

            worksheet = workbook.ActiveSheet;

            worksheet.Name = "ExportedFromDatGrid";

            int cellRowIndex = 1;
            int cellColumnIndex = 1;

            //Loop through each row and read value from each column.
            for (int i = -1; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    // Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
                    if (cellRowIndex == 1)
                    {
                        worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Columns[j].HeaderText;
                    }
                    else
                    {

                        if (dataGridView1.Rows[i].Cells[j].Value.ToString() != null)
                        {
                            worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                        }
                        else
                        {
                            worksheet.Cells[cellRowIndex, cellColumnIndex] = String.Empty;
                        }

                        // working:
                        //worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                    cellColumnIndex++;
                }
                cellColumnIndex = 1;
                cellRowIndex++;
            }

            //Getting the location and file name of the excel to save from user.
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
            saveDialog.FilterIndex = 2;

            if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                workbook.SaveAs(saveDialog.FileName);
                MessageBox.Show("Export Successful");
            }
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            excel.Quit();
            workbook = null;
            excel = null;
        }

    } // end ExportToExcel
</code>```

答:
```<code>if (dataGridView1.Rows[i].Cells[j].Value.ToString() != null)
</code>```

Don't call ToString() here, if your value is null you'll get a NullReferenceException. Simply test Value itself.

```<code>if (dataGridView1.Rows[i].Cells[j].Value != null)
</code>```

In fact, in your case you could shorten it to

```<code>worksheet.Cells[cellRowIndex, cellColumnIndex]=dataGridView1.Rows[i].Cells[j].Value?.ToString() ?? "";
</code>```

?. being the null conditional operator and ?? being the null coalescing operator.

Body:
My code is always entering the exception, does not matter if I try to "treat" the cell with NULL using IF/ELSE clauses.

My catch System.Exception error is:
"Object reference not set to an instance of an object"

Situation:
If I enter a NULL value on the Datagrid, an error will occur and the rest of the data is not saved.

       private void ExportToExcel()
    {
        // Creating a Excel object.
        Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

        try
        {

            worksheet = workbook.ActiveSheet;

            worksheet.Name = "ExportedFromDatGrid";

            int cellRowIndex = 1;
            int cellColumnIndex = 1;

            //Loop through each row and read value from each column.
            for (int i = -1; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    // Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
                    if (cellRowIndex == 1)
                    {
                        worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Columns[j].HeaderText;
                    }
                    else
                    {

                        if (dataGridView1.Rows[i].Cells[j].Value.ToString() != null)
                        {
                            worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                        }
                        else
                        {
                            worksheet.Cells[cellRowIndex, cellColumnIndex] = String.Empty;
                        }

                        // working:
                        //worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                    cellColumnIndex++;
                }
                cellColumnIndex = 1;
                cellRowIndex++;
            }

            //Getting the location and file name of the excel to save from user.
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
            saveDialog.FilterIndex = 2;

            if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                workbook.SaveAs(saveDialog.FileName);
                MessageBox.Show("Export Successful");
            }
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            excel.Quit();
            workbook = null;
            excel = null;
        }

    } // end ExportToExcel

Body:
if (dataGridView1.Rows[i].Cells[j].Value.ToString() != null)

Don't call ToString() here, if your value is null you'll get a NullReferenceException. Simply test Value itself.

if (dataGridView1.Rows[i].Cells[j].Value != null)

In fact, in your case you could shorten it to

worksheet.Cells[cellRowIndex, cellColumnIndex]=dataGridView1.Rows[i].Cells[j].Value?.ToString() ?? "";

?. being the null conditional operator and ?? being the null coalescing operator.


问:
Symfony 3: Handling exception MethodNotAllowedException
I've not clear how handling the exception MethodNotAllowedException in Symfony.
Let me explain,

ON VIEW

Suppose that we written this script on View to go to the Controller:

```<code>//Script on view to go to the controller
<script type="text/javascript">
    $.ajax({
      method: "POST",
      url: "{{ path('my_path') }}",
      data: { myValue }
    }).done(function( data ) {
        //do something
    });
</script>
</code>```

Define the route

We define the sending of data using the post method. Now, see it the route in routing.yml

```<code>//scr/myBundle/Resources/routing.yml
my_path:
    path:     /my-path
    defaults: { _controller: myBundle:myMain:doAndReturnSomething }
    methods:  [POST]
</code>```

Working on Controller

Now, in controller

```<code>//scr/myBundle/Resources/Controller/myMainController
class myMainController extends Controller{
  public function doAndReturnSomethingAction()
  {
    //doSomeThing
    return  $this->render('myBundle:myViews:view.html.twig');
}
</code>```

This works great. How we can see, the method defined to do the send is POST.

Now, when we reload the page with the browser or press f5. All works fine.
But, if we press enter in the url on browser

```<code>//Click on: localhost/myAplicationDir/web/my-path
</code>```

The aplication get broken, sure by we don't define sending with GET, I suppose.

How can I get this exception in Symfony and show the user a custom page?

I'm thinking in redirect to myBundle index page. Any sugest?

Thanks for help.
I'm just starting with PHP and Symfony.

SOLUTION

Solution #1

Create two separate routers with GET and POST methods respectively

Solution #2

I wouldn't like created two separate routes. My controller has many methods.
I wouldn't like send the data via GET by URL. But I wouldn't like that my application get broken.

```<code>//scr/myBundle/Resources/routing.yml
my_path:
    path:     /my-path
    defaults: { _controller: myBundle:myMain:doAndReturnSomething }
    methods:  [POST, GET]

//scr/myBundle/Resources/Controller/myMainController
use Symfony\Component\HttpFoundation\Request;
class myMainController extends Controller{
  public function doAndReturnSomethingAction(Request $request)
  {
    if ($request->getMethod() == 'POST')
      //doSomeThing
    else
      //redirect to index

    //This can be other way
    //myValue is sending via POST
    if ($request->get('myValue') != null)
      //doSomething
    else
      //redirect to index

    //return  $this->render('myBundle:myViews:view.html.twig');
}
</code>```

It's there any method for correct this in all routes on routing.yml??

答:
You'll want to enable GET on the route for this to work as you're intending.

```<code>//scr/myBundle/Resources/routing.yml
my_path:
    path:     /my-path
    defaults: { _controller: myBundle:myMain:doAndReturnSomething }
    methods:  [POST, GET]
</code>```

Although I wouldn't necessarily recommend this, and would instead recommend having two separate routes, and if absolutely necessary redirecting the GET from doAndReturnSomething to a separate Controller. Essentially ending up with doSomethingAction and returnSomethingAction respectively.

Body:
I've not clear how handling the exception MethodNotAllowedException in Symfony.
Let me explain,

ON VIEW

Suppose that we written this script on View to go to the Controller:

//Script on view to go to the controller

Define the route

We define the sending of data using the post method. Now, see it the route in routing.yml

//scr/myBundle/Resources/routing.yml
my_path:
    path:     /my-path
    defaults: { _controller: myBundle:myMain:doAndReturnSomething }
    methods:  [POST]

Working on Controller

Now, in controller

//scr/myBundle/Resources/Controller/myMainController
class myMainController extends Controller{
  public function doAndReturnSomethingAction()
  {
    //doSomeThing
    return  $this->render('myBundle:myViews:view.html.twig');
}

This works great. How we can see, the method defined to do the send is POST.

Now, when we reload the page with the browser or press f5. All works fine.
But, if we press enter in the url on browser

//Click on: localhost/myAplicationDir/web/my-path

The aplication get broken, sure by we don't define sending with GET, I suppose.

How can I get this exception in Symfony and show the user a custom page?

I'm thinking in redirect to myBundle index page. Any sugest?

Thanks for help.
I'm just starting with PHP and Symfony.

SOLUTION

Solution #1

Create two separate routers with GET and POST methods respectively

Solution #2

I wouldn't like created two separate routes. My controller has many methods.
I wouldn't like send the data via GET by URL. But I wouldn't like that my application get broken.

//scr/myBundle/Resources/routing.yml
my_path:
    path:     /my-path
    defaults: { _controller: myBundle:myMain:doAndReturnSomething }
    methods:  [POST, GET]

//scr/myBundle/Resources/Controller/myMainController
use Symfony\Component\HttpFoundation\Request;
class myMainController extends Controller{
  public function doAndReturnSomethingAction(Request $request)
  {
    if ($request->getMethod() == 'POST')
      //doSomeThing
    else
      //redirect to index

    //This can be other way
    //myValue is sending via POST
    if ($request->get('myValue') != null)
      //doSomething
    else
      //redirect to index

    //return  $this->render('myBundle:myViews:view.html.twig');
}

It's there any method for correct this in all routes on routing.yml??

Body:
You'll want to enable GET on the route for this to work as you're intending.

//scr/myBundle/Resources/routing.yml
my_path:
    path:     /my-path
    defaults: { _controller: myBundle:myMain:doAndReturnSomething }
    methods:  [POST, GET]

Although I wouldn't necessarily recommend this, and would instead recommend having two separate routes, and if absolutely necessary redirecting the GET from doAndReturnSomething to a separate Controller. Essentially ending up with doSomethingAction and returnSomethingAction respectively.


问:
How to fix the error CPackage::LoadFromXML that causes the package to fail?
I had this package which been running fine since a year or more.  All of sudden it has thrown below error.  Though on restart it was success.   How to debug this issue and prevent from happening again.</p>

```<code>Executed as user: xxxxx. Microsoft (R) SQL Server Execute Package Utility Version
10.0.2531.0 for 64-bit Copyright (C) Microsoft Corp 1984-2005. All rights reserved.
Started: 7:15:08 AM Error: 2011-07-07 07:15:08.62 Code: 0xC0010018 Source:
Description: Error loading value "
    <DTS:VariableValue xmlns:DTS="www.microsoft.com/SqlServer/Dts"
    DTS:DataSubType="ManagedSerializable"
    DTS:DataType="13"><SOAP-ENV:Envelope
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:SOAP-ENC="htt" from node "DTS:VariableValue".
End Error
Error: 2011-07-07 07:15:08.62 Code: 0xC0010018 Source:
Description: Error loading value
    "<DTS:Variable xmlns:DTS="www.microsoft.com/SqlServer/Dts">
    <DTS:Property DTS:Name="Expression"></DTS:Property>
    <DTS:Property DTS:Name="EvaluateAsExpression">0</DTS:Property>
    <DTS:Property DTS:Name="Namespace">User</DTS:Property>
    <DTS:Property DTS:Name=" from node "DTS:Variable".
End Error
Could not load package "d:\edw\edw\trunk\src\etlHandler\HDL\DropZoneJobHandler.dtsx"
because of error 0xC0010014.
Description: The package failed to load due to error 0xC0010014 "One or more
error occurred. There should be more specific errors preceding this one that
explains the details of the errors. This message is used as a return value
from functions that encounter errors.". This occurs when CPackage::LoadFromXML fails.
Source: Started: 7:15:08 AM Finished: 7:15:08 AM Elapsed: 0.609 seconds.
The package could not be loaded. The step failed.
</code>```

答:
The solution for this scenario was asking customer change the debug option Run64BitRuntime from True to False. With this Run64BitRuntime=False setting, all works as in 32bit mode. See below link:

https://blogs.msdn.microsoft.com/farukcelik/2010/06/16/why-package-load-error-0xc0010014-in-cpackageloadfromxml-error-appears-while-trying-to-run-an-ssis-package/

Body:
I had this package which been running fine since a year or more.  All of sudden it has thrown below error.  Though on restart it was success.   How to debug this issue and prevent from happening again.

Executed as user: xxxxx. Microsoft (R) SQL Server Execute Package Utility Version
10.0.2531.0 for 64-bit Copyright (C) Microsoft Corp 1984-2005. All rights reserved.
Started: 7:15:08 AM Error: 2011-07-07 07:15:08.62 Code: 0xC0010018 Source:
Description: Error loading value "
    <DTS:VariableValue xmlns:DTS="www.microsoft.com/SqlServer/Dts"
    DTS:DataSubType="ManagedSerializable"
    DTS:DataType="13"><SOAP-ENV:Envelope
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:SOAP-ENC="htt" from node "DTS:VariableValue".
End Error
Error: 2011-07-07 07:15:08.62 Code: 0xC0010018 Source:
Description: Error loading value
    "<DTS:Variable xmlns:DTS="www.microsoft.com/SqlServer/Dts">
    <DTS:Property DTS:Name="Expression"></DTS:Property>
    <DTS:Property DTS:Name="EvaluateAsExpression">0</DTS:Property>
    <DTS:Property DTS:Name="Namespace">User</DTS:Property>
    <DTS:Property DTS:Name=" from node "DTS:Variable".
End Error
Could not load package "d:\edw\edw\trunk\src\etlHandler\HDL\DropZoneJobHandler.dtsx"
because of error 0xC0010014.
Description: The package failed to load due to error 0xC0010014 "One or more
error occurred. There should be more specific errors preceding this one that
explains the details of the errors. This message is used as a return value
from functions that encounter errors.". This occurs when CPackage::LoadFromXML fails.
Source: Started: 7:15:08 AM Finished: 7:15:08 AM Elapsed: 0.609 seconds.
The package could not be loaded. The step failed.