问:
File processing on load balancing server (Cluster)
I have application in PHP on cluster server. It copy file from aws bucket on server process the file (unzip file. convert PDF to XML using itext java, Read XML and save data to database) and the upload processed file back to bucket.

It works fine for single instance but in load balancing for multiple instances file under process on server disappears.
I can not process file directly from bucket as I can not unzip it on bucket also can not run jar file on bucket. So I have to store file
temporary for processing. Is there any way to handle this situation

答:
What you need is a system which will store the file without losses. There are many alternatives for that.

a) Another server

b) An SQS Queue.
   @strongiz answer above explains it very well.

c) Even another database.

In each of these cases, you need a flag which will define if file is processed or not. when file processing is complete

a) delete the file or,

b) Change the flag

Since, PHP is session oriented, you cant store data there permannently, so, you need to connect to another interface. In case of a database, You can actually store a the file path entry and a flag to determine if file is processed or not. So, even a combo of the 3 might also work.


来源: stackexchange

问:
How to allow only numbers in user input
I'm just starting out in C# and I made this pretty simple calculator. First of all, what do you think about my code, is there anything I should improve? Second, when I ask the user to input 2 numbers, how do I make it so he can only type numbers? If the user types a different character the loop gets stuck and the program crashes.  </p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace App1
{
    class Program
    {
        static void Main(string[] args)
        {
            bool retry = true;
            while (retry)
            {
                retry = true;
                double x1;
                double x2;
                double x3;
                string calc;
                Console.WriteLine("**** Hello, Welcome to Calculator ****");
                Console.WriteLine("Type a number please: ");

                x1 = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("\n Now type another number: ");
                x2 = Convert.ToDouble(Console.ReadLine());

                Console.WriteLine("\n Now please select a calculation:(/,*,+/-)");
                calc = Convert.ToString(Console.ReadLine());
                if (calc == "*")
                {
                    x3 = (x1 * x2);
                    Console.WriteLine("\n Your Numbers equal = " + x3);
                    retry = false;
                }
                else if (calc == "/")
                {
                    x3 = (x1 / x2); Console.WriteLine("\n Your Numbers equal = " + x3);
                    retry = false;
                }
                else if (calc == "+")
                {
                    x3 = (x1 + x2);
                    Console.WriteLine("\n Your Numbers equal = " + x3);
                    retry = false;
                }
                else if (calc == "-")
                {
                    x3 = (x1 - x2);
                    Console.WriteLine("\n Your Numbers equal = " + x3);
                    retry = false;
                }
                else
                {
                    Console.WriteLine("\n Error, please type one of the 4 calculations: ");
                    retry = true;
                }

                //Don't Exit:
                Console.ReadKey();
                //Don't Exit:
            }
        }
    }
}
</code>```

答:
You can use Double.TryParse to make sure that the user's input is a valid double. This method has the benefit of not throwing an exception if it receives invalid input.

Usage works like this:

```<code>double x1;
Console.WriteLine("Type a number please: ");
bool success = Double.TryParse(Console.ReadLine(), out x1);
</code>```

What we are doing here is we are telling C# to attempt to convert the input to a double. If this works, success is true and x1 holds that value. If not, success is false and no exception is thrown.

NOTE: If this syntax is confusing, give the documentation of the out keyword a quick read.

The success variable allows you to know if the user entered a number. You can wrap this all up in a loop so that the program only progresses if the user enters a number like so:

```<code>bool success = false;
double x1;
while (!success)
{
    Console.WriteLine("Type a number please: ");
    success = Double.TryParse(Console.ReadLine(), out x1);
}
</code>```

This loop will repeat again and again until the user has entered a number, at which point it will exit and the input will be stored in x1. You can repeat this for the second number, as well as for the operation input (addition, multiplication etc).

An extra piece of advice if I may, take a look at C#'s switch keyword, which saves you from having to chain so many else if statements, as well as the break keyword which makes the retry variable in your code unnecessary.

EDIT: To prevent "Use of unassigned local variable", you're going to have to give your numbers an initial value. Example:

```<code>double x1 = 0.0;
</code>```

This won't affect the program since, assuming you went with the loop, execution doesn't progress until a valid number has been entered and that value has changed.

ContentLicense: CC BY-SA 3.0

Title: How to allow only numbers in user input

Body:
I'm just starting out in C# and I made this pretty simple calculator. First of all, what do you think about my code, is there anything I should improve? Second, when I ask the user to input 2 numbers, how do I make it so he can only type numbers? If the user types a different character the loop gets stuck and the program crashes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace App1
{
    class Program
    {
        static void Main(string[] args)
        {
            bool retry = true;
            while (retry)
            {
                retry = true;
                double x1;
                double x2;
                double x3;
                string calc;
                Console.WriteLine("**** Hello, Welcome to Calculator ****");
                Console.WriteLine("Type a number please: ");

                x1 = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("\n Now type another number: ");
                x2 = Convert.ToDouble(Console.ReadLine());

                Console.WriteLine("\n Now please select a calculation:(/,*,+/-)");
                calc = Convert.ToString(Console.ReadLine());
                if (calc == "*")
                {
                    x3 = (x1 * x2);
                    Console.WriteLine("\n Your Numbers equal = " + x3);
                    retry = false;
                }
                else if (calc == "/")
                {
                    x3 = (x1 / x2); Console.WriteLine("\n Your Numbers equal = " + x3);
                    retry = false;
                }
                else if (calc == "+")
                {
                    x3 = (x1 + x2);
                    Console.WriteLine("\n Your Numbers equal = " + x3);
                    retry = false;
                }
                else if (calc == "-")
                {
                    x3 = (x1 - x2);
                    Console.WriteLine("\n Your Numbers equal = " + x3);
                    retry = false;
                }
                else
                {
                    Console.WriteLine("\n Error, please type one of the 4 calculations: ");
                    retry = true;
                }

                //Don't Exit:
                Console.ReadKey();
                //Don't Exit:
            }
        }
    }
}

Body:
You can use Double.TryParse to make sure that the user's input is a valid double. This method has the benefit of not throwing an exception if it receives invalid input.

Usage works like this:

double x1;
Console.WriteLine("Type a number please: ");
bool success = Double.TryParse(Console.ReadLine(), out x1);

What we are doing here is we are telling C# to attempt to convert the input to a double. If this works, success is true and x1 holds that value. If not, success is false and no exception is thrown.

NOTE: If this syntax is confusing, give the documentation of the out keyword a quick read.

The success variable allows you to know if the user entered a number. You can wrap this all up in a loop so that the program only progresses if the user enters a number like so:

bool success = false;
double x1;
while (!success)
{
    Console.WriteLine("Type a number please: ");
    success = Double.TryParse(Console.ReadLine(), out x1);
}

This loop will repeat again and again until the user has entered a number, at which point it will exit and the input will be stored in x1. You can repeat this for the second number, as well as for the operation input (addition, multiplication etc).

An extra piece of advice if I may, take a look at C#'s switch keyword, which saves you from having to chain so many else if statements, as well as the break keyword which makes the retry variable in your code unnecessary.

EDIT: To prevent "Use of unassigned local variable", you're going to have to give your numbers an initial value. Example:

double x1 = 0.0;

This won't affect the program since, assuming you went with the loop, execution doesn't progress until a valid number has been entered and that value has changed.


问:
Qt: passing objects to every window
Im a beginner at C++ since I'm a Java-Dev. I'm learning Qt right now.
Now I want in my widget application on central object for holding special functionality (for example a bunch of methods for sending different network-command or something like that). In my mainwindow.cpp I've got this

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //...
    BusinessLogic* bl = new BusinessLogic;
    bl->setMyValue(44);
    this->setBusinessLogic(bl);
    this->getBusinessLogic();

    //...
}

BusinessLogic* MainWindow::getBusinessLogic()
{
    return this->bl;
}

void MainWindow::setBusinessLogic(BusinessLogic* newbl)
{
    this->bl = newbl;
}
</code>```

Where BusinessLogic.cpp is the class which I want to access from all windows in my application. So in my Dialog which get opend when the pushButton is clicked, I try to use the businesslogic instance like this in the constructor

```<code>Dialog::Dialog(QDialog *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    //...
    ((MainWindow*)parent)->getBusinessLogic();
}
</code>```

Unfortunately the program crashes everytime the dialog get instanciated (the line with ((MainWindow*)parent)->getBusinessLogic(); get called.

What can I do?

答:
Don't pass a zero parent or a dangling pointer to the dialog.

But more seriously, verify your assumptions:

```<code>qDebug() << "the parent object is" << parent;
auto p = qobject_cast<MainWindow*>(parent);
if (p)
    p->getBusinessLogic();
</code>```

Debug output will give you some idea of whether a parent is set, and of what type it is at the moment. Remember that during the construction of a MainWindow instance, it goes through being different types (quite literally). So depending on when you construct the child, you might get a parent of type QWidget* or QMainWindow* or MainWindow*. During the destruction you could even get a QObject* parent!

Title: Qt: passing objects to every window

Body:
Im a beginner at C++ since I'm a Java-Dev. I'm learning Qt right now.
Now I want in my widget application on central object for holding special functionality (for example a bunch of methods for sending different network-command or something like that). In my mainwindow.cpp I've got this

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //...
    BusinessLogic* bl = new BusinessLogic;
    bl->setMyValue(44);
    this->setBusinessLogic(bl);
    this->getBusinessLogic();

    //...
}

