问:
Sum values from a text file and printing them
I'm trying to add the cost of books from a text file and print them. However, I'm getting [Ljava.lang.Double;@55f96302 where my values should be.

Here is my current code:

```<code>System.out.println("Welcome to the libary book search system.");
System.out.println("------------------------------------------");

if(choice.equals("Text File")) {

    //String sc = null;
    System.out.println("Title\t\t\tAuthor\t\t\tPrice\t\t\tBookPublisher\t\t\tISBN");
    System.out.println("=====\t\t\t======\t\t\t=====\t\t\t=============\t\t\t====");

    int count = 0;

    try {
        File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");
        Scanner sc = new Scanner(Fileobject);

        // Read and display each line of the file
        while(sc.hasNextLine()) {
            String line2 = sc.nextLine();
            Scanner sc2 = new Scanner(line2);
            sc2.useDelimiter("-");
            System.out.println(line2);

            while(sc2.hasNext()) {
                BookTitle[count] = sc2.next();
                System.out.println(BookTitle[count]);
                BookAuthor[count] = (sc2.next());
                System.out.println(BookAuthor[count]);
                BookPrice[count] = sc2.next();
                System.out.println(BookPrice[count]);
                BookPublisher[count] = sc2.next();
                System.out.println(BookPublisher[count]);
                ISBN[count] = sc2.next();
                System.out.println(ISBN[count]);
            }

            sc2.close();
            count++;

        }

        //for(int index=0;index<count;++index) {
            //BookPrice2[index]=Double.parseDouble(BookPrice[index]);
            //System.out.println(BookPrice2[index]);
        //}

        sc.close();
        System.out.println("----------------------");
        System.out.println("Totals of the Text File:");
        System.out.println("----------------------");
        System.out.println("Total Numbers Of Books:" + NUMBEROFBOOKS);
        System.out.println("Total Cost Of Books:"+ BookPrice2 );
        System.out.println("Maximum Cost Of A Book:");
        System.out.println("Minimum Cost Of A Book:");
        System.out.println("Average Cost Of A Book:");
        System.out.println("Total number of valid books:");
        System.out.println("Total number of invalid books:");
    } catch (FileNotFoundException e) {
            System.out.println("File does not exist");
    }
}
</code>```

Here is my text file:

```<code>The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625
</code>```

Here is what is being displayed by my java program:

```<code>Enter what you want to do: Type 'Input' for user input or 'Text File' to read from file.

Text File

Welcome to the libary book search system.
------------------------------------------
Title           Author          Price           BookPublisher               ISBN
=====           ======          =====           =============           ====
The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
The Hunger Games
Suzanne Collins
5
Scholastic Press
9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
OOP programming
Graham Winter
32
Oriely
9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625
Harry potter
Jk Rowling
10
Bloomsbury
9788700631625
----------------------
Totals of the Text File:
----------------------
Total Numbers Of Books:3
Total Cost Of Books:[Ljava.lang.Double;@55f96302
Maximum Cost Of A Book:
Minimum Cost Of A Book:
Average Cost Of A Book:
Total number of valid books:
Total number of invalid books:
</code>```

答:
Your current output of java.lang.Double@55f96302 is the toString() output for the Double wrapper class which inherits the Object class's toString() method. The value you are seeing is the memory address for that object.

And you want to output a String representation of the value instead. To do this you would use the doubleValue() method of Double to convert from an Object to the primitive type: double.

Use BookPrice2.doubleValue() here:

System.out.println("Total Cost Of Books:"+ BookPrice2.doubleValue() ); //+  gb.format());

Side note: variable names in Java should begin with a lowercase letter so BookPrice2 should be named bookPrice2. You'll learn more naming conventions along the way as you continue to learn Java.

Body:
I'm trying to add the cost of books from a text file and print them. However, I'm getting [Ljava.lang.Double;@55f96302 where my values should be.

Here is my current code:

System.out.println("Welcome to the libary book search system.");
System.out.println("------------------------------------------");

if(choice.equals("Text File")) {

    //String sc = null;
    System.out.println("Title\t\t\tAuthor\t\t\tPrice\t\t\tBookPublisher\t\t\tISBN");
    System.out.println("=====\t\t\t======\t\t\t=====\t\t\t=============\t\t\t====");

    int count = 0;

    try {
        File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");
        Scanner sc = new Scanner(Fileobject);

        // Read and display each line of the file
        while(sc.hasNextLine()) {
            String line2 = sc.nextLine();
            Scanner sc2 = new Scanner(line2);
            sc2.useDelimiter("-");
            System.out.println(line2);

            while(sc2.hasNext()) {
                BookTitle[count] = sc2.next();
                System.out.println(BookTitle[count]);
                BookAuthor[count] = (sc2.next());
                System.out.println(BookAuthor[count]);
                BookPrice[count] = sc2.next();
                System.out.println(BookPrice[count]);
                BookPublisher[count] = sc2.next();
                System.out.println(BookPublisher[count]);
                ISBN[count] = sc2.next();
                System.out.println(ISBN[count]);
            }

            sc2.close();
            count++;

        }

        //for(int index=0;index<count;++index) {
            //BookPrice2[index]=Double.parseDouble(BookPrice[index]);
            //System.out.println(BookPrice2[index]);
        //}

        sc.close();
        System.out.println("----------------------");
        System.out.println("Totals of the Text File:");
        System.out.println("----------------------");
        System.out.println("Total Numbers Of Books:" + NUMBEROFBOOKS);
        System.out.println("Total Cost Of Books:"+ BookPrice2 );
        System.out.println("Maximum Cost Of A Book:");
        System.out.println("Minimum Cost Of A Book:");
        System.out.println("Average Cost Of A Book:");
        System.out.println("Total number of valid books:");
        System.out.println("Total number of invalid books:");
    } catch (FileNotFoundException e) {
            System.out.println("File does not exist");
    }
}

Here is my text file:

The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625

Here is what is being displayed by my java program:

Enter what you want to do: Type 'Input' for user input or 'Text File' to read from file.

Text File

Welcome to the libary book search system.
------------------------------------------
Title           Author          Price           BookPublisher               ISBN
=====           ======          =====           =============           ====
The Hunger Games - Suzanne Collins - 5 - Scholastic Press - 9781921988752
The Hunger Games
Suzanne Collins
5
Scholastic Press
9781921988752
OOP programming - Graham Winter - 32 - Oriely - 9876543219
OOP programming
Graham Winter
32
Oriely
9876543219
Harry potter - Jk Rowling - 10 - Bloomsbury - 9788700631625
Harry potter
Jk Rowling
10
Bloomsbury
9788700631625
----------------------
Totals of the Text File:
----------------------
Total Numbers Of Books:3
Total Cost Of Books:[Ljava.lang.Double;@55f96302
Maximum Cost Of A Book:
Minimum Cost Of A Book:
Average Cost Of A Book:
Total number of valid books:
Total number of invalid books:


来源: stackexchange

问:
select row where the slot is the biggest
i need to select one row where slot_left is the biggest. i tried

```<code>for ( $i=1;$i<3;$i++) {
    $sql5 = "SELECT * from user u where (
        select max(slot_left) from company c,user u
        where c.id=u.company_id and c.id='$name'
    )";
    $result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
    while($row=mysqli_fetch_array($result5)) {
        // echo the id which the slot_left is the biggest
        echo $i['slot_left'];
    }
}
</code>```

but still cannot. please help!

答:
You have to use GROUP BY in your query.
And query execution in Loop is not recommended, it will decrees performance.

Try this.

```<code>$sql5 = "select c.id, max(slot_left) from company c,user u
        where c.id=u.company_id and c.id='$id' GROUP by c.id";

    $result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
    while($row=mysqli_fetch_array($result5)) {
        echo $row['slot_left'];
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i need to select one row where slot_left is the biggest. i tried

for ( $i=1;$i<3;$i++) {
    $sql5 = "SELECT * from user u where (
        select max(slot_left) from company c,user u
        where c.id=u.company_id and c.id='$name'
    )";
    $result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
    while($row=mysqli_fetch_array($result5)) {
        // echo the id which the slot_left is the biggest
        echo $i['slot_left'];
    }
}

but still cannot. please help!

Body:
You have to use GROUP BY in your query.
And query execution in Loop is not recommended, it will decrees performance.

Try this.

$sql5 = "select c.id, max(slot_left) from company c,user u
        where c.id=u.company_id and c.id='$id' GROUP by c.id";

    $result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
    while($row=mysqli_fetch_array($result5)) {
        echo $row['slot_left'];
    }


问:
MongoDB Symfony3 pagination From To limit results using QueryBuilder
I'm using mongoDB in my symfony3 application, and I need to use setMaxResults and setFirstResult in my repository to paginate my results in my listing action. But I'm more used to use MySql as a database and I don't find how to do it in my cas.

I tried to use it as this :

```<code>$qb = $this->createQueryBuilder('DemoBundle:Entity');
$qb ->select('u');
$qb ->setMaxResults($max)
    ->setFirstResult($first);
</code>```

But I have an error as followed :

Attempted to call an undefined method named "setMaxResults" of class
  "Doctrine\ODM\MongoDB\Query\Builder

The full function is as like this :

```<code>public function search($data, $page = 0, $max = NULL, $getResult = true)
{
    $qb = $this->createQueryBuilder('AresAPITournamentBundle:Tournament');
    $query = isset($data['query']) && $data['query']?$data['query']:null;

    $qb ->select('u');

    if ($query) {
        $qb
            ->andWhere('u.name like :query')
            ->setParameter('query', "%".$query."%")
        ;
    }

    if ($max) {
        $qb ->setMaxResults($max)
            ->setFirstResult($page * $max)
        ;
    } else {
        $preparedQuery = $qb->getQuery();
    }

    return $getResult?$preparedQuery->execute():$preparedQuery;
}
</code>```

I found the ressource in this tutorial.

How can I achieve this ?

答:
Response was :</p>

```<code>    $qb ->limit($to)
        ->skip($from);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using mongoDB in my symfony3 application, and I need to use setMaxResults and setFirstResult in my repository to paginate my results in my listing action. But I'm more used to use MySql as a database and I don't find how to do it in my cas.

I tried to use it as this :

$qb = $this->createQueryBuilder('DemoBundle:Entity');
$qb ->select('u');
$qb ->setMaxResults($max)
    ->setFirstResult($first);

But I have an error as followed :

Attempted to call an undefined method named "setMaxResults" of class
  "Doctrine\ODM\MongoDB\Query\Builder

The full function is as like this :

public function search($data, $page = 0, $max = NULL, $getResult = true)
{
    $qb = $this->createQueryBuilder('AresAPITournamentBundle:Tournament');
    $query = isset($data['query']) && $data['query']?$data['query']:null;

    $qb ->select('u');

    if ($query) {
        $qb
            ->andWhere('u.name like :query')
            ->setParameter('query', "%".$query."%")
        ;
    }

    if ($max) {
        $qb ->setMaxResults($max)
            ->setFirstResult($page * $max)
        ;
    } else {
        $preparedQuery = $qb->getQuery();
    }

    return $getResult?$preparedQuery->execute():$preparedQuery;
}

I found the ressource in this tutorial.

How can I achieve this ?

Body:
Response was :

    $qb ->limit($to)
        ->skip($from);


问:
Debug external project from winform application
I have two separated projects
XLSWriterUI (WinFormApp)
XLSWriter (consoleapp)

The XLSWriteUI starts without any problems. In the XLSWriteUI applications, there Is a button called "Parse". When you hit this button, the XLSWriter application executable Is called like this:

Main.cs In XLSWriterUI

```<code> private void Parse_Click(object sender, EventArgs e)
        {
            // Enable waitcursor
            // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            Tabs_SetWaitCursor(Parse);

            try
            {
                Debug.Text = String.Empty;
                Debug.Refresh();

                // Create process
                // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                // Set startup parameters
                proc.StartInfo.FileName = @"XLSWriter.exe";
                proc.StartInfo.Arguments = Tabs_GetParameters();
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.OutputDataReceived += new DataReceivedEventHandler(StdOutReceiver);

                // Start process
                // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                proc.Start();
                proc.BeginOutputReadLine();
                proc.WaitForExit();
            }
            catch (Exception Ex)
            {
                // Whatever
                Debug.AppendText(Ex.Message);
            }
            // Cancel waitcursor
            // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            Tabs_CancelWaitCursor(Parse);
        }
</code>```

As you can see, the executable of the XLSWriter Is called when you hit the Parse-button. I don't want this. I want to be able to debug the XLSWriter application project when you hit the button so I can step in and out in code in Visual studio.

So basically, I want to do this:
Start both the applications via visual studio so they are running,
Set a breakpoint in XLSWriter,
When I click on the button in XLSWriterUI, the breakpoint In XLSWriter should be triggerd.

How can I do this?

答: If you have both proejcts in your solution then From Solution Use Set Startup projects feature and choose your project from multiple startup options</p>

Body:
I have two separated projects
XLSWriterUI (WinFormApp)
XLSWriter (consoleapp)

The XLSWriteUI starts without any problems. In the XLSWriteUI applications, there Is a button called "Parse". When you hit this button, the XLSWriter application executable Is called like this:

Main.cs In XLSWriterUI

 private void Parse_Click(object sender, EventArgs e)
        {
            // Enable waitcursor
            // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            Tabs_SetWaitCursor(Parse);

            try
            {
                Debug.Text = String.Empty;
                Debug.Refresh();

                // Create process
                // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                // Set startup parameters
                proc.StartInfo.FileName = @"XLSWriter.exe";
                proc.StartInfo.Arguments = Tabs_GetParameters();
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.OutputDataReceived += new DataReceivedEventHandler(StdOutReceiver);

                // Start process
                // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                proc.Start();
                proc.BeginOutputReadLine();
                proc.WaitForExit();
            }
            catch (Exception Ex)
            {
                // Whatever
                Debug.AppendText(Ex.Message);
            }
            // Cancel waitcursor
            // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            Tabs_CancelWaitCursor(Parse);
        }

As you can see, the executable of the XLSWriter Is called when you hit the Parse-button. I don't want this. I want to be able to debug the XLSWriter application project when you hit the button so I can step in and out in code in Visual studio.

So basically, I want to do this:
Start both the applications via visual studio so they are running,
Set a breakpoint in XLSWriter,
When I click on the button in XLSWriterUI, the breakpoint In XLSWriter should be triggerd.

How can I do this?


问:
Test the size of a text on a button with getTextSize()
I need to check if the text size on a button have the size 37sp.
I found a method to get the size with: .getTextSize(), but the size with I receive is: 126.0,  and not 48sp.
The code off button:

```<code><Button
    android:id="@+id/buttoneql"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="="
    android:textColor="@android:color/black"
    android:textSize="48sp" />
</code>```

The test:

```<code>buttoneql = (Button) currentActivity.findViewById(R.id.buttoneql);
assertEquals( 48.0f, buttoneql.getTextSize() );
</code>```

How I should do to recive the ral value of the text size?

答:
I solved the problem by multiplying the value I need (128.0) by 2.625 and rounding it up correctly to make it an integer.

```<code>int size = (int) Math.round (48.0 * 2.625);
</code>```

And after, comparing to the receive value:

```<code>assertEquals(size, (int) buttoneql.getTextSize());
</code>```

Body:
I need to check if the text size on a button have the size 37sp.
I found a method to get the size with: .getTextSize(), but the size with I receive is: 126.0,  and not 48sp.
The code off button:

<Button
    android:id="@+id/buttoneql"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="="
    android:textColor="@android:color/black"
    android:textSize="48sp" />

The test:

buttoneql = (Button) currentActivity.findViewById(R.id.buttoneql);
assertEquals( 48.0f, buttoneql.getTextSize() );

How I should do to recive the ral value of the text size?

Body:
I solved the problem by multiplying the value I need (128.0) by 2.625 and rounding it up correctly to make it an integer.

int size = (int) Math.round (48.0 * 2.625);

And after, comparing to the receive value:

assertEquals(size, (int) buttoneql.getTextSize());


问:
Python's matplotlib import
On my working PC (Windows7, no internet connection) there are two Pythons: one is the main (C:\Python36-32) with IDLE. Another - freshly installed Anaconda (C:\ProgramData\Anaconda3) - just for scipy and matplotlib (IT guy thought it is the best option).

So, matplotlib works only if I run my scripts from cmd. But it is not comfortable. I prefer IDLE or any other modern environment.

But if I try use matplotlib in IDLE - I got an "No module named 'matplotlib'". I tried to edit sys.path and run:

```<code>sys.path.append("C:\\ProgramData\\Anaconda3\\Lib\\site-packages").
</code>```

It helps a little bit - I got new error "No module named 'matplotlib._path'". So, it looks like IDLE knows what is matplotlib now, but doesn't know it's functions.
Is there any way to connect IDLE with Anaconda's libraries? Maybe to append paths recursively?

答:
It's probably not a good idea to mix the python distributions through the system path.

Python should ship with IDLE. So you can use the IDLE from the Anaconda distribution,

```<code>C:\ProgramData\Anaconda3>python.exe Lib\idlelib\idle.py
</code>```

Also note that Anaconda should also provide Spyder. This might be a nicer IDE.

Title: Python's matplotlib import

Body:
On my working PC (Windows7, no internet connection) there are two Pythons: one is the main (C:\Python36-32) with IDLE. Another - freshly installed Anaconda (C:\ProgramData\Anaconda3) - just for scipy and matplotlib (IT guy thought it is the best option).

So, matplotlib works only if I run my scripts from cmd. But it is not comfortable. I prefer IDLE or any other modern environment.

But if I try use matplotlib in IDLE - I got an "No module named 'matplotlib'". I tried to edit sys.path and run:

sys.path.append("C:\\ProgramData\\Anaconda3\\Lib\\site-packages").

It helps a little bit - I got new error "No module named 'matplotlib._path'". So, it looks like IDLE knows what is matplotlib now, but doesn't know it's functions.
Is there any way to connect IDLE with Anaconda's libraries? Maybe to append paths recursively?

Body:
It's probably not a good idea to mix the python distributions through the system path.

Python should ship with IDLE. So you can use the IDLE from the Anaconda distribution,

C:\ProgramData\Anaconda3>python.exe Lib\idlelib\idle.py

Also note that Anaconda should also provide Spyder. This might be a nicer IDE.


问:
deduplicates values in array with javascript before GET query
I have the following loop that list domains. Each line contains a checkbox with domain as value stored in array urls[] :

```<code><form action="/profiles-routing/add/63" method="get">
...
        <?php foreach ($accesslogs as $accesslog): ?>
        <tr>
            <td>
                <input class="checkbox" type="checkbox" name="urls[]" value="<?= $accesslog->DOMAIN ?>">
            </td>
            <td><a href="<?= $accesslog->url ?>" data-toggle="tooltip" title="<?= $accesslog->url ?>"><?= $accesslog->DOMAIN ?></a></td>
        </tr>
        <?php endforeach; ?>
...
</form>
</code>```

I could have many same domains in the query, I looking how to deduplicate urls values with a javascript before doing the GET query.

For example, javascript should modify this :

http://127.0.0.1:8001/profiles-routing/add/63?urls[0]=www.domaine1.com&urls[1]=www.domaine1.com&urls[2]=www.domaine1.com&urls[3]=www.domaine2.com&urls[4]=www.domaine2.com

To this :
http://127.0.0.1:8001/profiles-routing/add/63?urls[0]=www.domaine1.com&urls[3]=www.domaine2.com

How can I do it ?

Thank you,

答:
I came up with this code to help you out:

```<code><?php
    function arr_clearduplicates($arr) {
        $newArray = array();

        foreach($arr as $val) {
            //If the value isn't in the array, push it in.
            // This will make sure no existing data is added again.
            if(!in_array($val, $newArray)) {
                $newArray[] = $val;
            }
        }

        return $newArray;
    }
?>
</code>```

This will basically register a function doing this:

Take whatever array you give it

Make a new empty array.

Take all values in your first array, if they are already in the new array, they will not be added, otherwise, they will.

Return the empty array.

Which means: array will have no values equal to each other.

Body:
I have the following loop that list domains. Each line contains a checkbox with domain as value stored in array urls[] :

<form action="/profiles-routing/add/63" method="get">
...
        <?php foreach ($accesslogs as $accesslog): ?>

                <input class="checkbox" type="checkbox" name="urls[]" value="<?= $accesslog->DOMAIN ?>">

            <a href="<?= $accesslog->url ?>" data-toggle="tooltip" title="<?= $accesslog->url ?>"><?= $accesslog->DOMAIN ?>

        <?php endforeach; ?>
...
</form>

I could have many same domains in the query, I looking how to deduplicate urls values with a javascript before doing the GET query.

For example, javascript should modify this :

http://127.0.0.1:8001/profiles-routing/add/63?urls[0]=www.domaine1.com&urls[1]=www.domaine1.com&urls[2]=www.domaine1.com&urls[3]=www.domaine2.com&urls[4]=www.domaine2.com

To this :
http://127.0.0.1:8001/profiles-routing/add/63?urls[0]=www.domaine1.com&urls[3]=www.domaine2.com

How can I do it ?

Thank you,

Body:
I came up with this code to help you out:

<?php
    function arr_clearduplicates($arr) {
        $newArray = array();

        foreach($arr as $val) {
            //If the value isn't in the array, push it in.
            // This will make sure no existing data is added again.
            if(!in_array($val, $newArray)) {
                $newArray[] = $val;
            }
        }

        return $newArray;
    }
?>

This will basically register a function doing this:

Take whatever array you give it

Make a new empty array.

Take all values in your first array, if they are already in the new array, they will not be added, otherwise, they will.

Return the empty array.

Which means: array will have no values equal to each other.


问:
Automate Opera Mini Tests via Appium/Selenium
I have researched how to test mobile web apps via Appium (to use the mobile sdk)
The achieve automation of opera browser tests, one can use selenium / appium with the opera chrome or presto drivers (imported libraries)

However there is no documentation with regards to running automation on opera mini applications.

Does anyone know if this is possible? Has anyone successfully used Apium to test Opera Mini?

答:
Though it is not supported out of the box by Appium (CHROME, CHROMIUM, SAFARI are listed), you can use operachromiumdriver:</p>

```<code>desired_caps['chromedriverExecutable'] = '/absolute/path/to/operadriver'
desired_caps['app'] = os.path.abspath('opera-browser.apk')
desired_caps['appPackage'] = 'com.opera.browser'
desired_caps['androidDeviceSocket'] = desired_caps['appPackage'] + '.devtools'
</code>```

Body:
Though it is not supported out of the box by Appium (CHROME, CHROMIUM, SAFARI are listed), you can use operachromiumdriver:

desired_caps['chromedriverExecutable'] = '/absolute/path/to/operadriver'
desired_caps['app'] = os.path.abspath('opera-browser.apk')
desired_caps['appPackage'] = 'com.opera.browser'
desired_caps['androidDeviceSocket'] = desired_caps['appPackage'] + '.devtools'


问:
Asp.net - <customErrors mode="Off"/> error when trying to access working webpage
I have created an asp.net webpage and have uploaded it onto a webserver. However when I try to view the page remotely, I get errors about the customerror tag in the web.config file. The page works locally with no errors or warnings. Also if I upload the page as a .html file, I can view it fine remotely.
I have seen a lot of other people with this error, but the 'solutions' just say to change the customErrors tag to 'Off', which I have done and does not work, do you know is there an issue with the webserver or what could be the problem here?

Here is the error page:

Server Error in '/' Application.
  Runtime Error
  Description: An application error occurred on the server. The current custom error >settings for this application prevent the details of the application error from being >viewed remotely (for security reasons). It could, however, be viewed by browsers running >on the local server machine.

Details: To enable the details of this specific error message to be viewable on remote >machines, please create a  tag within a "web.config" configuration file >located in the root directory of the current web application. This  tag >should then have its "mode" attribute set to "Off".

```<code><configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>
</code>```

Notes: The current error page you are seeing can be replaced by a custom error page by >modifying the "defaultRedirect" attribute of the application's  >configuration tag to point to a custom error page URL.

```<code><configuration>
    <system.web>
        <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
    </system.web>
</configuration>
</code>```

And here is my web.config file:

```<code><?xml version="1.0"?>
<configuration>

  <system.web>
    <customErrors mode="Off"/>
  </system.web>

  <system.web>
    <compilation debug="true"/>
    <authentication mode="None"/>
  </system.web>
</configuration>
</code>```

答:
Sometime in the future
Comment out the following code in web.config

```<code> <!--<system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>-->
</code>```

update the  to the following code.

```<code><system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <customErrors mode="Off"/>
    <trust level="Full"/>
  </system.web>
</code>```

Body:
I have created an asp.net webpage and have uploaded it onto a webserver. However when I try to view the page remotely, I get errors about the customerror tag in the web.config file. The page works locally with no errors or warnings. Also if I upload the page as a .html file, I can view it fine remotely.
I have seen a lot of other people with this error, but the 'solutions' just say to change the customErrors tag to 'Off', which I have done and does not work, do you know is there an issue with the webserver or what could be the problem here?

Here is the error page:

Server Error in '/' Application.
  Runtime Error
  Description: An application error occurred on the server. The current custom error >settings for this application prevent the details of the application error from being >viewed remotely (for security reasons). It could, however, be viewed by browsers running >on the local server machine.

Details: To enable the details of this specific error message to be viewable on remote >machines, please create a  tag within a "web.config" configuration file >located in the root directory of the current web application. This  tag >should then have its "mode" attribute set to "Off".

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Notes: The current error page you are seeing can be replaced by a custom error page by >modifying the "defaultRedirect" attribute of the application's  >configuration tag to point to a custom error page URL.

<configuration>
    <system.web>
        <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
    </system.web>
</configuration>

And here is my web.config file:

<?xml version="1.0"?>
<configuration>

  <system.web>
    <customErrors mode="Off"/>
  </system.web>

  <system.web>
    <compilation debug="true"/>
    <authentication mode="None"/>
  </system.web>
</configuration>

Body:
Sometime in the future
Comment out the following code in web.config

 <!--<system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>-->

update the  to the following code.

<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <customErrors mode="Off"/>
    <trust level="Full"/>
  </system.web>


问:
Fixed & shrinking navbar
I didn't find anything on Google about this without using Bootstrap and in my project I didn't want to. (because I'm a beginner and I decided to start with a vanilla project - only css html and js and mostly because when I started building this I didn't even know what bootstrap was).
So how I can make the white (id: top-mare + logo) navbar fixed and shrinking while scrolling?

HTML

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Best DAVNIC73</title>
    <link href="css/css.css" rel="stylesheet" />
    <link href="css/sshow.css" rel="stylesheet" />
    <link href="css/mqueries.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

Contact

Despre noi

Locatie

Acasa

Buton1

Buton2

Buton3

Buton4

1 / 3

2 / 3

3 / 3

            ❮
            ❯

            <button onclick="topFunction()" id="myBtn" title="Inapoi la inceputul paginii"></button>

SC Best DAVNIC73 SRL

 Judet Dambovita, Oras Targoviste, Strada, Nr

074 44 44 444

bestdavnic73@gmail.com

Copyright Ⓒ 2017

```
</div>
</div>
</p>

<p>CSS</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>html {
    box-sizing: border-box;
    height: 100%;
    font-family: Roboto, Arial;
}

*,
*:before,
*:after {
    box-sizing: inherit;
}

body {
    font-family: Roboto, Arial;
    height: auto;
    width: 100%;
    padding: 0;
    padding-bottom: 6vw;
    margin: 0;
    font-size: 1.1vw;
    min-height: 100%;
    position: relative;
}

header {
    color: #ffffff;
    padding: 0;
    margin: 0;
    border-bottom: 1px solid #ADADAD;
}

#container {
    margin: 0 auto;
    padding: 0;
    color: #ffffff;
}

#top-mic {
    background-color: #F28A00;
    margin: 0;
    padding: 0;
    margin-bottom: 0.73vw;
}

#top-mic ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        overflow: hidden;
}

#top-mic li {
        float: right;
        padding: 0.416vw 1.5625vw;
}

#top-mic li a {
        display: block;
        text-decoration: none;
        color: #ffffff;
        text-align: center;
        font-size: 0.6vw;
        font-weight: bold;
        transition: color 0.25s ease;
        margin-right: 2.8645vw;
}

#top-mic li a:hover {
    color: #ADADAD;
}

#logo {
 max-width: 100%;
    float: left;
    margin-left: 12.5vw;
    margin-right: 6.77vw;
    width:15vw;
 height: auto !important;
}

#top-mare-wrap {
    margin: 0 auto;
}

#top-mare {
    padding: 0;
    margin: 0;
    margin-bottom: 3.125vw;

}

#top-mare ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
}

#top-mare li {
        display: inline;
}

#top-mare li a {
        margin-top: 2.1875vw;
        margin-left: 2.083vw;
        padding-right: 1.041vw;
        display: inline-block;
        text-decoration: none;
        color: #ADADAD;
        text-align: center;
        font-size: 2.1vw;
        font-weight: bold;
        transition: color 0.25s ease;
}

#top-mare li a:hover {
        color: #F28A00;
}

#test {
    color:black;
}

.footer {
    position: fixed;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: #F28A00;
}

.footer ul {
        list-style-type: none;
        margin: 0;
        padding: 1.041vw;
}

.footer li {
        font-size: 0.9vw;
        font-weight:bold;
        display: inline;
        margin-left: 2.604vw;
        padding-right: 0.78125vw;
        padding-bottom: 0.263vw;
}

.copyright {
    float:right;
}

#nume {
    font-weight: italic;
}

#myBtn {
    display: none;
    position: fixed;
    bottom: 3.646vw;
    left: 3.125vw;
    z-index: 99;
    border: none;
    outline: none;
    background-color: #F28A00;
    color: white;
    cursor: pointer;
    padding: 0.78125vw;
    border-radius: 10px;
    width: 3.33333vw;
    height: 3.3333vw;
}

.location {
    width: 0.677vw;
    height: 0.677vw;
}

.phone {
    width: 0.677vw;
    height: 0.677vw;
}

#mail {
    height: 0.677vw;
    width: 0.9375vw;
}</code>```

答:
To create shrinking animation I would suggest you to use CSS transition and jQuery addClass.

So, you're going to measure the scroll position from top. When at height wanted, add CSS class holding shrink values to that element.

For example your logo has class 'logo':

```<code><img src="image/logo.jpg" class="logo"/>
</code>```

Logo CSS:

```<code>.logo {
    width: 200px;
    transition: all .5s ease-in-out;
}
</code>```

The class you're going to add/remove is called eg. 'shrink'. It holds shrink values (eg you want the shrinking logo to be 125px wide):

```<code>.logo.shrink {
    width: 125px;
}
</code>```

Next add shrink class to logo when needed (70px from top in this example).

```<code>$(document).on('scroll', function() {
    if ($(this).scrollTop > 70) {
        $('.logo').addClass('shrink');
    } else if ($(this).scrollTop < 70) {
        $('.logo').removeClass('shrink');
    }
});
</code>```

I made you an example: https://jsfiddle.net/cr29y1tc/29/

Title: Fixed & shrinking navbar

Body:
I didn't find anything on Google about this without using Bootstrap and in my project I didn't want to. (because I'm a beginner and I decided to start with a vanilla project - only css html and js and mostly because when I started building this I didn't even know what bootstrap was).
So how I can make the white (id: top-mare + logo) navbar fixed and shrinking while scrolling?

HTML

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Best DAVNIC73</title>
    <link href="css/css.css" rel="stylesheet" />
    <link href="css/sshow.css" rel="stylesheet" />
    <link href="css/mqueries.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

Contact

Despre noi

Locatie

Acasa

Buton1

Buton2

Buton3

Buton4

1 / 3

2 / 3

3 / 3

            ❮
            ❯

            <button onclick="topFunction()" id="myBtn" title="Inapoi la inceputul paginii"></button>

SC Best DAVNIC73 SRL

 Judet Dambovita, Oras Targoviste, Strada, Nr

074 44 44 444

bestdavnic73@gmail.com

Copyright Ⓒ 2017

CSS

html {
    box-sizing: border-box;
    height: 100%;
    font-family: Roboto, Arial;
}

*,
*:before,
*:after {
    box-sizing: inherit;
}

body {
    font-family: Roboto, Arial;
    height: auto;
    width: 100%;
    padding: 0;
    padding-bottom: 6vw;
    margin: 0;
    font-size: 1.1vw;
    min-height: 100%;
    position: relative;
}

header {
    color: #ffffff;
    padding: 0;
    margin: 0;
    border-bottom: 1px solid #ADADAD;
}

#container {
    margin: 0 auto;
    padding: 0;
    color: #ffffff;
}

#top-mic {
    background-color: #F28A00;
    margin: 0;
    padding: 0;
    margin-bottom: 0.73vw;
}

#top-mic ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        overflow: hidden;
}

#top-mic li {
        float: right;
        padding: 0.416vw 1.5625vw;
}

#top-mic li a {
        display: block;
        text-decoration: none;
        color: #ffffff;
        text-align: center;
        font-size: 0.6vw;
        font-weight: bold;
        transition: color 0.25s ease;
        margin-right: 2.8645vw;
}

#top-mic li a:hover {
    color: #ADADAD;
}

#logo {
 max-width: 100%;
    float: left;
    margin-left: 12.5vw;
    margin-right: 6.77vw;
    width:15vw;
 height: auto !important;
}

#top-mare-wrap {
    margin: 0 auto;
}

#top-mare {
    padding: 0;
    margin: 0;
    margin-bottom: 3.125vw;

}

#top-mare ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
}

#top-mare li {
        display: inline;
}

#top-mare li a {
        margin-top: 2.1875vw;
        margin-left: 2.083vw;
        padding-right: 1.041vw;
        display: inline-block;
        text-decoration: none;
        color: #ADADAD;
        text-align: center;
        font-size: 2.1vw;
        font-weight: bold;
        transition: color 0.25s ease;
}

#top-mare li a:hover {
        color: #F28A00;
}

#test {
    color:black;
}

.footer {
    position: fixed;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: #F28A00;
}

.footer ul {
        list-style-type: none;
        margin: 0;
        padding: 1.041vw;
}