BusinessLogic* MainWindow::getBusinessLogic()
{
    return this->bl;
}

void MainWindow::setBusinessLogic(BusinessLogic* newbl)
{
    this->bl = newbl;
}

Where BusinessLogic.cpp is the class which I want to access from all windows in my application. So in my Dialog which get opend when the pushButton is clicked, I try to use the businesslogic instance like this in the constructor

Dialog::Dialog(QDialog *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    //...
    ((MainWindow*)parent)->getBusinessLogic();
}

Unfortunately the program crashes everytime the dialog get instanciated (the line with ((MainWindow*)parent)->getBusinessLogic(); get called.

What can I do?

Body:
Don't pass a zero parent or a dangling pointer to the dialog.

But more seriously, verify your assumptions:

qDebug() << "the parent object is" << parent;
auto p = qobject_cast<MainWindow*>(parent);
if (p)
    p->getBusinessLogic();

Debug output will give you some idea of whether a parent is set, and of what type it is at the moment. Remember that during the construction of a MainWindow instance, it goes through being different types (quite literally). So depending on when you construct the child, you might get a parent of type QWidget* or QMainWindow* or MainWindow*. During the destruction you could even get a QObject* parent!


问:
Storing a Windows SID in a Database for Lookup
I have an ASP.NET MVC application where I need to allow to customers configure MembershipProviders based on their environment, but still be able to map that MembershipUser to a concrete User model in our database.

Membership.GetUser() will give me access to the logged-in user's Membership.ProviderUserKey. I can use this to relate to a User record. Our custom SQL provider will just return the User.Id, but AD is a different story. In that case, ProviderUserKey is an IdentityReference.

These lookups will happen very frequently, as you can imagine (although caching can assist in reducing the lookups at the database level).

I can't decide which route is better to go: Storing the SID as a varbinary or varchar column. This column would not be a primary key and would not have a clustered index. Knowing that I can index strings pretty well, and reading a SID in string format is certainly nicer than binary. Anyone willing to share how they solved such a situation?

Update

I don't know how I missed this SO question when I was searching before I posted, but it seems pretty clear that ActiveDirectoryMembershipProvider and ActiveDirectoryMembershipUser are not quite cut out for the task at hand, as they exist today.

An answer in that SO question linked the following article, where the following was stated:

The relative identifier portion of a
  SID is unique relative to the domain,
  so if the domain changes, the relative
  identifier also changes.

Thus when a User object moves from one
  domain to another, a new SID must be
  generated for the user account and
  stored in the Object-SID property.

However, each group and user has an Object-GUID, which will never change, even if the account is moved. Therefore, it would behoove me to use Object-GUID in my User class, and not Object-SID. Otherwise, someone's User record will be abandoned if they are moved and therefore breaking the relationship between their principal and the data they created.

Unfortunately, ActiveDirectoryMembershipUser doesn't let me get at Object-GUID. So, I'll either have to translate the SID to a GUID after ActiveDirectoryMembershipUser does its work, or create my own MembershipProvider that does everything I need on the spot. Unfortunately, this means I might have to duplicate effort already done for me by ActiveDirectoryMembershipProvider.

答:
username is the LAST thing you want to index on.

SIDs only change in an AD when you change a user from one domain to another.  RIDs are split into 2 groups - inbuilt (< 1000) and user RIDs.  Pre-defined users such as Administrator, Guest etc always have the same RID.

If you want to handle movement of users etc, then GUID is the way to go.

username can be changed at any time in Users and Groups management.

this is different to the object name, which is invariant, but I don't believe is mandated unique across a forest.  You can have any number of John Smith users.

I'd look into the ADSI objects.  These are COM objects which should be accessible from ASP.  MSDN explains pretty well.  an ADSearch object can be used to return user attributes (e.g. including DN) from a GUID.

ContentLicense: CC BY-SA 2.5


问:
mysqli_insert_id() expects exactly 1 parameter, 0 given in CodeIgniter
I have a problem, Please Help me. I'm using Code igniter
This is my code.

my Models (M_register.php)

```<code>class M_register extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }

    function add_account($data)
    {
        $this->load->database();
        $this->db->insert('login',$data);
        **return  mysqli_insert_id();**
    }

    function changeActiveState($key)
    {
        $this->load->database();
        $data = array(
           'active' => 1
        );

        $this->db->where('md5(id)', $key);
        $this->db->update('login', $data);

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

And this is partly code in Controller
$data = array(

```<code>        'username' => $username,
        'password' => $password,
        'nama' => $nama,
        'email' => $email,
        'active' => 0
    );
    $this->load->model('m_register');
    **$id = $this->m_register->add_account($data);**
    $encrypted_id = md5($id);
enter code here
</code>```

And this My error:

答:
Pass the database connection variable as parameter</p>

```<code>$query = $this->db->insert('login',$data);
return  mysqli_insert_id($dbconnection);
</code>```

Body:
I have a problem, Please Help me. I'm using Code igniter
This is my code.

my Models (M_register.php)

class M_register extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }

    function add_account($data)
    {
        $this->load->database();
        $this->db->insert('login',$data);
        **return  mysqli_insert_id();**
    }

    function changeActiveState($key)
    {
        $this->load->database();
        $data = array(
           'active' => 1
        );

        $this->db->where('md5(id)', $key);
        $this->db->update('login', $data);

        return true;
    }
}

And this is partly code in Controller
$data = array(

        'username' => $username,
        'password' => $password,
        'nama' => $nama,
        'email' => $email,
        'active' => 0
    );
    $this->load->model('m_register');
    **$id = $this->m_register->add_account($data);**
    $encrypted_id = md5($id);
enter code here

And this My error:

Body:
Pass the database connection variable as parameter

$query = $this->db->insert('login',$data);
return  mysqli_insert_id($dbconnection);


问:
Python version issue when using types.FunctionType
I have a problem with code snippet founded on https://stackoverflow.com/a/10303539/4113228

When I try to compile:

```<code>import types
dynf = types.FunctionType(compile('print("wow")', 'dyn.py', 'exec'), {})
dynf()
</code>```

in file test.py using python2.7, everything working fine,
but when I try with python3.5 I get:

```<code>Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dynf()
  File "dyn.py", line 1, in <module>
NameError: name 'print' is not defined
</code>```

I'm new in python coding and I completly get stuck at this.. Many thanks for any help!

答:
The problem is that you're passing an empty dict as globals - because of this, the compiled code can't access global variables or builtins.

To allow access to builtin functions, use

```<code>import builtins
dynf = types.FunctionType(compile('print("wow")', 'dyn.py', 'exec'), {'__builtins__':builtins})
</code>```

Body:
I have a problem with code snippet founded on https://stackoverflow.com/a/10303539/4113228

When I try to compile:

import types
dynf = types.FunctionType(compile('print("wow")', 'dyn.py', 'exec'), {})
dynf()

in file test.py using python2.7, everything working fine,
but when I try with python3.5 I get:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dynf()
  File "dyn.py", line 1, in <module>
NameError: name 'print' is not defined

I'm new in python coding and I completly get stuck at this.. Many thanks for any help!

Body:
The problem is that you're passing an empty dict as globals - because of this, the compiled code can't access global variables or builtins.

To allow access to builtin functions, use

import builtins
dynf = types.FunctionType(compile('print("wow")', 'dyn.py', 'exec'), {'__builtins__':builtins})


问:
running angular app before e-2-e tests
I have written a few protractor tests against an angular 2 app. Both of them reside in the same repository (app and the tests). I need to run the app (npm start) on localhost before I can run those tests. whats the best way to achieve this?</p>

答:
In addition to @Brine his answer, this is what I did for an Angular 2 project I'm working on. I need to start a server before I can run my tests.

I've created a .js file that will

start the Angular app before running protractor on port 5555

run the protractor tests, if you need to pass arguments you can, but it's not added in this script

I'm using NPM scripts to run protractor, but you can add whatever you want in the const child = child_process.exec('npm run e2e.local'); part

// The server.js file
const express = require('express');
const path = require('path');
const app = express();
const child_process = require('child_process');

const e2e = path.resolve(process.cwd(), './e2e-tests/config/');
const port = 5555;
const appFolder = path.resolve(process.cwd(), './dist/your-app-folder/');

/**
  * Start a server
  */
class Protractor {
  server(port, dir) {
    app.set('port', port);
    // Pass the folder the app should be run from
    app.use(express.static(dir));

    return new Promise((resolve) => {
      let server = app.listen(port, () => {
        resolve(server);
      });
    });
  }
}

/**
 * Start a server and run protractor.
 */
(() => {
  process.env.LANG = 'en_US.UTF-8';
  // I'm having some npm scripts that run the protractor config
  const child = child_process.exec('npm run e2e.local');
  new Protractor()
    // Start the server on port 5555
    .server(port, appFolder)
    .then((server) => {
      // Start protractor
      child.stdout.pipe(process.stdout);
      child.stderr.pipe(process.stderr);
      // Stop the server if Protractor crashes or we're done testing
      child.on('exit', () => {
        server.close();
      });
    });
})();```