.footer li {
        font-size: 0.9vw;
        font-weight:bold;
        display: inline;
        margin-left: 2.604vw;
        padding-right: 0.78125vw;
        padding-bottom: 0.263vw;
}

.copyright {
    float:right;
}

#nume {
    font-weight: italic;
}

#myBtn {
    display: none;
    position: fixed;
    bottom: 3.646vw;
    left: 3.125vw;
    z-index: 99;
    border: none;
    outline: none;
    background-color: #F28A00;
    color: white;
    cursor: pointer;
    padding: 0.78125vw;
    border-radius: 10px;
    width: 3.33333vw;
    height: 3.3333vw;
}

.location {
    width: 0.677vw;
    height: 0.677vw;
}

.phone {
    width: 0.677vw;
    height: 0.677vw;
}

#mail {
    height: 0.677vw;
    width: 0.9375vw;
}

Body:
To create shrinking animation I would suggest you to use CSS transition and jQuery addClass.

So, you're going to measure the scroll position from top. When at height wanted, add CSS class holding shrink values to that element.

For example your logo has class 'logo':

<img src="image/logo.jpg" class="logo"/>

Logo CSS:

.logo {
    width: 200px;
    transition: all .5s ease-in-out;
}

The class you're going to add/remove is called eg. 'shrink'. It holds shrink values (eg you want the shrinking logo to be 125px wide):

.logo.shrink {
    width: 125px;
}

Next add shrink class to logo when needed (70px from top in this example).

$(document).on('scroll', function() {
    if ($(this).scrollTop > 70) {
        $('.logo').addClass('shrink');
    } else if ($(this).scrollTop < 70) {
        $('.logo').removeClass('shrink');
    }
});

I made you an example: https://jsfiddle.net/cr29y1tc/29/


问:
PHP search engine isn't working
I recently made a php function , but it isn't working like I want.

This is my code:

```<code><div class="pageContent">
<?php

    getComments($conn);

    function getComments($conn){

        $searchFor = $_POST['keyword'];

        $sql = "SELECT adds.* FROM keywords JOIN adds on keywords.productID = adds.id and keywords.keyword LIKE '%".$searchFor."%'";
        $result = $conn->query($sql);
        while ($row = $result->fetch_assoc()) {

            echo "<div class='add'>
                <img src='uploads/".$row['imgURL']."'>
                <div>
                    <h1><a>".$row['name']."</a></h1>
                    <p>".$row['descr']."</p>
                </div>
            </div>";

        }
    }

?>
<br />
</code>```

And the ($conn)

```<code>$conn = mysqli_connect("localhost", "root", "", "stp2");

if (!$conn) {

    die("Connection failed: ".mysqli_connect_error);

}
</code>```

When there are normal 2 different results the function is just showing 2 times the same result.

I hope that you guys can help me.

答: If you are getting duplicate results you may want to group them by the ID of the 'adds' table using GROUP BY. This would get rid of multiple copies of the same row from that table</p>

Title: PHP search engine isn't working

Body:
I recently made a php function , but it isn't working like I want.

This is my code:

<?php

    getComments($conn);

    function getComments($conn){

        $searchFor = $_POST['keyword'];

        $sql = "SELECT adds.* FROM keywords JOIN adds on keywords.productID = adds.id and keywords.keyword LIKE '%".$searchFor."%'";
        $result = $conn->query($sql);
        while ($row = $result->fetch_assoc()) {

            echo "

".$row['name']."

".$row['descr']."

";

        }
    }

?>

And the ($conn)

$conn = mysqli_connect("localhost", "root", "", "stp2");

if (!$conn) {

    die("Connection failed: ".mysqli_connect_error);

}

When there are normal 2 different results the function is just showing 2 times the same result.

I hope that you guys can help me.


问:
Permission denied on Cygnus conf/
Already I get my Cygnus last version installed, but when I try to create my agent configuration with this order:

```<code>sudo cat > /usr/cygnus/conf/cygnus_instance_1.conf
</code>```

I get always the following error

```<code>-bash: cygnus_instance_1.conf: Permission denied
</code>```

Anyone can help me? Thank you so much!!

答:
This problem is not with FIWARE Cygnus. Try creating the file in the local directory with:

```<code>cat > cygnus_instance_1.conf
</code>```

After that, verify if /usr/cygnus/conf really exists. In positive case, move you cygnus_instance_1.conf file created to the specific directory:

```<code>sudo mv cygnus_instance_1.conf /usr/cygnus/conf/.
</code>```

Now you have /usr/cygnus/conf file in the directory you want. If you need to edit it, just use some text editor (vi, vim, nano...) with sudo and it will work.

I hope it helps you.

Title: Permission denied on Cygnus conf/

Body:
Already I get my Cygnus last version installed, but when I try to create my agent configuration with this order:

sudo cat > /usr/cygnus/conf/cygnus_instance_1.conf

I get always the following error

-bash: cygnus_instance_1.conf: Permission denied

Anyone can help me? Thank you so much!!

Body:
This problem is not with FIWARE Cygnus. Try creating the file in the local directory with:

cat > cygnus_instance_1.conf

After that, verify if /usr/cygnus/conf really exists. In positive case, move you cygnus_instance_1.conf file created to the specific directory:

sudo mv cygnus_instance_1.conf /usr/cygnus/conf/.

Now you have /usr/cygnus/conf file in the directory you want. If you need to edit it, just use some text editor (vi, vim, nano...) with sudo and it will work.

I hope it helps you.


问:
What is MASM ? which we generally use it for learning assembly language code?
In 8086 processor,what ic's we use are different...i think they are of 16 bit...but we practice the code in 64 bit computers..how is it possible?please expalin>>>>What is MaSm actually?? and can you explain me where I can get the software....</p>

答:
MASM - is the Microsoft Macro Assembler. It is an assembler. It takes your code
pre-processes it and converts it to binary. The links it to runnable executable or an OBJect file.

all Intel processors 32bit and em64t processors (80386 and up) support the 8086 compatability mode called "real mode". Wich means that all PCs to this day are backward compatible with say MS-DOS and all the games that used to run on IBM XT. Those will run on modern machines but really fast so those will be unplayable :-)