I hope this helps you.

Title: running angular app before e-2-e tests

Body:
In addition to @Brine his answer, this is what I did for an Angular 2 project I'm working on. I need to start a server before I can run my tests.

I've created a .js file that will

start the Angular app before running protractor on port 5555

run the protractor tests, if you need to pass arguments you can, but it's not added in this script

I'm using NPM scripts to run protractor, but you can add whatever you want in the const child = child_process.exec('npm run e2e.local'); part

// The server.js file
const express = require('express');
const path = require('path');
const app = express();
const child_process = require('child_process');

const e2e = path.resolve(process.cwd(), './e2e-tests/config/');
const port = 5555;
const appFolder = path.resolve(process.cwd(), './dist/your-app-folder/');

/**
  * Start a server
  */
class Protractor {
  server(port, dir) {
    app.set('port', port);
    // Pass the folder the app should be run from
    app.use(express.static(dir));

    return new Promise((resolve) => {
      let server = app.listen(port, () => {
        resolve(server);
      });
    });
  }
}

/**
 * Start a server and run protractor.
 */
(() => {
  process.env.LANG = 'en_US.UTF-8';
  // I'm having some npm scripts that run the protractor config
  const child = child_process.exec('npm run e2e.local');
  new Protractor()
    // Start the server on port 5555
    .server(port, appFolder)
    .then((server) => {
      // Start protractor
      child.stdout.pipe(process.stdout);
      child.stderr.pipe(process.stderr);
      // Stop the server if Protractor crashes or we're done testing
      child.on('exit', () => {
        server.close();
      });
    });
})();

I hope this helps you.


问:
HTMLUnit EcmaError TypeError
I'm trying to get data from the URL "https://www.mtgstocks.com/lists/1". Through HTMLUnit I'm getting this error and I'm not sure where to go from here. I don't even understand what the error means.

First this is my code:

```<code>import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.io.IOException;

public class Main {
public static void main(String[] args) throws Exception {
    java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
    try {

        WebClient webClient = new WebClient(BrowserVersion.CHROME);
        HtmlPage page = webClient.getPage("https://www.mtgstocks.com/lists/1");
        webClient.getOptions().setJavaScriptEnabled(true);
        //webClient.waitForBackgroundJavaScript(3000);
    } catch (IOException ex) {
        ex.printStackTrace();
        }
    }
}
</code>```

This is my error:

```<code>Exception in thread "main" ======= EXCEPTION START ========
EcmaError: lineNumber=[1] column=[0] lineSource=[<no source>] name=[TypeError] sourceName=[https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js] message=[TypeError: Expected argument of type object, but instead had type object (https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js#1)]
com.gargoylesoftware.htmlunit.ScriptException: TypeError: Expected argument of type object, but instead had type object (https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js#1)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:898)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:637)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:518)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:778)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:754)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:980)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:352)
at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:239)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:258)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:781)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:738)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1243)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1143)
at net.sourceforge.htmlunit.cyberneko.filters.DefaultFilter.endElement(DefaultFilter.java:226)
at net.sourceforge.htmlunit.cyberneko.filters.NamespaceBinder.endElement(NamespaceBinder.java:345)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3154)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2117)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner.scanDocument(HTMLScanner.java:945)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:521)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:472)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.parse(HTMLParser.java:988)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:246)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:188)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:272)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:160)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:520)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:394)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:311)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:459)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:444)
at com.company.Main.main(Main.java:17)
Caused by: net.sourceforge.htmlunit.corejs.javascript.EcmaError: TypeError: Expected argument of type object, but instead had type object (https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js#1)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3915)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3899)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3924)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.typeError1(ScriptRuntime.java:3934)
at net.sourceforge.htmlunit.corejs.javascript.ScriptableObject.ensureScriptableObject(ScriptableObject.java:2194)
at net.sourceforge.htmlunit.corejs.javascript.NativeObject.execIdCall(NativeObject.java:335)
at net.sourceforge.htmlunit.corejs.javascript.IdFunctionObject.call(IdFunctionObject.java:94)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1540)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:800)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:105)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:416)
at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:292)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3264)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.exec(InterpretedFunction.java:115)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$3.doRun(JavaScriptEngine.java:769)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:883)
... 32 more
Enclosed exception:
net.sourceforge.htmlunit.corejs.javascript.EcmaError: TypeError: Expected argument of type object, but instead had type object (https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js#1)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3915)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3899)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3924)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.typeError1(ScriptRuntime.java:3934)
at net.sourceforge.htmlunit.corejs.javascript.ScriptableObject.ensureScriptableObject(ScriptableObject.java:2194)
at net.sourceforge.htmlunit.corejs.javascript.NativeObject.execIdCall(NativeObject.java:335)
at net.sourceforge.htmlunit.corejs.javascript.IdFunctionObject.call(IdFunctionObject.java:94)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1540)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:50)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script.r(https://www.mtgstocks.com:443/inline.c4ea8b629bf43d39fe04.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script.r(https://www.mtgstocks.com:443/inline.c4ea8b629bf43d39fe04.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script.r(https://www.mtgstocks.com:443/inline.c4ea8b629bf43d39fe04.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script.r(https://www.mtgstocks.com:443/inline.c4ea8b629bf43d39fe04.bundle.js:1)
at script(https://www.mtgstocks.com:443/inline.c4ea8b629bf43d39fe04.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:800)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:105)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:416)
at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:292)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3264)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.exec(InterpretedFunction.java:115)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$3.doRun(JavaScriptEngine.java:769)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:883)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:637)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:518)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:778)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:754)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:980)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:352)
at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:239)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:258)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:781)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:738)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1243)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1143)
at net.sourceforge.htmlunit.cyberneko.filters.DefaultFilter.endElement(DefaultFilter.java:226)
at net.sourceforge.htmlunit.cyberneko.filters.NamespaceBinder.endElement(NamespaceBinder.java:345)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3154)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2117)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner.scanDocument(HTMLScanner.java:945)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:521)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:472)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.parse(HTMLParser.java:988)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:246)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:188)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:272)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:160)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:520)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:394)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:311)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:459)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:444)
at com.company.Main.main(Main.java:17)
======= EXCEPTION END ========

Process finished with exit code 1
</code>```

Thank you for your help!

答: Seems to be an bug in HtmlUnit. Please open an issue.</p>

Title: HTMLUnit EcmaError TypeError

Body:
I'm trying to get data from the URL "https://www.mtgstocks.com/lists/1". Through HTMLUnit I'm getting this error and I'm not sure where to go from here. I don't even understand what the error means.

First this is my code:

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.io.IOException;

public class Main {
public static void main(String[] args) throws Exception {
    java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
    try {

        WebClient webClient = new WebClient(BrowserVersion.CHROME);
        HtmlPage page = webClient.getPage("https://www.mtgstocks.com/lists/1");
        webClient.getOptions().setJavaScriptEnabled(true);
        //webClient.waitForBackgroundJavaScript(3000);
    } catch (IOException ex) {
        ex.printStackTrace();
        }
    }
}

This is my error:

Exception in thread "main" ======= EXCEPTION START ========
EcmaError: lineNumber=[1] column=[0] lineSource=[<no source>] name=[TypeError] sourceName=[https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js] message=[TypeError: Expected argument of type object, but instead had type object (https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js#1)]
com.gargoylesoftware.htmlunit.ScriptException: TypeError: Expected argument of type object, but instead had type object (https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js#1)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:898)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:637)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:518)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:778)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:754)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:980)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:352)
at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:239)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:258)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:781)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:738)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1243)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1143)
at net.sourceforge.htmlunit.cyberneko.filters.DefaultFilter.endElement(DefaultFilter.java:226)
at net.sourceforge.htmlunit.cyberneko.filters.NamespaceBinder.endElement(NamespaceBinder.java:345)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3154)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2117)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner.scanDocument(HTMLScanner.java:945)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:521)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:472)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.parse(HTMLParser.java:988)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:246)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:188)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:272)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:160)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:520)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:394)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:311)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:459)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:444)
at com.company.Main.main(Main.java:17)
Caused by: net.sourceforge.htmlunit.corejs.javascript.EcmaError: TypeError: Expected argument of type object, but instead had type object (https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js#1)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3915)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3899)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3924)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.typeError1(ScriptRuntime.java:3934)
at net.sourceforge.htmlunit.corejs.javascript.ScriptableObject.ensureScriptableObject(ScriptableObject.java:2194)
at net.sourceforge.htmlunit.corejs.javascript.NativeObject.execIdCall(NativeObject.java:335)
at net.sourceforge.htmlunit.corejs.javascript.IdFunctionObject.call(IdFunctionObject.java:94)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1540)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:800)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:105)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:416)
at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:292)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3264)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.exec(InterpretedFunction.java:115)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$3.doRun(JavaScriptEngine.java:769)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:883)
... 32 more
Enclosed exception:
net.sourceforge.htmlunit.corejs.javascript.EcmaError: TypeError: Expected argument of type object, but instead had type object (https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js#1)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3915)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3899)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3924)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.typeError1(ScriptRuntime.java:3934)
at net.sourceforge.htmlunit.corejs.javascript.ScriptableObject.ensureScriptableObject(ScriptableObject.java:2194)
at net.sourceforge.htmlunit.corejs.javascript.NativeObject.execIdCall(NativeObject.java:335)
at net.sourceforge.htmlunit.corejs.javascript.IdFunctionObject.call(IdFunctionObject.java:94)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1540)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:50)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script.r(https://www.mtgstocks.com:443/inline.c4ea8b629bf43d39fe04.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script.r(https://www.mtgstocks.com:443/inline.c4ea8b629bf43d39fe04.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script.r(https://www.mtgstocks.com:443/inline.c4ea8b629bf43d39fe04.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at script.r(https://www.mtgstocks.com:443/inline.c4ea8b629bf43d39fe04.bundle.js:1)
at script(https://www.mtgstocks.com:443/inline.c4ea8b629bf43d39fe04.bundle.js:1)
at script(https://www.mtgstocks.com:443/polyfills.eec762705290a3a04ae2.bundle.js:1)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:800)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:105)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:416)
at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:292)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3264)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.exec(InterpretedFunction.java:115)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$3.doRun(JavaScriptEngine.java:769)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:883)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:637)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:518)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:778)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:754)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:980)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:352)
at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:239)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:258)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:781)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:738)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1243)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1143)
at net.sourceforge.htmlunit.cyberneko.filters.DefaultFilter.endElement(DefaultFilter.java:226)
at net.sourceforge.htmlunit.cyberneko.filters.NamespaceBinder.endElement(NamespaceBinder.java:345)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3154)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2117)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner.scanDocument(HTMLScanner.java:945)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:521)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:472)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.parse(HTMLParser.java:988)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:246)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:188)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:272)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:160)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:520)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:394)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:311)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:459)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:444)
at com.company.Main.main(Main.java:17)
======= EXCEPTION END ========

Process finished with exit code 1

Thank you for your help!


问:
To write a function in common lisp that will return the negation of a list
I get this error with my current code:

```<code> LET: illegal variable specification
   (COND (LISTP A (IF (NEGATE A) (NEGATE (REST L)) NIL))
    (T (SETF A (-A) (APPEND (LIST A) (REST L)) (NEGATE (REST L)) NIL)))
</code>```

my current code:

```<code>(defun negate(L)
 (setq x -1)

 (if (not (null L))

  (let ((a (fitst L))
        (cond (listp a
              (if (negate a)
                  (negate (rest L))
                nil))
        (t
         (setf a (-a) (append (list a)(rest L))
               (negate (rest L))
               nil))))
)
))
</code>```

and the test cases it needs to pass

```<code>o List is  (1 2 3 4)
o Output should be: (-1 -2 -3 -4)

o List is  (1 -2 (3 4))
o Output should be: (-1 2 (-3 -4) )
</code>```

答:
In the most polite sense, your code is a bit off. You're learning Lisp this week, aren't you? That's OK! It's a fun language and can really do some awesome things.

So I'm going to walk through the creation of the routine, and take you along the tour.

Your basic case is -

```<code>(defun negate (n)
  (if (> n 0) (- 0 n)))

(map #'negate '(1 2 3 4))
</code>```

Walking the tree is more complex, but let's walk through the ideas.

Essentially, you have three cases to answer: is the current element nil, a list or an atom?

```<code>(if (not (car seq))
  (if (listp (car seq))
    ;;Recurse
    ;;Otherwise negate the current element and append it to the recursed.
</code>```

Let's try a first cut at this:

```<code>(defun negate-seq (seq)
  (if (not seq)
      (return-from negate-seq))

  (if (listp (car seq))
      (negate-seq seq)
    (list (negate (car seq)) (negate-seq (cdr seq)))))
</code>```

That's great!
Except...

```<code>(negate-seq '(1 2)) ==> (-1 (-2 NIL))
</code>```

And...

```<code> (negate-seq '(1 (1 2 -3))) ==> STACK OVERFLOW!
</code>```

Oh boy. We're in trouble now.

First, let's just try a cons instead of a list.
That cleans up the weird nested list problem.

It's obvious that we're gotten into a loop of infinite recursion. That shouldn't be possible, because we've got the not seq guard. Okay, so let's try an debug. I'm using CLISP, and I can trace arguments with:

```<code>(trace 'negate-seq)
</code>```

then,

```<code>(negate-seq '(1 (1 2 -3)))
</code>```

Suddenly I see an explosion of

```<code>1621. Trace: (NEGATE-SEQ '((1 2 -3)))
1622. Trace: (NEGATE-SEQ '((1 2 -3)))
1623. Trace: (NEGATE-SEQ '((1 2 -3)))
1624. Trace: (NEGATE-SEQ '((1 2 -3)))
</code>```

Crikey, I forgot my cdr and to cons up the list case! Hmmmm.

Let's try this:

```<code>(defun negate-seq (seq)
  (if (not seq)
      (return-from negate-seq))

  (if (listp (car seq))
      (cons (negate-seq (car seq))
        (negate-seq (cdr seq)))
    (cons (negate (car seq)) (negate-seq (cdr seq)))))
</code>```

Recurse for the car, recuse on the car, cons them together, we might be on to something.

```<code> (negate-seq '(1 (1 2 -3))) =>  (-1 (-1 -2 NIL)
</code>```

Hmmmm. Let's take a look at the trace.