All PCs to this day are booting with their processor in the real mode and modern operating systems switch the processor to the 32bit/64bit "protected mode".

Basically what happens in real mode is that the CPU knows it is working as 8086.
E.g : all operations are on 16bit registers and the memory is addressed by a segment:offset
pair. The memory addresses are physical memory addresses and you have access to the first 1MB of RAM.
Physical address is calculated by segment shifted left by 4 bits + offset.
Thus 8000h:100h is the same address as 8010h:0h , physical address is 80100h in the memory.

Some modern machines have EFI instead of BIOS and those boot in the "protected mode" from the start. MAC machines are like that.


问:
Getting a lot of crashes from android youtube player api
I am using version 1.2.1 (tried with latest version 1.2.2) of android's youtube player api. It works fine on most of the devices. However now and then, I keep on getting crashes on crashlytics. I am getting the following crashes

```<code>Fatal Exception: java.lang.IllegalStateException: android.os.TransactionTooLargeException
   at com.google.android.youtube.api.jar.client.RemoteEmbeddedPlayer.x(SourceFile:558)
   at bpd.w(SourceFile:576)
   at tef.onTransact(SourceFile:390)
   at android.os.Binder.transact(Binder.java:395)
   at com.google.android.youtube.player.internal.d$a$a.r(Unknown Source)
   at com.google.android.youtube.player.internal.s.h(Unknown Source)
   at com.google.android.youtube.player.YouTubePlayerView.e(Unknown Source)
   at com.google.android.youtube.player.YouTubePlayerSupportFragment.onSaveInstanceState(Unknown Source)
   at android.support.v4.app.Fragment.performSaveInstanceState(Fragment.java:1936)
   at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1654)
   at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1722)
   at android.support.v4.app.Fragment.performSaveInstanceState(Fragment.java:1938)
   at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1654)
   at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1722)
   at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:527)
   at com.newshunt.news.activities.NewsBaseActivity.onSaveInstanceState(NewsBaseActivity.java:56)
   at com.newshunt.news.activities.NewsDetailsActivity.onSaveInstanceState(NewsDetailsActivity.java:613)
   at android.app.Activity.performSaveInstanceState(Activity.java:1388)
   at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1286)
   at android.app.ActivityThread.callCallActivityOnSaveInstanceState(ActivityThread.java:4588)
   at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3960)
   at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4023)
   at android.app.ActivityThread.access$1200(ActivityThread.java:181)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1498)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:145)
   at android.app.ActivityThread.main(ActivityThread.java:6117)
   at java.lang.reflect.Method.invoke(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
</code>```

Also getting crashes for the following exception.

```<code>Fatal Exception: java.lang.IllegalStateException: android.os.DeadObjectException
   at com.google.android.apps.youtube.api.jar.a.eo.surfaceDestroyed(SourceFile:236)
   at android.view.SurfaceView.updateWindow(SurfaceView.java:589)
   at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:237)
   at android.view.View.dispatchDetachedFromWindow(View.java:12854)
   at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:2757)
   at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:2757)
   at android.view.ViewGroup.removeViewInternal(ViewGroup.java:3844)
   at android.view.ViewGroup.removeViewInternal(ViewGroup.java:3819)
   at android.view.ViewGroup.removeView(ViewGroup.java:3751)
   at com.google.android.youtube.player.YouTubePlayerView$1.b(Unknown Source)
   at com.google.android.youtube.player.internal.r.h(Unknown Source)
   at com.google.android.youtube.player.internal.r$e.onServiceDisconnected(Unknown Source)
   at android.app.LoadedApk$ServiceDispatcher.doDeath(LoadedApk.java:1111)
   at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1125)
   at android.os.Handler.handleCallback(Handler.java:725)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:176)
   at android.app.ActivityThread.main(ActivityThread.java:5317)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:511)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
   at dalvik.system.NativeStart.main(NativeStart.java)
</code>```

The crash happens to appear in specific versions of youtube application like 5.2.27. Although there are a lot of issues filed for these crashes, there has been no reply from the youtube developers on how to mitigate this issue.

Some of the fellow developers have suggested the following workarounds

1) Use loadVideo instead of cueVideo. But I cannot use this workaround because loadVideo always autoplays the video which is not a requirement of my application. Also someone mentioned that with loadVideo also, this problem is happening although in some different version.

2) Put check in the code to check the youtube application version and then put the specific code. Now the problem with this approach is that I have to check each and every version of youtube app ever released and check which versions are causing the issue which is not a good workaround.

Now is there any fix which I can apply to avoid this issue or are the youtube developers planning to release some jar which internally takes care of all these issues?

答:
The android YouTube Player API is not stable, there are known bugs in it. The team from YouTube said that they will release a new version of the library.

For now, the best solution I have found is to build my own library.

Body:
I am using version 1.2.1 (tried with latest version 1.2.2) of android's youtube player api. It works fine on most of the devices. However now and then, I keep on getting crashes on crashlytics. I am getting the following crashes

Fatal Exception: java.lang.IllegalStateException: android.os.TransactionTooLargeException
   at com.google.android.youtube.api.jar.client.RemoteEmbeddedPlayer.x(SourceFile:558)
   at bpd.w(SourceFile:576)
   at tef.onTransact(SourceFile:390)
   at android.os.Binder.transact(Binder.java:395)
   at com.google.android.youtube.player.internal.d$a$a.r(Unknown Source)
   at com.google.android.youtube.player.internal.s.h(Unknown Source)
   at com.google.android.youtube.player.YouTubePlayerView.e(Unknown Source)
   at com.google.android.youtube.player.YouTubePlayerSupportFragment.onSaveInstanceState(Unknown Source)
   at android.support.v4.app.Fragment.performSaveInstanceState(Fragment.java:1936)
   at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1654)
   at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1722)
   at android.support.v4.app.Fragment.performSaveInstanceState(Fragment.java:1938)
   at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1654)
   at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1722)
   at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:527)
   at com.newshunt.news.activities.NewsBaseActivity.onSaveInstanceState(NewsBaseActivity.java:56)
   at com.newshunt.news.activities.NewsDetailsActivity.onSaveInstanceState(NewsDetailsActivity.java:613)
   at android.app.Activity.performSaveInstanceState(Activity.java:1388)
   at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1286)
   at android.app.ActivityThread.callCallActivityOnSaveInstanceState(ActivityThread.java:4588)
   at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3960)
   at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4023)
   at android.app.ActivityThread.access$1200(ActivityThread.java:181)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1498)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:145)
   at android.app.ActivityThread.main(ActivityThread.java:6117)
   at java.lang.reflect.Method.invoke(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

Also getting crashes for the following exception.

Fatal Exception: java.lang.IllegalStateException: android.os.DeadObjectException
   at com.google.android.apps.youtube.api.jar.a.eo.surfaceDestroyed(SourceFile:236)
   at android.view.SurfaceView.updateWindow(SurfaceView.java:589)
   at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:237)
   at android.view.View.dispatchDetachedFromWindow(View.java:12854)
   at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:2757)
   at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:2757)
   at android.view.ViewGroup.removeViewInternal(ViewGroup.java:3844)
   at android.view.ViewGroup.removeViewInternal(ViewGroup.java:3819)
   at android.view.ViewGroup.removeView(ViewGroup.java:3751)
   at com.google.android.youtube.player.YouTubePlayerView$1.b(Unknown Source)
   at com.google.android.youtube.player.internal.r.h(Unknown Source)
   at com.google.android.youtube.player.internal.r$e.onServiceDisconnected(Unknown Source)
   at android.app.LoadedApk$ServiceDispatcher.doDeath(LoadedApk.java:1111)
   at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1125)
   at android.os.Handler.handleCallback(Handler.java:725)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:176)
   at android.app.ActivityThread.main(ActivityThread.java:5317)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:511)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
   at dalvik.system.NativeStart.main(NativeStart.java)

The crash happens to appear in specific versions of youtube application like 5.2.27. Although there are a lot of issues filed for these crashes, there has been no reply from the youtube developers on how to mitigate this issue.

Some of the fellow developers have suggested the following workarounds

1) Use loadVideo instead of cueVideo. But I cannot use this workaround because loadVideo always autoplays the video which is not a requirement of my application. Also someone mentioned that with loadVideo also, this problem is happening although in some different version.

2) Put check in the code to check the youtube application version and then put the specific code. Now the problem with this approach is that I have to check each and every version of youtube app ever released and check which versions are causing the issue which is not a good workaround.

Now is there any fix which I can apply to avoid this issue or are the youtube developers planning to release some jar which internally takes care of all these issues?


问:
Emoijis in JSON, Datapower
I have a mpgw where the request is JSON.
I save the content in a context variable with JSON.stringify(json)
The problem is when  json contains a emoiji eg \uD83D\uDE0D tha variable no longer will be a string, it will be binary and the emoijis is shown as dots.
I need to use the the content of the variable later to calculate hmac so it has to look exact as the original json.

Is there any way to get around this?
Help wold be much appreciated.

We are running firmware: IDG.7.5.2.9

/Jocke D

答:
Ok, from your comment I can conclude that it is the Stringify() that messes it up. This is according to the cookbook for escaping (there is a RFC describing this)...

Try adding your own function for stringify() that will handle unicode better:

```<code>function JSON_stringify(s, emit_unicode) {
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) {
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

ctx.setVar('json', JSON_stringify(json, false));
</code>```

Something like that...

Title: Emoijis in JSON, Datapower

Body:
Ok, from your comment I can conclude that it is the Stringify() that messes it up. This is according to the cookbook for escaping (there is a RFC describing this)...

Try adding your own function for stringify() that will handle unicode better:

function JSON_stringify(s, emit_unicode) {
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) {
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

ctx.setVar('json', JSON_stringify(json, false));

Something like that...


问:
Opencart "You do not have permission to access this page, please refer to your system administrator"
Every time I installed a new extension, I got this error:

error: You do not have permission to access this page, please refer to your system administrator.

I've already gone to System > User Group, and Add permission to new extension modules (both Access Permission and Modify Permission) but no luck.

I tried to install "2checkout" "Ajax Quick CheckOut" " and get the same error.

答:
Go to admin - system - users - user groups
Edit your administrator and select all then save it.
Problem will be solved.</p>


问:
Assign jQuery datepicker to div element and get the value
I want to show a datepicker using jQuery when user click on some text, and after the user select the date on datepicker, I can get the value from the date picker as javascript variable. My code is like this:

```<code><div id="datepicker-container" style="display: none;">
    <div id="select-delivery-date-input"> </div>
</div>
<a id="show-datepicker">Select Delivery Date</a>
<script>
  $("#show-datepicker").click(function(){
      $("#datepicker-container").show();
  });
  $('#select-delivery-date-input').datepicker({
      dateFormat:'yy-m-d',
      minDate: new Date(),
  });
</script>
</code>```

The problem is when the datepicker popup, when I tried to select the date on datepicker popup it won't close the datepicker popup.

Fiddle example

答:
Please find below the altered code:</p>

```<code>$(document).ready(function() {
var selectedDate;

  $("#show-datepicker").click(function(){
      $("#datepicker-container").show();
  });
  $('#select-delivery-date-input').datepicker({
      dateFormat:'yy-m-d',
      minDate: new Date(),
      onSelect: function(date){
      selectedDate = date;
      alert(selectedDate);//selected date is assigned to date1, you can use date1 anywhere
      $("#datepicker-container").hide();
    }
     }
   );
});
</code>```

Body:
I want to show a datepicker using jQuery when user click on some text, and after the user select the date on datepicker, I can get the value from the date picker as javascript variable. My code is like this:

Select Delivery Date

The problem is when the datepicker popup, when I tried to select the date on datepicker popup it won't close the datepicker popup.

Fiddle example

Body:
Please find below the altered code:

$(document).ready(function() {
var selectedDate;

  $("#show-datepicker").click(function(){
      $("#datepicker-container").show();
  });
  $('#select-delivery-date-input').datepicker({
      dateFormat:'yy-m-d',
      minDate: new Date(),
      onSelect: function(date){
      selectedDate = date;
      alert(selectedDate);//selected date is assigned to date1, you can use date1 anywhere
      $("#datepicker-container").hide();
    }
     }
   );
});


问:
How do I read a file line by line while modifying lines as needed?
In Perl, I'm trying to read a file line by line and process each line, modifying it as required.
So far, the only way I'm reading to be able to do this is read the file into an array, modify each element of the array as needed, then when it's finished, output it back to the file.

Is there a better way to do this, perhaps some way I can replace single lines as I go along?

Right now, my processing code looks like this:

```<code>while (my $line = <FILE>)
{
    # process line here
    # ...........

    print FILE $line;
}
</code>```

My code seems to be very close, except that it's replacing one line after the line I'm currently in, so it seems that if I could back the file pointer up by one line, it would write to the correct place in the file.

Am I on the right track? What would I need to do from here to back up the file pointer so it writes to the same line I'm reading from?

Edit:

Out of the answers I received, both using local $^I and Tie::File worked nicely.
I ended up going with Tie::File so I wouldn't have to print out every line of the file. This way if something happens midway through the script, my file won't be messed up.

My new code looks like this:

```<code>use Tie::File;

chomp(my $filename = $ARGV[0]);
tie my @array, 'Tie::File', $filename or die $!;

foreach my $line(@array)
{
    # ...... line processing happens here .......
    # ...... $line is automatically written to file if $line is changed .......
}
</code>```

答:
What would I need to do from here to back up the file pointer so it writes to the same line I'm reading from?

This doesn't help, unless every line you intend to write is the same length as the line you're replacing (in which case the tools you're looking for are seek and tell). For ordinary editing though, the standard file model just doesn't cut it for replacing bits in-place.

Fortunately, Perl comes with a feature that makes what you need easy, called "in-place editing mode", in which the source file is either renamed or unlinked, and the output directed to a new file with the same name. Most often it's used by enabling the -i command-line switch together with the -p or -n switches for line-wise editing, but you can also enable it within a program using the $^I special variable.

Example code:

```<code>{   # Create a scope to localize variables in.
    # If you want to back up the originals, set $^I to ".bak" instead.
    local $^I = "";
    # Set @ARGV to the file you want to process, or a list of files.
    local @ARGV = ("file.txt");

    while (my $line = <>) {
        # Process $line here.
        print $line;
    }
}
</code>```

Body:
In Perl, I'm trying to read a file line by line and process each line, modifying it as required.
So far, the only way I'm reading to be able to do this is read the file into an array, modify each element of the array as needed, then when it's finished, output it back to the file.

Is there a better way to do this, perhaps some way I can replace single lines as I go along?

Right now, my processing code looks like this:

while (my $line = <FILE>)
{
    # process line here
    # ...........

    print FILE $line;
}

My code seems to be very close, except that it's replacing one line after the line I'm currently in, so it seems that if I could back the file pointer up by one line, it would write to the correct place in the file.

Am I on the right track? What would I need to do from here to back up the file pointer so it writes to the same line I'm reading from?

Edit:

Out of the answers I received, both using local $^I and Tie::File worked nicely.
I ended up going with Tie::File so I wouldn't have to print out every line of the file. This way if something happens midway through the script, my file won't be messed up.

My new code looks like this:

use Tie::File;

chomp(my $filename = $ARGV[0]);
tie my @array, 'Tie::File', $filename or die $!;

foreach my $line(@array)
{
    # ...... line processing happens here .......
    # ...... $line is automatically written to file if $line is changed .......
}

Body:
What would I need to do from here to back up the file pointer so it writes to the same line I'm reading from?

This doesn't help, unless every line you intend to write is the same length as the line you're replacing (in which case the tools you're looking for are seek and tell). For ordinary editing though, the standard file model just doesn't cut it for replacing bits in-place.

Fortunately, Perl comes with a feature that makes what you need easy, called "in-place editing mode", in which the source file is either renamed or unlinked, and the output directed to a new file with the same name. Most often it's used by enabling the -i command-line switch together with the -p or -n switches for line-wise editing, but you can also enable it within a program using the $^I special variable.

Example code:

{   # Create a scope to localize variables in.
    # If you want to back up the originals, set $^I to ".bak" instead.
    local $^I = "";
    # Set @ARGV to the file you want to process, or a list of files.
    local @ARGV = ("file.txt");

    while (my $line = <>) {
        # Process $line here.
        print $line;
    }
}


问:
How to show the selected options static from db + angular js
```<code><select name="gender" ng-model="list.gender" data-select-id="bc813756-82d5-45d7-932c-ab9afd0a08da" class="initialized">
    <option value="" disabled="">Gender</option>
    <option ng-selected="list.gender == 'Male'" value="Male" >Male</option>
    <option ng-selected="list.gender == 'Female'" value="Female" >Female</option>
</select>
</code>```

Suppose I am getting the "Male" value from DB, how to show selected option?

答:
In your case, like you only have two options available for the genre (Male or Female) can use true or false:

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

app.controller('MainCtrl', function($scope) {
  // This would be the value get from your DB
  var genreGetFromDB = 'female';

  // Here you validate the value of the genre
  if (genreGetFromDB != 'male') {
    $scope.genre = false;
  } else {
    $scope.genre = true;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="GenreApp">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <select aria-label="ngSelected demo">
      <option>Female</option>
      <option ng-selected="genre">Male</option>
    </select>
  </body>

</html></code>```

Keep Rocking!

Body:
<select name="gender" ng-model="list.gender" data-select-id="bc813756-82d5-45d7-932c-ab9afd0a08da" class="initialized">
    <option value="" disabled="">Gender</option>
    <option ng-selected="list.gender == 'Male'" value="Male" >Male</option>
    <option ng-selected="list.gender == 'Female'" value="Female" >Female</option>
</select>

Suppose I am getting the "Male" value from DB, how to show selected option?

Body:
In your case, like you only have two options available for the genre (Male or Female) can use true or false:

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

app.controller('MainCtrl', function($scope) {
  // This would be the value get from your DB
  var genreGetFromDB = 'female';

  // Here you validate the value of the genre
  if (genreGetFromDB != 'male') {
    $scope.genre = false;
  } else {
    $scope.genre = true;
  }
});

<!DOCTYPE html>
<html ng-app="GenreApp">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <select aria-label="ngSelected demo">
      <option>Female</option>
      <option ng-selected="genre">Male</option>
    </select>
  </body>

</html>

Keep Rocking!


问:
http requests in stenciljs
How can I make http requests (GET / POST / PUT / DELETE) in StencilJS?

I tried using axios as follows: Did npm install axios --save and in the stencil component import axios from 'axios';. As soon as I call axios.get(...)I get the following error message:

[ ERROR ]  bundling: node_modules/axios/lib/adapters/http.js, line: 4

A module cannot import itself

L3:  var utils = require('./../utils');

L4:  var settle = require('./../core/settle');

L5:  var buildURL = require('./../helpers/buildURL');

I understand it might have to do with this issue: https://github.com/ionic-team/stencil/issues/98

However, any recommendations on how to get html requests work within a stencil component?

答: You can even use my component to use Fetch API, just drop the URL and listen for the OK or KO event.</p>

Title: http requests in stenciljs


问:
Why ASP.NET website customErrors mode="Off" not working
Our ASP.NET 4.0 web application on production server (Windows Server 2008 R2 64bit with IIS7.5) is not showing detailed error message despite adding the following settings in the web.config file:

```<code><?xml version="1.0"?>
<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>
</code>```

According to this MSDN article, we should get the detailed error message but we are getting the following custom error message that's displayed on an error page that we direct to in the "catch" block of try/catch when an error occurs:

Application has encounter an error, please try again later. If the problem persists please contact the system admin at: ....."

We also tried this suggestion but still on an error on the try/catch block the above message gets displayed. We even restarted the IIS to make sure the web.config changes get applied but not luck. We have made sure the above settings are not repeated in the web.config file and that there are no other web.config files in the app.

Edit
Moreover, we do not have <deployment ...> element in the machine.config file that means according to this MSDN article, <deployment retail="false"> is the default.

答:
Sometime in the future, comment out the following code in web.config:

```

<p>update the to the following code.</p>

<pre class="lang-xml prettyprint-override"><code><system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" /><!--Depends on your version of .Net--->
    <httpRuntime targetFramework="4.6.1" /><!-- Depends on your version of .Net--->
    <customErrors mode="Off"/> <!-- add this line--->
    <trust level="Full"/> <!-- add this line--->
</system.web>
</code>```

Body:
Our ASP.NET 4.0 web application on production server (Windows Server 2008 R2 64bit with IIS7.5) is not showing detailed error message despite adding the following settings in the web.config file:

<?xml version="1.0"?>
<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

According to this MSDN article, we should get the detailed error message but we are getting the following custom error message that's displayed on an error page that we direct to in the "catch" block of try/catch when an error occurs:

Application has encounter an error, please try again later. If the problem persists please contact the system admin at: ....."

We also tried this suggestion but still on an error on the try/catch block the above message gets displayed. We even restarted the IIS to make sure the web.config changes get applied but not luck. We have made sure the above settings are not repeated in the web.config file and that there are no other web.config files in the app.

Edit
Moreover, we do not have <deployment ...> element in the machine.config file that means according to this MSDN article, <deployment retail="false"> is the default.

Body:
Sometime in the future, comment out the following code in web.config:

 <!--<system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>-->

update the to the following code.

<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" /><!--Depends on your version of .Net--->
    <httpRuntime targetFramework="4.6.1" /><!-- Depends on your version of .Net--->
    <customErrors mode="Off"/> <!-- add this line--->
    <trust level="Full"/> <!-- add this line--->
</system.web>


问:
WCF POST json object
I'm new on web service operations. I'm trying to create web service for my android app.Solution work for search or list operation but problem is that i can not send to object customer

These are my Models and they mapped :

```<code>public class Address
{
    public virtual int ID { get; set; }

    public virtual int CustomerID { get; set; }

    public virtual String City { get; set; }

    public virtual String Phone { get; set; }
}

[DataContract]
public class Customer
{
   [DataMember]
    public virtual int ID { get; set; }

    [DataMember]
    public virtual String Name { get; set; }

    [DataMember]
    public virtual int Age { get; set; }

    [DataMember]
    public virtual String SurName { get; set; }

    [DataMember]
    private IList<Address> address = new List<Address>();

    [DataMember]
    public virtual IList<Address> Addresses
    {
        get { return address; }
        set { address = value; }
    }
}
</code>```

And I try this method but it does not work

```<code>    [WebInvoke(Method = "POST",
    UriTemplate = "CreateCustomer/",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json )]
    public Customer CreateCustomer(Customer customer)
    {
        //Customer customer = JsonConvert.DeserializeObject<Customer>(CustomerJson);
        if(customer == null)
        {
            throw new ArgumentNullException("FAIL");
        }
        CustomerManager cm = new CustomerManager();
        cm.CreateCustomer(customer);

        return customer;
    }
</code>```

And that is my Create method with Nhibernate

```<code>    public Customer CreateCustomer(Customer customer)
    {
        ISession session = this.GetSession();
        using (var tx = session.BeginTransaction())
        {
            try
            {
                this.GetSession().Save(customer); //new NHibernateSessionManager().GetSession();
                this.GetSession().Save(customer.Addresses);
                tx.Commit();

            }
            catch
            {
                tx.Rollback();
            }
        }
        return customer;
    }
</code>```

thanx for advice.

答:
Shouldn't the CreateCustomer() method look like this:

```<code>public Customer CreateCustomer(Customer customer)
{
    using (var session = this.GetSession())
    using (var tx = session.BeginTransaction())
    {
        try
        {
            session.Save(customer);
            session.Save(customer.Addresses); // This could be omitted with cascade

            tx.Commit();
        }
        catch
        {
            tx.Rollback();
        }
    }

    return customer;
}
</code>```

Title: WCF POST json object

Body:
I'm new on web service operations. I'm trying to create web service for my android app.Solution work for search or list operation but problem is that i can not send to object customer

These are my Models and they mapped :

public class Address
{
    public virtual int ID { get; set; }

    public virtual int CustomerID { get; set; }

    public virtual String City { get; set; }

    public virtual String Phone { get; set; }
}

[DataContract]
public class Customer
{
   [DataMember]
    public virtual int ID { get; set; }

    [DataMember]
    public virtual String Name { get; set; }

    [DataMember]
    public virtual int Age { get; set; }

    [DataMember]
    public virtual String SurName { get; set; }

    [DataMember]
    private IList<Address> address = new List<Address>();

    [DataMember]
    public virtual IList<Address> Addresses
    {
        get { return address; }
        set { address = value; }
    }
}

And I try this method but it does not work

    [WebInvoke(Method = "POST",
    UriTemplate = "CreateCustomer/",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json )]
    public Customer CreateCustomer(Customer customer)
    {
        //Customer customer = JsonConvert.DeserializeObject<Customer>(CustomerJson);
        if(customer == null)
        {
            throw new ArgumentNullException("FAIL");
        }
        CustomerManager cm = new CustomerManager();
        cm.CreateCustomer(customer);

        return customer;
    }

And that is my Create method with Nhibernate

    public Customer CreateCustomer(Customer customer)
    {
        ISession session = this.GetSession();
        using (var tx = session.BeginTransaction())
        {
            try
            {
                this.GetSession().Save(customer); //new NHibernateSessionManager().GetSession();
                this.GetSession().Save(customer.Addresses);
                tx.Commit();

            }
            catch
            {
                tx.Rollback();
            }
        }
        return customer;
    }

thanx for advice.

Body:
Shouldn't the CreateCustomer() method look like this:

public Customer CreateCustomer(Customer customer)
{
    using (var session = this.GetSession())
    using (var tx = session.BeginTransaction())
    {
        try
        {
            session.Save(customer);
            session.Save(customer.Addresses); // This could be omitted with cascade

            tx.Commit();
        }
        catch
        {
            tx.Rollback();
        }
    }

    return customer;
}


问:
Checking a column with two attributes
I have list of names that have either one checking account and/or one saving account linked to their direct deposit. 22 means checking and 32 means savings.

If they have just a checking account (22) or just a savings account (32) in the column then I want to have a '100%' in the column next to it. However, if a person has a checking and a savings account, I want to leave it blank. (We have to manually look in another software for the information)

Example

Employee #   Account      Allocated %
 100          22

 100          32

 101          22              100
 102          32              100

How would I go about this?

答:
I'd use something like this:

```<code>UPDATE t1
SET [Allocated %] = 100
FROM YourTable t1
WHERE t1.Account IN (22,32)
    AND NOT EXISTS (
        SELECT 1
        FROM YourTable t2
        WHERE t2.[Employee #] = t1.[Employee #]
            AND t2.Account IN (22,32)
            AND t2.Account <> t1.Account
    )
</code>```

But you should, of course, sanity check it first:

```<code>SELECT *
FROM YourTable
WHERE YourTable.Account IN (22,32)
    AND YourTable.[Employee #] IN (
        SELECT t1.[Employee #]
        FROM YourTable t1
        WHERE t1.Account IN (22,32)
            AND NOT EXISTS (
                SELECT 1
                FROM YourTable t2
                WHERE t2.[Employee #] = t1.[Employee #]
                    AND t2.Account <> t1.Account
                    AND t2.Account IN (22,32)
            )
    )
ORDER BY [Employee #], Account;
</code>```

Title: Checking a column with two attributes

Body:
I'd use something like this:

UPDATE t1
SET [Allocated %] = 100
FROM YourTable t1
WHERE t1.Account IN (22,32)
    AND NOT EXISTS (
        SELECT 1
        FROM YourTable t2
        WHERE t2.[Employee #] = t1.[Employee #]
            AND t2.Account IN (22,32)
            AND t2.Account <> t1.Account
    )

But you should, of course, sanity check it first:

SELECT *
FROM YourTable
WHERE YourTable.Account IN (22,32)
    AND YourTable.[Employee #] IN (
        SELECT t1.[Employee #]
        FROM YourTable t1
        WHERE t1.Account IN (22,32)
            AND NOT EXISTS (
                SELECT 1
                FROM YourTable t2
                WHERE t2.[Employee #] = t1.[Employee #]
                    AND t2.Account <> t1.Account
                    AND t2.Account IN (22,32)
            )
    )
ORDER BY [Employee #], Account;


问:
Deduce return type of a function template from argument types (not from arguments)
I am aware of the very straightforward usage of decltype, as in

```<code>template<typename T, typename F>
auto myfunc(T elem, F func) -> decltype(func(elem))
{
    return func(elem);
}
</code>```

I would like to know whether return type of a function can be deduced without reference to the function arguments, but instead to the argument type, i.e. something akin to decltype(func, T)?

I understand that in this case one is a type and the other is an object, but what I'm trying to do seems to be very natural. Yet I failed to find a simple way of expressing what I want. Any help?

Thank you.

答:
This is exactly what std::declval is for:

```<code>template<typename T, typename F>
auto myfunc(T elem, F func) -> decltype(func(std::declval<T>()))
{
    return func(elem);
}
</code>```

But since you do have an object of that type already, why bother?

Body:
I am aware of the very straightforward usage of decltype, as in

template<typename T, typename F>
auto myfunc(T elem, F func) -> decltype(func(elem))
{
    return func(elem);
}

I would like to know whether return type of a function can be deduced without reference to the function arguments, but instead to the argument type, i.e. something akin to decltype(func, T)?

I understand that in this case one is a type and the other is an object, but what I'm trying to do seems to be very natural. Yet I failed to find a simple way of expressing what I want. Any help?

Thank you.

Body:
This is exactly what std::declval is for:

template<typename T, typename F>
auto myfunc(T elem, F func) -> decltype(func(std::declval<T>()))
{
    return func(elem);
}

But since you do have an object of that type already, why bother?


问:
Unable to connect to remote SQL Server 2005
I have created my asp.net website using database ASPNETDB.MDF but when I try to host my site on server ...

The SQL Server 2005 hosting provider issue me the

```<code>database name dobriyalji
server ip : 69.112.222.220
database username : XXXX
database password : XXXX
</code>```

I have imported all of my ASPNETDB.MDF tables to my server database dobriyalji ...

And I empty the Appdata.mdf and aspnetdb.log file from App_Data Folder ...

When I try to run my site the following error occurs ...

An attempt to attach an auto-named database for file
  Users\Ashish Dobriyal\Documents\Visual Studio
  2008\WebSites\VOLVO\App_Data\ASPNETDB.MDF

failed. A database with the same name exists, or specified file cannot
  be opened, or it is located on UNC share.

MY LOCALHOST CONNECTION STRING :

```<code><connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</code>```

MY REMOTE HOST CONNECTION STRING :

```<code><connectionStrings>
    <add name="vbi_india2kConnectionString" connectionString="Data Source=69.112.222.220;Initial Catalog=dobriyalji;Persist Security Info=True;User ID=XXXX;Password=XXXX" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</code>```

答:
Do you have the physical mdf / ldf files from your development machine. Assuming you do as the error "specified file cannot be opened" is quite clear. So are you on a shared SQL Server with other sites; if so is there a database on the sql server called aspnetdb? You may have to change the name of your database as you attach it in order to get it onto the sql server.</p>

```<code>EXEC sp_attach_db @dbname = N'myASPNetDB',
   @filename1 = N'c:\mypathdata\myaspnet.mdf',
   @filename2 = N'c:\mypathlogs\myaspnet_log.ldf'
</code>```

Body:
I have created my asp.net website using database ASPNETDB.MDF but when I try to host my site on server ...

The SQL Server 2005 hosting provider issue me the

database name dobriyalji
server ip : 69.112.222.220
database username : XXXX
database password : XXXX

I have imported all of my ASPNETDB.MDF tables to my server database dobriyalji ...

And I empty the Appdata.mdf and aspnetdb.log file from App_Data Folder ...

When I try to run my site the following error occurs ...

An attempt to attach an auto-named database for file
  Users\Ashish Dobriyal\Documents\Visual Studio
  2008\WebSites\VOLVO\App_Data\ASPNETDB.MDF

failed. A database with the same name exists, or specified file cannot
  be opened, or it is located on UNC share.

MY LOCALHOST CONNECTION STRING :

<connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

MY REMOTE HOST CONNECTION STRING :

<connectionStrings>
    <add name="vbi_india2kConnectionString" connectionString="Data Source=69.112.222.220;Initial Catalog=dobriyalji;Persist Security Info=True;User ID=XXXX;Password=XXXX" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Body:
Do you have the physical mdf / ldf files from your development machine. Assuming you do as the error "specified file cannot be opened" is quite clear. So are you on a shared SQL Server with other sites; if so is there a database on the sql server called aspnetdb? You may have to change the name of your database as you attach it in order to get it onto the sql server.

EXEC sp_attach_db @dbname = N'myASPNetDB',
   @filename1 = N'c:\mypathdata\myaspnet.mdf',
   @filename2 = N'c:\mypathlogs\myaspnet_log.ldf'


问:
How can I get the OneToOne relationship easily?
I have two model, names User and Account,  the Account to User is one to one relationship:

```<code>class User(AbstractUser):

    real_name = models.CharField(max_length=12, null=True,blank=True)
    phone = models.CharField( max_length=11)
    email_is_validated = models.BooleanField(default=False)
    qq = models.CharField(max_length=10, null=True, blank=True)

class Account(models.Model):

    user = models.OneToOneField(to=User)
    balance = models.DecimalField(max_digits=16, decimal_places=2, default=0.00)
    total_charge = models.DecimalField(max_digits=16, decimal_places=2, default=0.00)
    total_consume = models.DecimalField(max_digits=16, decimal_places=2, default=0.00)
</code>```

So, in this case, in my serializer:

```<code>class OrderCreateSerializer(ModelSerializer):

     def create(self, validated_data):

        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user
</code>```

I get the user, can I use user.account to get the account?
and or whether I need to do something in User model, such as user @property. (those are my whimsical idea)
Or is there a convenient way to get the user's account instance?

答:
Set related_name for your model.

My code example:

```<code>class Profile(models.Model):
    projects = models.ManyToManyField(Project, related_name='profiles')
    ...

class Project(models.Model):
    ...
</code>```

Now I could call Projects from Profile using profile.projects.all()

And I could call Profiles from Project using project.profiles.all()

Docs:
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey.related_name

Body:
I have two model, names User and Account,  the Account to User is one to one relationship:

class User(AbstractUser):

    real_name = models.CharField(max_length=12, null=True,blank=True)
    phone = models.CharField( max_length=11)
    email_is_validated = models.BooleanField(default=False)
    qq = models.CharField(max_length=10, null=True, blank=True)

class Account(models.Model):

    user = models.OneToOneField(to=User)
    balance = models.DecimalField(max_digits=16, decimal_places=2, default=0.00)
    total_charge = models.DecimalField(max_digits=16, decimal_places=2, default=0.00)
    total_consume = models.DecimalField(max_digits=16, decimal_places=2, default=0.00)

So, in this case, in my serializer:

class OrderCreateSerializer(ModelSerializer):

     def create(self, validated_data):

        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user

I get the user, can I use user.account to get the account?
and or whether I need to do something in User model, such as user @property. (those are my whimsical idea)
Or is there a convenient way to get the user's account instance?

Body:
Set related_name for your model.

My code example:

class Profile(models.Model):
    projects = models.ManyToManyField(Project, related_name='profiles')
    ...

class Project(models.Model):
    ...

Now I could call Projects from Profile using profile.projects.all()

And I could call Profiles from Project using project.profiles.all()

Docs:
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey.related_name


问:
How to take screenshot of element using python3 and selenium
I want to take screenshot of the element.
I tried with below mentioned code:

```<code>ElementIs=driver.find_element_by_xpath(".//body/img")
ElementIs.screenshot('abc.jpg')
</code>```

but got error:

```<code>File "C:\Python34\lib\site-packages\selenium-2.47.1-y3.4.egg\selenium\webdriver\remote\webelement.py", line 448, in _execute   return self._parent.execute(command, params)
File "C:\Python34\lib\site-packages\selenium-2.47.1-y3.4.egg\selenium\webdriver\remote\webdriver.py", line 196, in execute self.error_handler.check_response(response)
File "C:\Python34\lib\site-packages\selenium-2.47.1-py3.4.egg\selenium\webdriver\remote\errorhandler.py", line 102, in check_responsevalue = json.loads(value_json)
File "C:\Python34\lib\json\__init__.py", line 318, in loads   return _default_decoder.decode(s)
File "C:\Python34\lib\json\decoder.py", line 343, in decode   obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python34\lib\json\decoder.py", line 361, in raw_decode raise ValueError(errmsg("Expecting value", s, err.value)) from None ValueError: Expecting value: line 1 column 1 (char 0)
</code>```

答:
With Firefox you can:

```<code>driver = webdriver.Firefox()
qr = driver.find_element_by_css_selector('.css_class')
qr.screenshot("abc.jpg")
</code>```

You can use class, id or tags in find_element_by_css_selector.

Body:
I want to take screenshot of the element.
I tried with below mentioned code:

ElementIs=driver.find_element_by_xpath(".//body/img")
ElementIs.screenshot('abc.jpg')

but got error:

File "C:\Python34\lib\site-packages\selenium-2.47.1-y3.4.egg\selenium\webdriver\remote\webelement.py", line 448, in _execute   return self._parent.execute(command, params)
File "C:\Python34\lib\site-packages\selenium-2.47.1-y3.4.egg\selenium\webdriver\remote\webdriver.py", line 196, in execute self.error_handler.check_response(response)
File "C:\Python34\lib\site-packages\selenium-2.47.1-py3.4.egg\selenium\webdriver\remote\errorhandler.py", line 102, in check_responsevalue = json.loads(value_json)
File "C:\Python34\lib\json\__init__.py", line 318, in loads   return _default_decoder.decode(s)
File "C:\Python34\lib\json\decoder.py", line 343, in decode   obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python34\lib\json\decoder.py", line 361, in raw_decode raise ValueError(errmsg("Expecting value", s, err.value)) from None ValueError: Expecting value: line 1 column 1 (char 0)

Body:
With Firefox you can:

driver = webdriver.Firefox()
qr = driver.find_element_by_css_selector('.css_class')
qr.screenshot("abc.jpg")

You can use class, id or tags in find_element_by_css_selector.


问:
get the wanted objects from the array of objects
This is my first question in stackoverflow, So any kind of help is appreciated.

I have an array like this

```<code>var products = [{status:'available', ...},{status:'none', ...},{status:'available', ...},{status:'', ...},{status:'none', ...}]
</code>```

how can I get an array that contains only  products[i].status = 'available' .

I already did this with for loop but isn't there a better method? My code is practically full of loops now & it's not easy to read.

Thank you for you help.

答:
Using  ES5 most broswer support this one:

```<code>products.filter(function(product){return product.status === 'available'})
</code>```

Using  ES6 works too but not all browser support ES6 yet:

```<code>products.filter(product => product.status === 'available')
</code>```

Body:
This is my first question in stackoverflow, So any kind of help is appreciated.

I have an array like this

var products = [{status:'available', ...},{status:'none', ...},{status:'available', ...},{status:'', ...},{status:'none', ...}]

how can I get an array that contains only  products[i].status = 'available' .

I already did this with for loop but isn't there a better method? My code is practically full of loops now & it's not easy to read.

Thank you for you help.

Body:
Using  ES5 most broswer support this one:

products.filter(function(product){return product.status === 'available'})

Using  ES6 works too but not all browser support ES6 yet:

products.filter(product => product.status === 'available')


问:
IO timeout value for Linux and Windows?
If a disk has some problems, the disk driver usually retries it. For example, sometimes Linux SCSI driver will get BUSY status from SCSI drives  and resend the IO. The upper layers (e.g., FS) will wait until:
1. The disk driver can't handle the IO error and directly report error.
2. The disk driver still retries but timeout occurs.

My question is that what's the timeout value in Windows and Linux platforms? For example, if I invoke "write" to send some data to disk synchronously, how long will the system call return if it can't really write data?

Thanks!

答:
On Linux, you can get the IO timeout value from each block device by reading the value on :

/sys/block/mydevice/device/timeout

By default, the value is 60s.

Title: IO timeout value for Linux and Windows?