Trace: (NEGATE-SEQ '(1 (1 2 -3)))

Trace: (NEGATE-SEQ '((1 2 -3)))

Trace: (NEGATE-SEQ '(1 2 -3))

Trace: (NEGATE-SEQ '(2 -3))

Trace: (NEGATE-SEQ '(-3))

Trace: (NEGATE-SEQ 'NIL)

Trace: NEGATE-SEQ ==> NIL

Trace: NEGATE-SEQ ==> (NIL)

Trace: NEGATE-SEQ ==> (-2 NIL)

Trace: NEGATE-SEQ ==> (-1 -2 NIL)

Trace: (NEGATE-SEQ 'NIL)

Trace: NEGATE-SEQ ==> NIL

Trace: NEGATE-SEQ ==> ((-1 -2 NIL))

Trace: NEGATE-SEQ ==> (-1 (-1 -2 NIL))

So I recurse until the -3, then.... it falls off? Odd. Ah! I'm continually grabbing the CDR of things. A CDR is always a list. (cdr '(-3)) is nil!

Let's see here....

(much rummaging around)

Negate returns nil on positive. D'oh.

```<code>(defun negate (n)
  (if ( > n 0)
      (- 0 n)
    n))

(defun negate-seq (seq)
  "Written by Paul Nathan"
  (if (not seq)
      (return-from negate-seq))

  (if (listp (car seq))
      (cons (negate-seq (car seq))
        (negate-seq (cdr seq)))
    (cons (negate (car seq))
      (negate-seq (cdr seq)))))
</code>```

Body:
I get this error with my current code:

 LET: illegal variable specification
   (COND (LISTP A (IF (NEGATE A) (NEGATE (REST L)) NIL))
    (T (SETF A (-A) (APPEND (LIST A) (REST L)) (NEGATE (REST L)) NIL)))

my current code:

(defun negate(L)
 (setq x -1)

 (if (not (null L))

  (let ((a (fitst L))
        (cond (listp a
              (if (negate a)
                  (negate (rest L))
                nil))
        (t
         (setf a (-a) (append (list a)(rest L))
               (negate (rest L))
               nil))))
)
))

and the test cases it needs to pass

o List is  (1 2 3 4)
o Output should be: (-1 -2 -3 -4)

o List is  (1 -2 (3 4))
o Output should be: (-1 2 (-3 -4) )

Body:
In the most polite sense, your code is a bit off. You're learning Lisp this week, aren't you? That's OK! It's a fun language and can really do some awesome things.

So I'm going to walk through the creation of the routine, and take you along the tour.

Your basic case is -

(defun negate (n)
  (if (> n 0) (- 0 n)))

(map #'negate '(1 2 3 4))

Walking the tree is more complex, but let's walk through the ideas.

Essentially, you have three cases to answer: is the current element nil, a list or an atom?

(if (not (car seq))
  (if (listp (car seq))
    ;;Recurse
    ;;Otherwise negate the current element and append it to the recursed.

Let's try a first cut at this:

(defun negate-seq (seq)
  (if (not seq)
      (return-from negate-seq))

  (if (listp (car seq))
      (negate-seq seq)
    (list (negate (car seq)) (negate-seq (cdr seq)))))

That's great!
Except...

(negate-seq '(1 2)) ==> (-1 (-2 NIL))

And...

 (negate-seq '(1 (1 2 -3))) ==> STACK OVERFLOW!

Oh boy. We're in trouble now.

First, let's just try a cons instead of a list.
That cleans up the weird nested list problem.

It's obvious that we're gotten into a loop of infinite recursion. That shouldn't be possible, because we've got the not seq guard. Okay, so let's try an debug. I'm using CLISP, and I can trace arguments with:

(trace 'negate-seq)

then,

(negate-seq '(1 (1 2 -3)))

Suddenly I see an explosion of

1621. Trace: (NEGATE-SEQ '((1 2 -3)))
1622. Trace: (NEGATE-SEQ '((1 2 -3)))
1623. Trace: (NEGATE-SEQ '((1 2 -3)))
1624. Trace: (NEGATE-SEQ '((1 2 -3)))

Crikey, I forgot my cdr and to cons up the list case! Hmmmm.

Let's try this:

(defun negate-seq (seq)
  (if (not seq)
      (return-from negate-seq))

  (if (listp (car seq))
      (cons (negate-seq (car seq))
        (negate-seq (cdr seq)))
    (cons (negate (car seq)) (negate-seq (cdr seq)))))

Recurse for the car, recuse on the car, cons them together, we might be on to something.

 (negate-seq '(1 (1 2 -3))) =>  (-1 (-1 -2 NIL)

Hmmmm. Let's take a look at the trace.

Trace: (NEGATE-SEQ '(1 (1 2 -3)))

Trace: (NEGATE-SEQ '((1 2 -3)))

Trace: (NEGATE-SEQ '(1 2 -3))

Trace: (NEGATE-SEQ '(2 -3))

Trace: (NEGATE-SEQ '(-3))

Trace: (NEGATE-SEQ 'NIL)

Trace: NEGATE-SEQ ==> NIL

Trace: NEGATE-SEQ ==> (NIL)

Trace: NEGATE-SEQ ==> (-2 NIL)

Trace: NEGATE-SEQ ==> (-1 -2 NIL)

Trace: (NEGATE-SEQ 'NIL)

Trace: NEGATE-SEQ ==> NIL

Trace: NEGATE-SEQ ==> ((-1 -2 NIL))

Trace: NEGATE-SEQ ==> (-1 (-1 -2 NIL))

So I recurse until the -3, then.... it falls off? Odd. Ah! I'm continually grabbing the CDR of things. A CDR is always a list. (cdr '(-3)) is nil!

Let's see here....

(much rummaging around)

Negate returns nil on positive. D'oh.

(defun negate (n)
  (if ( > n 0)
      (- 0 n)
    n))

(defun negate-seq (seq)
  "Written by Paul Nathan"
  (if (not seq)
      (return-from negate-seq))

  (if (listp (car seq))
      (cons (negate-seq (car seq))
        (negate-seq (cdr seq)))
    (cons (negate (car seq))
      (negate-seq (cdr seq)))))


问:
Create dynamic switchery
I want to create dynamic switchery and create and button object with jquery and some dynamic variable for this then I want the Html object to append to Html I can't do it below link is my code
Visit jsfiddle.net/eu3a0k3m/2/

my js codes:

```<code>var count = 3;
$("#btn").click(function(){
    CreateInlineChildWithSwitchery(++count);
});
function CreateInlineChildWithSwitchery (countOfChilds){

      var Integer_LastSwitcheryId = count;

      var btn = $('<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">');
console.log(btn)
$('#all-encyclopedia').append(
        $("#tpl ").html()
                                  .replace(/{switchery}/g,btn)
      );

      eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch"+Integer_LastSwitcheryId.toString()+"')");

      eval("switchery" + Integer_LastSwitcheryId.toString() +"={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");

      eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change"+Integer_LastSwitcheryId.toString()+"')");

      eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field"+Integer_LastSwitcheryId.toString()+"')");

  }

  for(i=1;i<4;i++)
      CreateInlineChildWithSwitchery(count++);
</code>```

my Html codes:

```<code><script type="text/tpl" id="tpl">
{switchery}
</script>
<button id="btn">insert Switchery</button>
<div id="all-encyclopedia"></div>
</code>```

答:
I changed my code to below :

HTML  :

```<code><link href="https://alireza-salehi.ir/switchery/switchery.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://alireza-salehi.ir/switchery/switchery.js"></script>
<script type="text/tpl" id="tpl">
{switchery}
</script>
<button id="btn">insert Switchery</button>
<div id="all-encyclopedia">
  <input type="checkbox" id="js-switch1" class="js-switch1 js-check-change1 col-lg-3" data-switchery="true">
</div>
</code>```

js:

```<code>var count = parseInt($("[data-switchery=true]:last").attr('id')[$("[data-switchery=true]:last").attr('id').length-1]) + 1;

var elem1 = document.querySelector('#js-switch1');
var switchery1 = new Switchery(elem1,
{
  color: '#1AB394',
  secondaryColor: '#688ab0'
});

$("#btn").click(function() {
  CreateInlineChildWithSwitchery(++count);
});

function CreateInlineChildWithSwitchery(countOfChilds) {

  var Integer_LastSwitcheryId = count;

  var btn = '<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">';

  $('#all-encyclopedia').append(
    $("#tpl").html()
    .replace(/{switchery}/g, btn)
  );

  eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch" + Integer_LastSwitcheryId.toString() + "')");

  eval("switchery" + Integer_LastSwitcheryId.toString() + "={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");
        console.log(window[ "switchery" + Integer_LastSwitcheryId.toString() ])
  eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change" + Integer_LastSwitcheryId.toString() + "')");

  eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field" + Integer_LastSwitcheryId.toString() + "')");

}

for (i = 1; i < 4; i++)
  CreateInlineChildWithSwitchery(count++);
</code>```

the first button of elements changes to Switchery and other not changed.

Visit: jsfiddle.net/eu3a0k3m/4

Title: Create dynamic switchery

Body:
I want to create dynamic switchery and create and button object with jquery and some dynamic variable for this then I want the Html object to append to Html I can't do it below link is my code
Visit jsfiddle.net/eu3a0k3m/2/

my js codes:

var count = 3;
$("#btn").click(function(){
    CreateInlineChildWithSwitchery(++count);
});
function CreateInlineChildWithSwitchery (countOfChilds){

      var Integer_LastSwitcheryId = count;

      var btn = $('<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">');
console.log(btn)
$('#all-encyclopedia').append(
        $("#tpl ").html()
                                  .replace(/{switchery}/g,btn)
      );

      eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch"+Integer_LastSwitcheryId.toString()+"')");

      eval("switchery" + Integer_LastSwitcheryId.toString() +"={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");

      eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change"+Integer_LastSwitcheryId.toString()+"')");

      eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field"+Integer_LastSwitcheryId.toString()+"')");

  }

  for(i=1;i<4;i++)
      CreateInlineChildWithSwitchery(count++);

my Html codes:

<button id="btn">insert Switchery</button>

Body:
I changed my code to below :

HTML  :

<link href="https://alireza-salehi.ir/switchery/switchery.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://alireza-salehi.ir/switchery/switchery.js"></script>
<script type="text/tpl" id="tpl">
{switchery}
</script>
<button id="btn">insert Switchery</button>
<div id="all-encyclopedia">
  <input type="checkbox" id="js-switch1" class="js-switch1 js-check-change1 col-lg-3" data-switchery="true">
</div>

js:

var count = parseInt($("[data-switchery=true]:last").attr('id')[$("[data-switchery=true]:last").attr('id').length-1]) + 1;

var elem1 = document.querySelector('#js-switch1');
var switchery1 = new Switchery(elem1,
{
  color: '#1AB394',
  secondaryColor: '#688ab0'
});

$("#btn").click(function() {
  CreateInlineChildWithSwitchery(++count);
});

function CreateInlineChildWithSwitchery(countOfChilds) {

  var Integer_LastSwitcheryId = count;

  var btn = '<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">';

  $('#all-encyclopedia').append(
    $("#tpl").html()
    .replace(/{switchery}/g, btn)
  );

  eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch" + Integer_LastSwitcheryId.toString() + "')");

  eval("switchery" + Integer_LastSwitcheryId.toString() + "={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");
        console.log(window[ "switchery" + Integer_LastSwitcheryId.toString() ])
  eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change" + Integer_LastSwitcheryId.toString() + "')");

  eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field" + Integer_LastSwitcheryId.toString() + "')");

}

for (i = 1; i < 4; i++)
  CreateInlineChildWithSwitchery(count++);

the first button of elements changes to Switchery and other not changed.

Visit: jsfiddle.net/eu3a0k3m/4


问:
Target div and previous titles with jQuery
I have an HTML structure like this, and would like to move all the image galleries together with their corresponding titles and subtitles to a different position .image_content

```<code><h2>Some section</h2>
<p></p>
<p></p>
<p></p>

<h2>Some other section</h2>
<h3>Some sub-section</h3>
<p></p>
<p></p>
<p></p>

<h2>Planos</h2>
<div id='gallery-4' class='gallery'>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
</div>

<h2>Fotos</h2>
<h3>Fotos archivo</h3>
<div id='gallery-5' class='gallery'>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
    <dl class='gallery-item'></dl>
</div>
</code>```

So far I've got this code to move the galleries:

```<code>$('.gallery').appendTo('.image_content');
</code>```

But I'm failing to also get the corresponding H2 and H3 titles. I've tried this but it's not working:

```<code>$('.gallery').prev('h2').appendTo('.image_content');
$('.gallery').appendTo('.image_content');
</code>```

This is the expected result (image_content already exists in another part of the code):

```<code><div class="image_content">
    <h2>Planos</h2>
    <div id='gallery-4' class='gallery'>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
    </div>

    <h2>Fotos</h2>
    <h3>Fotos archivo</h3>
    <div id='gallery-5' class='gallery'>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
        <dl class='gallery-item'></dl>
    </div>
</div>
</code>```

答:
.prev() only selects the previous element. So on the second gallery it would try to select the h2, but it won't because it is it is a h3. You can use .prevAll() in conjunction with the :first to select the first element it finds, because .prevAll() selects all previous sibling elements of the specified selector. I didn't use .prevAll() for the h3 selector because on the first gallery it would select the title "Some sub-section". I also added .each() to iterate through each gallery, so you could potentially add conditional statements to use different selectors methods.

It is not the best code in the world, but it should suit your purposes, or at least a good starting point.

$(document).ready(function(){
  $('.gallery').each(function() {
    $(this).prevAll('h2:first').appendTo('.image_content');
    $(this).prev('h3').appendTo('.image_content');
    $(this).appendTo('.image_content');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <h2>Some section</h2>
<p></p>
<p></p>
<p></p>

<h2>Some other section</h2>
<h3>Some sub-section</h3>
<p></p>
<p></p>
<p></p>

<h2>Planos</h2>
<div id='gallery-4' class='gallery'>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
</div>

<h2>Fotos</h2>
<h3>Fotos archivo</h3>
<div id='gallery-5' class='gallery'>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
</div>

<div class="image_content"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script></code>```

EDIT: If you are not able to add a wrapper to each gallery and title then the below code with work in the situations you have described. I have added a couple of conditional statements to check if the previous h2 or h3 exists and if it doesn't then use .prev().prev('h2') and .prev().prev('h3'). This will select an sibling element 2 steps back.

$(document).ready(function(){
  $('.gallery').each(function() {
    var prevH2 = $(this).prev('h2');
    var prevH3 = $(this).prev('h3');
    if(prevH2.length == 0) {
      prevH2 = $(this).prev().prev('h2');
    }
    if(prevH3.length == 0) {
      prevH3 = $(this).prev().prev('h3').appendTo('.image_content');
    }
    prevH2.appendTo('.image_content')
    prevH3.appendTo('.image_content')
    $(this).appendTo('.image_content');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Some section</h2>
<p></p>
<p></p>
<p></p>

<h2>Some other section</h2>
<h3>Some sub-section</h3>
<p></p>
<p></p>
<p></p>

<h2>Planos</h2>
<div id='gallery-4' class='gallery'>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
</div>

<h2>Fotos</h2>
<h3>Fotos archivo</h3>
<div id='gallery-5' class='gallery'>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
</div>

<h3>Fotos archivo</h3>
<div id='gallery-5' class='gallery'>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
</div>

<div class="image_content"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script></code>```

Body:
I have an HTML structure like this, and would like to move all the image galleries together with their corresponding titles and subtitles to a different position .image_content

Some section

Some other section

Some sub-section

Planos

Fotos

Fotos archivo

So far I've got this code to move the galleries:

$('.gallery').appendTo('.image_content');

But I'm failing to also get the corresponding H2 and H3 titles. I've tried this but it's not working:

$('.gallery').prev('h2').appendTo('.image_content');
$('.gallery').appendTo('.image_content');

This is the expected result (image_content already exists in another part of the code):

Planos

Fotos

Fotos archivo

Body:
.prev() only selects the previous element. So on the second gallery it would try to select the h2, but it won't because it is it is a h3. You can use .prevAll() in conjunction with the :first to select the first element it finds, because .prevAll() selects all previous sibling elements of the specified selector. I didn't use .prevAll() for the h3 selector because on the first gallery it would select the title "Some sub-section". I also added .each() to iterate through each gallery, so you could potentially add conditional statements to use different selectors methods.

It is not the best code in the world, but it should suit your purposes, or at least a good starting point.

$(document).ready(function(){
  $('.gallery').each(function() {
    $(this).prevAll('h2:first').appendTo('.image_content');
    $(this).prev('h3').appendTo('.image_content');
    $(this).appendTo('.image_content');
  });
});

 <h2>Some section</h2>
<p></p>
<p></p>
<p></p>

<h2>Some other section</h2>
<h3>Some sub-section</h3>
<p></p>
<p></p>
<p></p>

<h2>Planos</h2>
<div id='gallery-4' class='gallery'>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
</div>

<h2>Fotos</h2>
<h3>Fotos archivo</h3>
<div id='gallery-5' class='gallery'>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
  <dl class='gallery-item'></dl>
</div>

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

EDIT: If you are not able to add a wrapper to each gallery and title then the below code with work in the situations you have described. I have added a couple of conditional statements to check if the previous h2 or h3 exists and if it doesn't then use .prev().prev('h2') and .prev().prev('h3'). This will select an sibling element 2 steps back.

$(document).ready(function(){
  $('.gallery').each(function() {
    var prevH2 = $(this).prev('h2');
    var prevH3 = $(this).prev('h3');
    if(prevH2.length == 0) {
      prevH2 = $(this).prev().prev('h2');
    }
    if(prevH3.length == 0) {
      prevH3 = $(this).prev().prev('h3').appendTo('.image_content');
    }
    prevH2.appendTo('.image_content')
    prevH3.appendTo('.image_content')
    $(this).appendTo('.image_content');
  });
});

<h2>Some section</h2>
<p></p>
<p></p>
<p></p>

<h2>Some other section</h2>
<h3>Some sub-section</h3>
<p></p>
<p></p>
<p></p>

<h2>Planos</h2>
<div id='gallery-4' class='gallery'>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
</div>

<h2>Fotos</h2>
<h3>Fotos archivo</h3>
<div id='gallery-5' class='gallery'>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
</div>

<h3>Fotos archivo</h3>
<div id='gallery-5' class='gallery'>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
 <dl class='gallery-item'></dl>
</div>

<div class="image_content"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>


Title: generate_series in postgresql from field in table

Body:
Postgresql!

I have a table "meeting"

create table meeting (
id SERIAL,
name varchar,
date_start timestamp not null,
period interval default '0:0:0');

And some data

select * from meeting;
+----+---------------+---------------------+--------+
| id |     name      |     date_start      | period |
+----+---------------+---------------------+--------+
|  1 | Måndagsmöte   | 2017-06-06 09:00:00 | 7 days |
|  2 | torsdagssoppa | 2017-06-01 00:00:00 | 7 days |
+----+---------------+---------------------+--------+

And can select comming meetings from this;

select id,name, date from meeting,
generate_series(
(select date_start::timestamptz from meeting where id=1)::timestamp,
'2017-08-01 00:00:00', (select period from meeting where id=1)) as date
 where date > '2017-06-15 00:00:00'
 and date < '2017-07-20 00:00:00' and id=1;

+----+-------------+---------------------+
| id |    name     |        date         |
+----+-------------+---------------------+
|  1 | Måndagsmöte | 2017-06-20 09:00:00 |
|  1 | Måndagsmöte | 2017-06-27 09:00:00 |
|  1 | Måndagsmöte | 2017-07-04 09:00:00 |
|  1 | Måndagsmöte | 2017-07-11 09:00:00 |
|  1 | Måndagsmöte | 2017-07-18 09:00:00 |
+----+-------------+---------------------+

Is there any posibility to relax the "id=1" and have all meetings for all names?

/gh

Body:
According to your data you can use the next query:

select *
from (select id,
             name,
             generate_series(date_start, '2017-08-01 00:00:00', period) date
      from   meeting) mt
where  mt.date > '2017-06-15 00:00:00'
and    mt.date < '2017-07-20 00:00:00'

id | name          | date
-: | :------------ | :------------------
 1 | Måndagsmöte | 2017-06-20 09:00:00
 1 | Måndagsmöte | 2017-06-27 09:00:00
 1 | Måndagsmöte | 2017-07-04 09:00:00
 1 | Måndagsmöte | 2017-07-11 09:00:00
 1 | Måndagsmöte | 2017-07-18 09:00:00
 2 | torsdagssoppa | 2017-06-22 00:00:00
 2 | torsdagssoppa | 2017-06-29 00:00:00
 2 | torsdagssoppa | 2017-07-06 00:00:00
 2 | torsdagssoppa | 2017-07-13 00:00:00

dbfiddle here


问:
Does Vert.x has real concurrency for single verticles?
the question might look like a troll but it is actually about how vert.x manages concurrency since a verticle itself runs in a dedicated thread.

Let's look at this simple vert.x http server written in Java:

```<code>import org.vertx.java.core.Handler;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.platform.Verticle;

public class Server extends Verticle {
    public void start() {
        vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() {
           public void handle(HttpServerRequest req) {
                req.response().end("Hello");
           }
        }).listen(8080);
    }
}
</code>```

As far as I understand the docs, this whole file represents a verticle. So the start method is called within the dedicated verticle thread, so far so good. But where is the requestHandler invoked ? If it is invoked on exactly this thread I can't see where it is better than node.js.

I'm pretty familiar with Netty, which is the network/concurrency library vert.x is based on. Every incoming connection is mapped to a dedicated thread which scales quite nicely. So.. does this mean that incoming connections represent verticles as well ? But how can then the verticle instance "Server" communicate with those clients ? In fact I would say that this concept is as limited as Node.js.

Please help me to understand the concepts right!

Regards,
Chris

答:
As you correctly answered to yourself, vertex indeed uses async non-blocking programming (like node.js) so you can't do blocking operations because you would otherwise stop the whole (application) world from turning.

You can scale servers as you correctly stated, by spawning more (n=CPU cores) verticle instances, each trying to listen on same TCP/HTTP port.

Where it shines compared to node.js is that the JVM itself is multi-threaded, which gives you more advantages (from the runtime point of view, not including type safety of Java etc etc):

Multithreaded (cross-verticle) communication, while still being constrained to thread-safe Actor-like model, does not require IPC (Inter Process Communication) to pass messages between verticles - everything happens inside the same process, same memory region. Which is faster than node.js spawning every forked task in a new system process and using IPC to communicate

Ability to do compute-heavy and/or blocking tasks within the same JVM process: http://vertx.io/docs/vertx-core/java/#blocking_code or http://vertx.io/docs/vertx-core/java/#worker_verticles

Speed of HotSpot JVM compared to V8 :)

Body:
the question might look like a troll but it is actually about how vert.x manages concurrency since a verticle itself runs in a dedicated thread.

Let's look at this simple vert.x http server written in Java:

import org.vertx.java.core.Handler;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.platform.Verticle;

public class Server extends Verticle {
    public void start() {
        vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() {
           public void handle(HttpServerRequest req) {
                req.response().end("Hello");
           }
        }).listen(8080);
    }
}

As far as I understand the docs, this whole file represents a verticle. So the start method is called within the dedicated verticle thread, so far so good. But where is the requestHandler invoked ? If it is invoked on exactly this thread I can't see where it is better than node.js.

I'm pretty familiar with Netty, which is the network/concurrency library vert.x is based on. Every incoming connection is mapped to a dedicated thread which scales quite nicely. So.. does this mean that incoming connections represent verticles as well ? But how can then the verticle instance "Server" communicate with those clients ? In fact I would say that this concept is as limited as Node.js.

Please help me to understand the concepts right!

Regards,
Chris


问:
Fail to push to Heroku: /app/.heroku/python/bin/pip:No such file or directory
I am trying to push a Django project to Heroku, but it keeps telling me that the following:

```<code>/app/.heroku/python/bin/pip: No such file or directory
</code>```

The complete error message is shown below. How can I address this issue? Do I need to first install pip on Heroku?

```<code>Counting objects: 451, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (383/383), done.
Writing objects: 100% (451/451), 1.07 MiB | 349.00 KiB/s, done.
Total 451 (delta 87), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing python-3.5.1
remote: -----> Installing pip
remote: -----> Installing requirements with pip
remote:        /app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51
/bin/steps/pip-install: line 5: /app/.heroku/python/bin/pip: No such file or directory
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !   Push rejected to rocky-tor-70537.
remote:
To https://git.heroku.com/rocky-tor-70537.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/rocky-tor-70537.git'
</code>```

My requirements.txt file is empty, as shown below.

```<code># this is for Heroku and other servers.
# Locally, you should install requirements_base.txt
-r requirements_server.txt
</code>```

My requirements_server.txt is as follows:

```<code>-r requirements_base.txt
# packages that are unnecessary on Windows/Mac local dev environments, or don't install properly
psycopg2>=2.5.1
</code>```

My requirements_base.txt is as follows:

```<code>appdirs==1.4.3
asgi-redis==0.14.1
asgiref==0.14.0
autobahn==0.16.0
Babel==2.3.4
boto==2.42.0
channels==0.17.3
colorama==0.3.7
contextlib2==0.5.4
coverage==4.2
daphne==0.14.3
dj-database-url==0.4.1
Django==1.8.8
django-countries==4.0
django-easymoney==0.7.1
django-floppyforms==1.7.0
django-idmap==0.4.1
django-vanilla-views==1.0.4
djangorestframework==3.4.6
honcho==0.7.1
huey==1.2.0
IPy==0.83
mock==2.0.0
msgpack-python==0.4.8
otree-core==1.2.8
otree-save-the-change==1.1.3
packaging==16.8
pbr==1.10.0
py==1.4.31
pyparsing==2.2.0
pytest==2.9.2
pytest-django==3.0.0
python-redis-lock==3.2.0
pytz==2016.6.1
raven==5.25.0
redis==2.10.5
requests==2.11.1
schema==0.6.2
six==1.10.0
Twisted==16.2.0
txaio==2.5.1
unicodecsv==0.14.1
whitenoise==3.2.1
ws4py==0.3.5
XlsxWriter==0.9.3
zope.interface==4.2.0
</code>```

答:
I simply had two typos in my runtime.txt

Make sure it says python-3.6.1 and not Python-3.6.1 or python 3.6.1

The error message is pretty bad. May this post save someone 30 minutes.

Body:
I am trying to push a Django project to Heroku, but it keeps telling me that the following:

/app/.heroku/python/bin/pip: No such file or directory

The complete error message is shown below. How can I address this issue? Do I need to first install pip on Heroku?

Counting objects: 451, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (383/383), done.
Writing objects: 100% (451/451), 1.07 MiB | 349.00 KiB/s, done.
Total 451 (delta 87), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing python-3.5.1
remote: -----> Installing pip
remote: -----> Installing requirements with pip
remote:        /app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51
/bin/steps/pip-install: line 5: /app/.heroku/python/bin/pip: No such file or directory
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !   Push rejected to rocky-tor-70537.
remote:
To https://git.heroku.com/rocky-tor-70537.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/rocky-tor-70537.git'

My requirements.txt file is empty, as shown below.

# this is for Heroku and other servers.
# Locally, you should install requirements_base.txt
-r requirements_server.txt

My requirements_server.txt is as follows:

-r requirements_base.txt
# packages that are unnecessary on Windows/Mac local dev environments, or don't install properly
psycopg2>=2.5.1

My requirements_base.txt is as follows:

appdirs==1.4.3
asgi-redis==0.14.1
asgiref==0.14.0
autobahn==0.16.0
Babel==2.3.4
boto==2.42.0
channels==0.17.3
colorama==0.3.7
contextlib2==0.5.4
coverage==4.2
daphne==0.14.3
dj-database-url==0.4.1
Django==1.8.8
django-countries==4.0
django-easymoney==0.7.1
django-floppyforms==1.7.0
django-idmap==0.4.1
django-vanilla-views==1.0.4
djangorestframework==3.4.6
honcho==0.7.1
huey==1.2.0
IPy==0.83
mock==2.0.0
msgpack-python==0.4.8
otree-core==1.2.8
otree-save-the-change==1.1.3
packaging==16.8
pbr==1.10.0
py==1.4.31
pyparsing==2.2.0
pytest==2.9.2
pytest-django==3.0.0
python-redis-lock==3.2.0
pytz==2016.6.1
raven==5.25.0
redis==2.10.5
requests==2.11.1
schema==0.6.2
six==1.10.0
Twisted==16.2.0
txaio==2.5.1
unicodecsv==0.14.1
whitenoise==3.2.1
ws4py==0.3.5
XlsxWriter==0.9.3
zope.interface==4.2.0


问:
I want to use aggregate function in attribute having integer name in it
I am using following mysql query in relation review(70,60,30) that is having attribute name with integer value

```<code>SELECT AVG(70) FROM `review`;
</code>```

But problem is that I am getting 70.0000 as answer which is not a correct one as it recognize 70 as value not a attribute name..

Plz help...

答:
Try to do it with the table name too:</p>

```<code>SELECT AVG(review.70) FROM `review`;
</code>```

Body:
I am using following mysql query in relation review(70,60,30) that is having attribute name with integer value

SELECT AVG(70) FROM `review`;

But problem is that I am getting 70.0000 as answer which is not a correct one as it recognize 70 as value not a attribute name..

Plz help...

Body:
Try to do it with the table name too:

SELECT AVG(review.70) FROM `review`;


问:
Firebase: What's the correct way to update values?
If my database structure is like this:

and I have this:

```<code>    ref = Database.database().reference().child(passUserID)

    ref?.child("wins").updateChildValues("wins": numerator)
</code>```

where numerator = (games played beforehand) + (games played after logging in), for the second statement it is giving me an error in the expression that I don't know how to fix.

Also if I try to do this instead:

```<code>ref?.child("wins").setValue(numerator)
</code>```

it messes up my data bad and gives a bad instruction error.

答:
If you use .setValue triggers only in the beginning. Instead of .setValue use updateChildValues(.values/.childAdded/.childRemoved etc..) to update the values inside your tree. It will be executed whenever changes occurs to your node.

How to update particular value of child in Firebase DB

Body:
If my database structure is like this:

and I have this:

    ref = Database.database().reference().child(passUserID)

    ref?.child("wins").updateChildValues("wins": numerator)

where numerator = (games played beforehand) + (games played after logging in), for the second statement it is giving me an error in the expression that I don't know how to fix.

Also if I try to do this instead:

ref?.child("wins").setValue(numerator)

it messes up my data bad and gives a bad instruction error.


问:
Clojure - Adding pairs of numbers in a vector
I have a vector [1 2 3 4]. Is there a way of adding each pair to get [(+ 1 2) (+ 2 3) (+ 3 4)]

I tried

```<code>(loop [x 0]
  (when (< x (count y))
    (+ (nth y x) (nth y (+ 1 x)))
    (recur (+ x 1))))
</code>```

But I get an out of bounds error IndexOutOfBoundsException   clojure.lang.PersistentVector.arrayFor (PersistentVector.java:158)

答:
```<code>(fn [xs]
  (map + xs (rest xs)))
</code>```

Body:
I have a vector [1 2 3 4]. Is there a way of adding each pair to get [(+ 1 2) (+ 2 3) (+ 3 4)]

I tried

(loop [x 0]
  (when (< x (count y))
    (+ (nth y x) (nth y (+ 1 x)))
    (recur (+ x 1))))

But I get an out of bounds error IndexOutOfBoundsException   clojure.lang.PersistentVector.arrayFor (PersistentVector.java:158)

Body:
(fn [xs]
  (map + xs (rest xs)))


问:
Database '[DatabaseName]' already exists. Choose a different database name
I'm following this guide illustrating a code-first approach with Entity Framework core. Migrations were functioning correctly until, at some point, I deleted my .mdf file. Since then, executing Update-Database (to apply my migration) throws the following error:
Database 'DatabaseName' already exists. Choose a different database name.

Where exactly is this database? How can I remove it permanently?

According to this answer, I need to detach my database from Sql Server, but I'm not sure how to do that now. In Sql Server Management studio, If I execute sp_detach_db DatabaseName it throws error The database 'DatabaseName' does not exist. Supply a valid database name.

Thanks in advance.

UPDATE
I see I can also reproduce this database already exists error if I have the database attached in SQL Server Management Studio, and execute the Update-Database command. After I close the management studio, the migration applies without this error. Very confusing to me.

答:
Try to modify the number code of 'xxxxx-20170604092712' in Web.config file,

and then 'update-database' again. This worked for me.


问:
Netlink sockets
I am trying send a list/array of struct to kernel space from userspace. Similar to Link
As recommended there, I am thinking of using sockets for which i found link. Message is set hello in this line

```<code>strcpy(NLMSG_DATA(nlh), "Hello");
</code>```

I tried

```<code>NLMSG_DATA(nlh) = my_list
</code>```

That gave me error: lvalue required as left operand of assignment.

How can I change this to send an array/list using netlinks? If it can't be send this way, how else easily can I do this?

Update

My structure

```<code>typedef struct {
 int val1;
 int val2;
} mystruct;
</code>```

I need to allocate an array/list of these in kernel memory so other system calls can access that list.

答: You cannot send pointer-based structures using netlink sockets. See the packet structure of netlink: all data must be in a single block.</p>

Title: Netlink sockets

Body:
I am trying send a list/array of struct to kernel space from userspace. Similar to Link
As recommended there, I am thinking of using sockets for which i found link. Message is set hello in this line

strcpy(NLMSG_DATA(nlh), "Hello");

I tried

NLMSG_DATA(nlh) = my_list

That gave me error: lvalue required as left operand of assignment.

How can I change this to send an array/list using netlinks? If it can't be send this way, how else easily can I do this?

Update

My structure

typedef struct {
 int val1;
 int val2;
} mystruct;

I need to allocate an array/list of these in kernel memory so other system calls can access that list.


问:
current member from a custom set
I'm trying to create a custom set and I wanna take the current member of this custom set that I created

```<code>    WITH
    SET [~SET] AS
        Order(
            [especialidade].[nome].Members,
            [Measures].[consulta_valor],
            DESC
        )
    MEMBER [Measures].[prev] AS
         ([especialidade].[id].CurrentMember.PREVMEMBER, [Measures].[consulta_valor])

SELECT  {[Measures].[prev],[Measures].[consulta_valor]} ON 0,
[~SET] on 1
FROM [consulta]
</code>```

My idea is when I'm creating that member use the set that I created to do my interaction, my goal is to see if the measure of the current member is equals to the previous member because I'll put a position in my members and the same values need to have same position.
Someone could help me please?

答:
Try
[especialidade].[nome].currentmember

The set name is just an alias. You are still referencing the nome hierarchy.

Title: current member from a custom set

Body:
I'm trying to create a custom set and I wanna take the current member of this custom set that I created

    WITH
    SET [~SET] AS
        Order(
            [especialidade].[nome].Members,
            [Measures].[consulta_valor],
            DESC
        )
    MEMBER [Measures].[prev] AS
         ([especialidade].[id].CurrentMember.PREVMEMBER, [Measures].[consulta_valor])

SELECT  {[Measures].[prev],[Measures].[consulta_valor]} ON 0,
[~SET] on 1
FROM [consulta]

My idea is when I'm creating that member use the set that I created to do my interaction, my goal is to see if the measure of the current member is equals to the previous member because I'll put a position in my members and the same values need to have same position.
Someone could help me please?


问:
iteritems: match k value lower/upper and white space
I am using a dictionary in Python 2.7.

Below is the code:

```<code>d = {}
with open('input') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value

for k, v in d.iteritems():
    if k == 'items':
</code>```

In input file they mention some times "items" like below:

```<code>items:
Items:
ITEMS:
     Items  :
</code>```

I want to match all of above in my code that is Now I am using

```<code>k == "items":
</code>```

This does not work if "items" in upper case or has whitespaces.

Please help to fix my script.

答:
you can use str.strip and str.lower methods:

```<code>d = {}
with open('test.txt') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value

for k, v in d.iteritems():
    if k.lower().strip() == 'items':
        # do work with single value
</code>```

If you need to process values with similar keys, it may be a good idea to collect them into a list on step of d object creation.

We can do this with dict.setdefault method

```<code>d = {}
with open('test.txt') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        key = key.lower().strip()
        d.setdefault(key, []).append(value)

values = d['items']  # or use `d.get('items', [])` if there may not be 'items' key
# do work with multiple values
</code>```

or with dict extension – defaultdict

```<code>from collections import defaultdict

d = defaultdict(list)
with open('test.txt') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        key = key.lower().strip()
        d[key].append(value)

values = d['items']
# do work with multiple values
</code>```

Body:
I am using a dictionary in Python 2.7.

Below is the code:

d = {}
with open('input') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value

for k, v in d.iteritems():
    if k == 'items':

In input file they mention some times "items" like below:

items:
Items:
ITEMS:
     Items  :

I want to match all of above in my code that is Now I am using

k == "items":

This does not work if "items" in upper case or has whitespaces.

Please help to fix my script.

Body:
you can use str.strip and str.lower methods:

d = {}
with open('test.txt') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value

for k, v in d.iteritems():
    if k.lower().strip() == 'items':
        # do work with single value

If you need to process values with similar keys, it may be a good idea to collect them into a list on step of d object creation.

We can do this with dict.setdefault method

d = {}
with open('test.txt') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        key = key.lower().strip()
        d.setdefault(key, []).append(value)

values = d['items']  # or use `d.get('items', [])` if there may not be 'items' key
# do work with multiple values

or with dict extension – defaultdict

from collections import defaultdict

d = defaultdict(list)
with open('test.txt') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        key = key.lower().strip()
        d[key].append(value)

values = d['items']
# do work with multiple values


问:
JSF session scoped managed beans in cluster environment
I am looking to move a few web applications from a single server environment to a WebSphere clustered environment.  I am looking to see if there are code changes necessary.  The web applications use JSF framework and use managed beans annotated with @SessionScope

I have little knowledge of JSF, but based on what I read, the managed beans need to implement the Serializable interface if they are to be deployed in a clustered environment and that the WebSphere cluster would take care of synchronizing the managed beans, if they can be serialized/de-serialized. Is the above true?

答:
Yes, they are serialized into the HTTPSession which itself can be replicated across a cluster. They can then be recovered in the event of a failover.

In traditional WebSphere, this is via "memory to memory session replication" (a peer-to-peer architecture) or by using a shared database.  In the Liberty Profile, you can use DB, WebSphere Extreme Scale (WXS) or other memory grids (like hazelcast) for session replication.

The settings for session replication will determine how up-to-date your sessions coped beans are in the case of a failover.

ContentLicense: CC BY-SA 4.0


问:
How to convert Int to decimal in Node-Red?
I want to convert a decimal number to 16 bit binary from a register that node-red reads with modbus.</p>

答:
If you just want to test bits at specific offsets then you should portably be using bitwise operators like & and |

If you want to visualise the binary output the use the by toString(radix) method where the radix should be 2.

E.g. in a function node assuming the value to cover is in the msg.payload

```<code>msg.paload = msg.payload.toString(2);
return msg;
</code>```

Body:
If you just want to test bits at specific offsets then you should portably be using bitwise operators like & and |

If you want to visualise the binary output the use the by toString(radix) method where the radix should be 2.

E.g. in a function node assuming the value to cover is in the msg.payload

msg.paload = msg.payload.toString(2);
return msg;