问:
Check functions within class for True
(Python 3.6.3 on Windows 7 64 Bit using eclipse Oxygen)

i am trying to return the values of the function which returns True. You enter the relevant parameters a,v,s,j and depending on the results a specific case takes place. I have tried using callable but since all of them are callable it doesn't work. Using dict.items() has not worked either.

Maybe it is somehow possible to use a for-loop trying iterate through the class looking for True and break the loop. Unfortunately I was not able to set up such a for-loop. I am grateful for any help.

```<code>class cases(object):

    def __init__(self, a, v, s, j):
        self.a = a
        self.v = v
        self.s = s
        self.j = j

    def case_one(self, a, v, s, j):
        tj = pow((s/(2*j)),1/3)
        a_max = tj * j
        v_max = j*(tj**2)
        if a >= a_max and v >= v_max:
            x = True
        else:
            x = False
        return x, tj, a_max, v_max
    pass

    def case_two(self, a, v, s, j):
        tj = pow(v/j, 1/2)
        tv = (s/(j*tj**2)-2*tj)
        a_max = tj * j
        if a >= a_max and tv > 0:
            x = True
        else:
            x = False
        return x, tv, tj, a_max
    pass

    def case_three(self, a, v, s, j):
        ta = (a/j)*(-3/2+pow((1/4)+(s*j**2/pow(a,3)),1/2))
        tj = a/j
        v_max = j*tj*(ta+tj)
        if v >= v_max and ta > 0:
            x = True
        else:
            x = False
        return x, ta, tj, v_max
    pass

    def case_four(self, a, v, s, j):
        tj = a/j
        ta = (v/a)-(a/j)
        tv = (s/v)-(v/a)-(a/j)
        if tv > 0 and ta > 0:
            x = True
        else:
            x = False
        return x, tj, ta, tv
    pass

    def __call__(self):
        self.case_one()
        self.case_two()
        self.case_three()
        self.case_four()

case = cases.case_four(1,14.5,7,0.25,120)
print(case)
</code>```

P.S.:
Apparently I did not fully understand how "self" works within a class since I have to enter a "1" as the very first parameter in order get any results. otherwise i get an error message saying "TypeError: case_four() missing 1 required positional argument: 'j'" but j equals 120.

答:
Make an instance of you class (and rename your class to upper camel case).

=>

```<code>cases = Cases(14.5,7,0.25,120)
</code>```

Remove the arguments from your methods - self already has them since you assgined them to it inside __init__:

=>

```<code> def case_one(self):
        a,v,s,j = self.a, self.v, self.s, self.j   # aliases
        tj = pow((s/(2*j)),1/3)
        a_max = tj * j
        v_max = j*(tj**2)
        x = (a >= a_max and v >= v_max)
        return x, tj, a_max, v_max
</code>```

To loop over the methods to get the reurn values, do something like this. Note that the instance cases is used, not the class Cases:

=>

```<code>for method in [cases.case_one, cases.case_two, cases.case_three, cases.case_four]:
    ret = method()
    if ret[0]:
        print(method.__name__)
        break
else:
    print("no result was True")
</code>```

And remove the pass at the end of every method...

Title: Check functions within class for True

Body:
(Python 3.6.3 on Windows 7 64 Bit using eclipse Oxygen)

i am trying to return the values of the function which returns True. You enter the relevant parameters a,v,s,j and depending on the results a specific case takes place. I have tried using callable but since all of them are callable it doesn't work. Using dict.items() has not worked either.

Maybe it is somehow possible to use a for-loop trying iterate through the class looking for True and break the loop. Unfortunately I was not able to set up such a for-loop. I am grateful for any help.

class cases(object):

    def __init__(self, a, v, s, j):
        self.a = a
        self.v = v
        self.s = s
        self.j = j

    def case_one(self, a, v, s, j):
        tj = pow((s/(2*j)),1/3)
        a_max = tj * j
        v_max = j*(tj**2)
        if a >= a_max and v >= v_max:
            x = True
        else:
            x = False
        return x, tj, a_max, v_max
    pass

    def case_two(self, a, v, s, j):
        tj = pow(v/j, 1/2)
        tv = (s/(j*tj**2)-2*tj)
        a_max = tj * j
        if a >= a_max and tv > 0:
            x = True
        else:
            x = False
        return x, tv, tj, a_max
    pass

    def case_three(self, a, v, s, j):
        ta = (a/j)*(-3/2+pow((1/4)+(s*j**2/pow(a,3)),1/2))
        tj = a/j
        v_max = j*tj*(ta+tj)
        if v >= v_max and ta > 0:
            x = True
        else:
            x = False
        return x, ta, tj, v_max
    pass

    def case_four(self, a, v, s, j):
        tj = a/j
        ta = (v/a)-(a/j)
        tv = (s/v)-(v/a)-(a/j)
        if tv > 0 and ta > 0:
            x = True
        else:
            x = False
        return x, tj, ta, tv
    pass

    def __call__(self):
        self.case_one()
        self.case_two()
        self.case_three()
        self.case_four()

case = cases.case_four(1,14.5,7,0.25,120)
print(case)

P.S.:
Apparently I did not fully understand how "self" works within a class since I have to enter a "1" as the very first parameter in order get any results. otherwise i get an error message saying "TypeError: case_four() missing 1 required positional argument: 'j'" but j equals 120.

Body:
Make an instance of you class (and rename your class to upper camel case).

=>

cases = Cases(14.5,7,0.25,120)

Remove the arguments from your methods - self already has them since you assgined them to it inside __init__:

=>

 def case_one(self):
        a,v,s,j = self.a, self.v, self.s, self.j   # aliases
        tj = pow((s/(2*j)),1/3)
        a_max = tj * j
        v_max = j*(tj**2)
        x = (a >= a_max and v >= v_max)
        return x, tj, a_max, v_max

To loop over the methods to get the reurn values, do something like this. Note that the instance cases is used, not the class Cases:

=>

for method in [cases.case_one, cases.case_two, cases.case_three, cases.case_four]:
    ret = method()
    if ret[0]:
        print(method.__name__)
        break
else:
    print("no result was True")

And remove the pass at the end of every method...


来源: stackexchange

问:
java buffered image created with red mask
I am having trouble reading an image. If I do the following

```<code>URL url = new URL("http://tctechcrunch2011.files.wordpress.com/2012/10/gmm.jpg");
ImageInputStream stream = ImageIO.createImageInputStream(url.openStream());
ImageReader reader = ImageIO.getImageReaders(stream).next();
reader.setInput(stream, true, true);
BufferedImage image = reader.read(0);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageWriter writer = ImageIO.getImageWritersByFormatName("JPEG").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(bos);
writer.setOutput(ios);
IIOImage ioImage = new IIOImage(image, null, null);
writer.write(ioImage);
ios.close();
FileOutputStream fos = new FileOutputStream("badimage.jpeg");
fos.write(bos.toByteArray());
fos.close();
</code>```

the image is written with a red tint. Is there some option that needs to be set to read this image correctly?

答:
Here is a Java Servlet Example for a Workaround whitout using imageIO:</p>

```<code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    //TestImage
    String testImage = "UNC Path or URL.jpg";//Load your image here...

    //Get the streams
    FileInputStream inStream = new FileInputStream(testImage);
    ServletOutputStream outStream = response.getOutputStream();

    //Create the buffers
    BufferedInputStream inBuf = new BufferedInputStream(inStream);
    BufferedOutputStream outBuf = new BufferedOutputStream(outStream);

    //Write input into output
    int ch =0; ;
    while((ch=inBuf.read())!=-1)
        outBuf.write(ch);

    inBuf.close();
    inStream.close();
    outBuf.close();
    outStream.close();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble reading an image. If I do the following

URL url = new URL("http://tctechcrunch2011.files.wordpress.com/2012/10/gmm.jpg");
ImageInputStream stream = ImageIO.createImageInputStream(url.openStream());
ImageReader reader = ImageIO.getImageReaders(stream).next();
reader.setInput(stream, true, true);
BufferedImage image = reader.read(0);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageWriter writer = ImageIO.getImageWritersByFormatName("JPEG").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(bos);
writer.setOutput(ios);
IIOImage ioImage = new IIOImage(image, null, null);
writer.write(ioImage);
ios.close();
FileOutputStream fos = new FileOutputStream("badimage.jpeg");
fos.write(bos.toByteArray());
fos.close();

the image is written with a red tint. Is there some option that needs to be set to read this image correctly?

Body:
Here is a Java Servlet Example for a Workaround whitout using imageIO:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    //TestImage
    String testImage = "UNC Path or URL.jpg";//Load your image here...

    //Get the streams
    FileInputStream inStream = new FileInputStream(testImage);
    ServletOutputStream outStream = response.getOutputStream();

    //Create the buffers
    BufferedInputStream inBuf = new BufferedInputStream(inStream);
    BufferedOutputStream outBuf = new BufferedOutputStream(outStream);

    //Write input into output
    int ch =0; ;
    while((ch=inBuf.read())!=-1)
        outBuf.write(ch);

    inBuf.close();
    inStream.close();
    outBuf.close();
    outStream.close();
}


问:
BeautifulSoup select all href in some element with specific class
I'm trying to scrap images from this website. I tried with Scrapy(using Docker)and with scrapy/slenium. Scrapy seems not to work in windows10 home so I'm now trying with Selenium/Beautifulsoup. I'm using Python 3.6 with Spider into an Anaconda env.

This is how the href elements I need look like:

```<code><a class="emblem" href="detail/emblem/av1615001">
</code>```

I have to major problems:

- how should I select href with Beautifulsoup? Below in my code, you can see what I tried (but didn't work)

- As it is possible to observe the href is only a partial path to url...how should I deal with this issue?

Here my code so far:

```<code>from bs4 import BeautifulSoup
from time import sleep
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import urllib
import requests
from os.path  import basename

def start_requests(self):
        self.driver = webdriver.Firefox("C:/Anaconda3/envs/scrapy/selenium/webdriver")
        #programPause = input("Press the <ENTER> key to continue...")
        self.driver.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
        html = self.driver.page_source

        #html = requests.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
        soup = BeautifulSoup(html, "html.parser")
        emblemshref = soup.select("a", {"class" : "emblem", "href" : True})

        for href in emblemshref:
            link = href["href"]
            with open(basename(link)," wb") as f:
                f.write(requests.get(link).content)

        #click on "next>>"
        while True:
            try:
                next_page = self.driver.find_element_by_xpath("//a[@id='next']")
                sleep(3)
                self.logger.info('Sleeping for 3 seconds')
                next_page.click()

                #here again the same emblemshref loop

            except NoSuchElementException:
                #execute next on the last page
                self.logger.info('No more pages to load')
                self.driver.quit()
                break
</code>```

答:
Try this. It will give you all the urls traversing all the pages in that site. I've used Explicit Wait to make it faster and dynamic.

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup

driver = webdriver.Chrome()
url = "http://emblematica.grainger.illinois.edu/"
wait = WebDriverWait(driver, 10)
driver.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".emblem")))

while True:
    soup = BeautifulSoup(driver.page_source,"lxml")
    for item in soup.select('.emblem'):
        links = url + item['href']
        print(links)

    try:
        link = driver.find_element_by_id("next")
        link.click()
        wait.until(EC.staleness_of(link))
    except Exception:
        break
driver.quit()
</code>```

Partial output:

```<code>http://emblematica.grainger.illinois.edu/detail/emblem/av1615001
http://emblematica.grainger.illinois.edu/detail/emblem/av1615002
http://emblematica.grainger.illinois.edu/detail/emblem/av1615003
</code>```

Body:
I'm trying to scrap images from this website. I tried with Scrapy(using Docker)and with scrapy/slenium. Scrapy seems not to work in windows10 home so I'm now trying with Selenium/Beautifulsoup. I'm using Python 3.6 with Spider into an Anaconda env.

This is how the href elements I need look like:

I have to major problems:

- how should I select href with Beautifulsoup? Below in my code, you can see what I tried (but didn't work)

- As it is possible to observe the href is only a partial path to url...how should I deal with this issue?

Here my code so far:

from bs4 import BeautifulSoup
from time import sleep
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import urllib
import requests
from os.path  import basename

def start_requests(self):
        self.driver = webdriver.Firefox("C:/Anaconda3/envs/scrapy/selenium/webdriver")
        #programPause = input("Press the <ENTER> key to continue...")
        self.driver.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
        html = self.driver.page_source

        #html = requests.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
        soup = BeautifulSoup(html, "html.parser")
        emblemshref = soup.select("a", {"class" : "emblem", "href" : True})

        for href in emblemshref:
            link = href["href"]
            with open(basename(link)," wb") as f:
                f.write(requests.get(link).content)

        #click on "next>>"
        while True:
            try:
                next_page = self.driver.find_element_by_xpath("//a[@id='next']")
                sleep(3)
                self.logger.info('Sleeping for 3 seconds')
                next_page.click()

                #here again the same emblemshref loop

            except NoSuchElementException:
                #execute next on the last page
                self.logger.info('No more pages to load')
                self.driver.quit()
                break

Body:
Try this. It will give you all the urls traversing all the pages in that site. I've used Explicit Wait to make it faster and dynamic.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup

driver = webdriver.Chrome()
url = "http://emblematica.grainger.illinois.edu/"
wait = WebDriverWait(driver, 10)
driver.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".emblem")))

while True:
    soup = BeautifulSoup(driver.page_source,"lxml")
    for item in soup.select('.emblem'):
        links = url + item['href']
        print(links)

    try:
        link = driver.find_element_by_id("next")
        link.click()
        wait.until(EC.staleness_of(link))
    except Exception:
        break
driver.quit()

Partial output:

http://emblematica.grainger.illinois.edu/detail/emblem/av1615001
http://emblematica.grainger.illinois.edu/detail/emblem/av1615002
http://emblematica.grainger.illinois.edu/detail/emblem/av1615003


问:
Adding new task dependencies to built-in SBT tasks?
Is it possible to override or modify built-in SBT tasks (like compile) to depend on custom tasks in my own Build.scala? Overriding e.g. "compile" directly is not possible since it has been defined with lazy val and thus referring to super.compile emits a compiler error "super may be not be used on lazy value".</p>

答:
Since this question appears when Googling how to add a dependency in SBT, and the current answers are deprecated as of 0.13.x and removed in 1.0, here's the updated answer, assuming that printAction is the task that compile should depend on:

(Compile / compile) := ((Compile / compile) dependsOn printAction).value


问:
HQL - INSERT data to one table with mysql ,hibernate
```<code> public static int add_Book(String title, String auth_name, String publisher, String genre) {
     Transaction tx = session.beginTransaction();
    Query query = session.createQuery
             ("INSERT INTO Book(title,auth_name,publisher,genre)"
                    + "SELECT "+title+", "+auth_name+", "+publisher+", "+genre);
     tx.commit();
     return query.executeUpdate();
</code>```

and this error

Exception in thread "AWT-EventQueue-0"
  java.lang.IllegalStateException: No data type for node:
  org.hibernate.hql.internal.ast.tree.IdentNode   +-[IDENT] IdentNode:
  'q' {originalText=q}...

'q' is JTextField data

insert 'q' to 'title'

... Help would BE appreciated..

答:
I think the answer of @v.ladynev is good but you can also try like this :

```<code> public static void addBook(String title, String authName, String publisher, String genre) {

Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
// create book Object
Book book = new Book();
book.setTitle(title);
book.setAuthName(authName);
book.setPublisher(publisher);
book.setGenre(genre);

try {
 tx = session.beginTransaction();
 // Save the book to database
 session.save(book);
 tx.commit();
 }catch(Exception e){
    if (tx!=null) {
     tx.rollback();}
  e.printStackTrace();
 }finally{
 // close your session
 session.close();
 }
}
</code>```

Use at least the Bean class to code "cleanly". We use the query only in special cases, otherwise we must at most avoid it in the code or use at least bundle resources.

Anything else checks that in your Book bean class you havesetAuthName and not setAuth_Name.

Body:
 public static int add_Book(String title, String auth_name, String publisher, String genre) {
     Transaction tx = session.beginTransaction();
    Query query = session.createQuery
             ("INSERT INTO Book(title,auth_name,publisher,genre)"
                    + "SELECT "+title+", "+auth_name+", "+publisher+", "+genre);
     tx.commit();
     return query.executeUpdate();

and this error

Exception in thread "AWT-EventQueue-0"
  java.lang.IllegalStateException: No data type for node:
  org.hibernate.hql.internal.ast.tree.IdentNode   +-[IDENT] IdentNode:
  'q' {originalText=q}...

'q' is JTextField data

insert 'q' to 'title'

... Help would BE appreciated..

Body:
I think the answer of @v.ladynev is good but you can also try like this :

 public static void addBook(String title, String authName, String publisher, String genre) {

Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
// create book Object
Book book = new Book();
book.setTitle(title);
book.setAuthName(authName);
book.setPublisher(publisher);
book.setGenre(genre);

try {
 tx = session.beginTransaction();
 // Save the book to database
 session.save(book);
 tx.commit();
 }catch(Exception e){
    if (tx!=null) {
     tx.rollback();}
  e.printStackTrace();
 }finally{
 // close your session
 session.close();
 }
}

Use at least the Bean class to code "cleanly". We use the query only in special cases, otherwise we must at most avoid it in the code or use at least bundle resources.

Anything else checks that in your Book bean class you havesetAuthName and not setAuth_Name.


问:
LiveList is called twice when updating
I'm using LiveList to bind the children of a group to a list containing the data of the children. here is an example:

```<code>public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        ObservableList<Integer> intList = FXCollections.observableArrayList();
        LiveList<Circle> circleList = LiveList.map(intList, i -> {
            System.out.println("in");
            return new Circle(i);
        });

        Group group = new Group();
        Bindings.bindContent(group.getChildren(), circleList);

        intList.add(2);
        intList.clear();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

My problem is that for each change in intList the bound list is updated twice and which creates more objects than needed. Running the code gives:

```<code>in
in
Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Children: duplicate children added: parent = Group@68887c42
    at javafx.scene.Parent$2.onProposedChange(Parent.java:454)
    at com.sun.javafx.collections.VetoableListDecorator$VetoableSubListDecorator.clear(VetoableListDecorator.java:529)
    at com.sun.javafx.binding.ContentBinding$ListContentBinding.onChanged(ContentBinding.java:114)
    at org.reactfx.collection.ChangeListenerWrapper.onChange(LiveList.java:439)
    at org.reactfx.collection.ChangeListenerWrapper.onChange(LiveList.java:417)
    at org.reactfx.util.ListNotifications.lambda$takeHead$0(NotificationAccumulator.java:317)
    at org.reactfx.ObservableBase.notifyObservers(ObservableBase.java:68)
    at org.reactfx.ObservableBase.notifyObservers(ObservableBase.java:57)
    at org.reactfx.collection.MappedList.sourceChanged(MappedList.java:41)
    at org.reactfx.collection.LiveList.lambda$observeQuasiChanges$7(LiveList.java:256)
    at com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(ListListenerHelper.java:164)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
    at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
    at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
    at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
    at com.sun.javafx.collections.ObservableListWrapper.clear(ObservableListWrapper.java:157)
    at test1.Main.start(Main.java:27)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:748)
</code>```

I want that for each element in intList there will be a Circle in the group's children. Why does this happen and how can I make it work properly?

答:
The exception description is a red herring - the message "duplicate children added" is given whenever at the end of the change the number of children doesn't match what the change predicted it to be.

In your case, what actually happens is that the circle is not removed, so the Group ends up with a single child, yet clear predicted it should have ended with 0.

The reason why the circle is not removed is that it is not the same circle - your mapper creates a new Circle object whenever it is asked to perform the mapping, and so you get 1 circle when adding it, and a completely different one when clearing the list - this new Circle cannot be removed from the children of the group, and so it remains with 1 child even after the call to clear, triggering the exception.

To solve this you would have to make sure you return the same target-object for the same source-object - this may not be possible if your list of integers may contain duplicates.

Title: LiveList is called twice when updating

Body:
I'm using LiveList to bind the children of a group to a list containing the data of the children. here is an example:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        ObservableList<Integer> intList = FXCollections.observableArrayList();
        LiveList<Circle> circleList = LiveList.map(intList, i -> {
            System.out.println("in");
            return new Circle(i);
        });

        Group group = new Group();
        Bindings.bindContent(group.getChildren(), circleList);

        intList.add(2);
        intList.clear();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

My problem is that for each change in intList the bound list is updated twice and which creates more objects than needed. Running the code gives:

in
in
Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Children: duplicate children added: parent = Group@68887c42
    at javafx.scene.Parent$2.onProposedChange(Parent.java:454)
    at com.sun.javafx.collections.VetoableListDecorator$VetoableSubListDecorator.clear(VetoableListDecorator.java:529)
    at com.sun.javafx.binding.ContentBinding$ListContentBinding.onChanged(ContentBinding.java:114)
    at org.reactfx.collection.ChangeListenerWrapper.onChange(LiveList.java:439)
    at org.reactfx.collection.ChangeListenerWrapper.onChange(LiveList.java:417)
    at org.reactfx.util.ListNotifications.lambda$takeHead$0(NotificationAccumulator.java:317)
    at org.reactfx.ObservableBase.notifyObservers(ObservableBase.java:68)
    at org.reactfx.ObservableBase.notifyObservers(ObservableBase.java:57)
    at org.reactfx.collection.MappedList.sourceChanged(MappedList.java:41)
    at org.reactfx.collection.LiveList.lambda$observeQuasiChanges$7(LiveList.java:256)
    at com.sun.javafx.collections.ListListenerHelper$SingleChange.fireValueChangedEvent(ListListenerHelper.java:164)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
    at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
    at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
    at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
    at com.sun.javafx.collections.ObservableListWrapper.clear(ObservableListWrapper.java:157)
    at test1.Main.start(Main.java:27)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:748)

I want that for each element in intList there will be a Circle in the group's children. Why does this happen and how can I make it work properly?


问:
JavaScript: Get parent element values on click event
I'm completely new to JavaScript and struggling to get this working. I'm trying to display contact details in an alert box when a button is clicked.

The information is displayed in nested DIVs outlined below:

```<code><div class="info-and-actions">
<div class="info">
  <div class="name-container">
    <h4 class="name"><a href="#" title="Name" class="name-link">Trader 1</a></h4>
  </div>
<div class="details-container">
  <p class="tele">###############</p>
  <p class="email">hello@url.com</p>
</div>
  <div class="actions">
    <button class="displayContactDetails">Display contact details</button>
  </div>
</div>
</div>

<div class="info-and-actions">
<div class="info">
  <div class="name-container">
    <h4 class="name"><a href="#" title="Name" class="name-link">Trader 2</a></h4>
  </div>
<div class="details-container">
  <p class="tele">###############</p>
  <p class="email">hello@url.com</p>
</div>
  <div class="actions">
    <button class="displayContactDetails">Display contact details</button>
  </div>
</code>```

I am using this JavaScript with an event listener on the displayContactDetails button to display the contact details in the alert box.

```<code>function displayContactDetails() {
var contactName = document.querySelector("a.name-link.profile-link").textContent;
var contactTele = document.querySelector("p.tele").textContent;
alert("Contact " + contactName + " on " + contactTele);
}
</code>```

This currently displays the first trader's contact details when any displayContactDetails button is clicked.

What I want to do is select the relevant contact information from the parent elements of the button (.name-container and .details-container) - so when the second button is clicked, Trader 2's details are displayed.

How do I traverse the DOM to achieve this?

答:
i hope passing a unique info on the function call

          function displayContactDetails(id){
            var contactName = document.getElementById("name-link-"+id).textContent;

            alert("Contact " + contactName );
          }
     ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="info-and-actions">
    <div class="info">
      <div class="name-container">
        <h4 class="name">Trader 1</h4>
      </div>
    <div class="details-container">
      <p class="tele">###############</p>
      <p class="email">hello@url.com</p>
    </div>
      <div class="actions">
        <button class="displayContactDetails" onclick="displayContactDetails('one')">Display contact details</button>
      </div>
    </div>
    </div>

    <div class="info-and-actions">
    <div class="info">
      <div class="name-container">
        <h4 class="name">Trader 2</h4>
      </div>
    <div class="details-container">
      <p class="tele">###############</p>
      <p class="email">hello@url.com</p>
    </div>
      <div class="actions">
        <button class="displayContactDetails" onclick="displayContactDetails('two')">Display contact details</button>
      </div>
    </code>```

Body:
I'm completely new to JavaScript and struggling to get this working. I'm trying to display contact details in an alert box when a button is clicked.

The information is displayed in nested DIVs outlined below:

Trader 1

###############

hello@url.com

    <button class="displayContactDetails">Display contact details</button>

Trader 2

###############

hello@url.com

    <button class="displayContactDetails">Display contact details</button>

I am using this JavaScript with an event listener on the displayContactDetails button to display the contact details in the alert box.

function displayContactDetails() {
var contactName = document.querySelector("a.name-link.profile-link").textContent;
var contactTele = document.querySelector("p.tele").textContent;
alert("Contact " + contactName + " on " + contactTele);
}

This currently displays the first trader's contact details when any displayContactDetails button is clicked.

What I want to do is select the relevant contact information from the parent elements of the button (.name-container and .details-container) - so when the second button is clicked, Trader 2's details are displayed.

How do I traverse the DOM to achieve this?

Body:
i hope passing a unique info on the function call

          function displayContactDetails(id){
            var contactName = document.getElementById("name-link-"+id).textContent;

            alert("Contact " + contactName );
          }

    <div class="info-and-actions">
    <div class="info">
      <div class="name-container">
        <h4 class="name"><a href="#" title="Name" id="name-link-one">Trader 1</a></h4>
      </div>
    <div class="details-container">
      <p class="tele">###############</p>
      <p class="email">hello@url.com</p>
    </div>
      <div class="actions">
        <button class="displayContactDetails" onclick="displayContactDetails('one')">Display contact details</button>
      </div>
    </div>
    </div>

    <div class="info-and-actions">
    <div class="info">
      <div class="name-container">
        <h4 class="name"><a href="#" title="Name" id="name-link-two">Trader 2</a></h4>
      </div>
    <div class="details-container">
      <p class="tele">###############</p>
      <p class="email">hello@url.com</p>
    </div>
      <div class="actions">
        <button class="displayContactDetails" onclick="displayContactDetails('two')">Display contact details</button>
      </div>


问:
Generate tr on click of Image button jquery
I have a scenario where I want to duplicate the existing
 whenever I click on  + button which is:

Below is my
. how to generate this using jquery or javascript

```<code> <tr>
    <td>
        <div class="row noPadding vendorForm">
            <div class="vendorDaterow">
                <div class="vendorName">
                    <label>SP Vender Name</label><span>Shri Kamalkanth Co.</span>
                </div>
                <div class="vendorFromDate">
                    <label>From Date</label><span class="datepicker"><input type="text" id="spFromDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
                <div class="vendorToDate">
                    <label>To Date</label><span class="datepicker"><input type="text" id="spToDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
            </div>
            <div class="add">
                <i class="fa fa-plus" aria-hidden="true"></i>
            </div>
            <i class="max">(Maximum 5 Vendors)</i>

        </div>
    </td>
</tr>
</code>```

答:
Use clone() and after():

$(document).ready(function(){
    $("i.fa-plus").click(function(){
        var val = $("tr:last").clone()
        $("tr:last").after(val)
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
    <td>
        <div class="row noPadding vendorForm">
            <div class="vendorDaterow">
                <div class="vendorName">
                    <label>SP Vender Name</label><span>Shri Kamalkanth Co.</span>
                </div>
                <div class="vendorFromDate">
                    <label>From Date</label><span class="datepicker"><input type="text" id="spFromDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
                <div class="vendorToDate">
                    <label>To Date</label><span class="datepicker"><input type="text" id="spToDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
            </div>

        </div>
    </td>
</tr>
 </table>
            <div class="add">
                <i class="fa fa-plus" aria-hidden="true">+</i>
            </div>
            <i class="max">(Maximum 5 Vendors)</i></code>```

Body:
I have a scenario where I want to duplicate the existing
 whenever I click on  + button which is:

Below is my
. how to generate this using jquery or javascript

                    SP Vender NameShri Kamalkanth Co.

                    From Date<input type="text" id="spFromDate1" />

                    To Date<input type="text" id="spToDate1" />

            (Maximum 5 Vendors)

Body:
Use clone() and after():

$(document).ready(function(){
    $("i.fa-plus").click(function(){
        var val = $("tr:last").clone()
        $("tr:last").after(val)
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
    <td>
        <div class="row noPadding vendorForm">
            <div class="vendorDaterow">
                <div class="vendorName">
                    <label>SP Vender Name</label><span>Shri Kamalkanth Co.</span>
                </div>
                <div class="vendorFromDate">
                    <label>From Date</label><span class="datepicker"><input type="text" id="spFromDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
                <div class="vendorToDate">
                    <label>To Date</label><span class="datepicker"><input type="text" id="spToDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
            </div>

        </div>
    </td>
</tr>
 </table>
            <div class="add">
                <i class="fa fa-plus" aria-hidden="true">+</i>
            </div>
            <i class="max">(Maximum 5 Vendors)</i>


答:
You can use this

(function () {
  var toAddCloneCount = 2;

$('.add').on('click', function() {
  var $tr = $(this).closest('tr');
  var $tr2 = $tr.clone(true, true);
  $tr2.find(".vendorName").children('label').remove();
  $tr2.find(".add").children().remove();
  $tr2.find(".vendorFromDate").children('label').remove();
  $tr2.find(".vendorToDate").children('label').remove();
  $tr2.find('#txtVendorName').prop('id', 'txtVendorName' + toAddCloneCount);
  $tr2.find('#spFromDate1').prop('id', 'spFromDate' + toAddCloneCount);
  $tr2.find('#spToDate1').prop('id', 'spToDate' + toAddCloneCount++);
  $tr2.insertAfter($tr);
});
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.vendorName,.vendorFromDate,.vendorToDate{
width:33%;float:left;}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>

                                            SP Vender Name@*Shri Kamalkanth Co.*@<input type="text" name="nmVendorData" id="txtVendorName" />

                                            From Date<input type="text" id="spFromDate1" />

                                            To Date<input type="text" id="spToDate1" />

                                    (Maximum 5 Vendors)

```

Title: Generate tr on click of Image button jquery

Body:
You can use this

(function () {
  var toAddCloneCount = 2;

$('.add').on('click', function() {
  var $tr = $(this).closest('tr');
  var $tr2 = $tr.clone(true, true);
  $tr2.find(".vendorName").children('label').remove();
  $tr2.find(".add").children().remove();
  $tr2.find(".vendorFromDate").children('label').remove();
  $tr2.find(".vendorToDate").children('label').remove();
  $tr2.find('#txtVendorName').prop('id', 'txtVendorName' + toAddCloneCount);
  $tr2.find('#spFromDate1').prop('id', 'spFromDate' + toAddCloneCount);
  $tr2.find('#spToDate1').prop('id', 'spToDate' + toAddCloneCount++);
  $tr2.insertAfter($tr);
});
})();

.vendorName,.vendorFromDate,.vendorToDate{
width:33%;float:left;}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
                            <td>
                                <div class="row noPadding vendorForm">
                                    <div class="vendorDaterow">
                                        <div class="vendorName">
                                            <label>SP Vender Name</label><span>@*Shri Kamalkanth Co.*@<input type="text" name="nmVendorData" id="txtVendorName" /></span>
                                        </div>
                                        <div class="vendorFromDate">
                                            <label>From Date</label><span class="datepicker"><input type="text" id="spFromDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                        <div class="vendorToDate">
                                            <label>To Date</label><span class="datepicker"><input type="text" id="spToDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                    </div>
                                    <div class="add">
                                        <i class="fa fa-plus" aria-hidden="true"></i>
                                    </div>
                                    <i class="max">(Maximum 5 Vendors)</i>

                                </div>
                            </td>
                        </tr>
</table>


问:
codeigniter insert current time in database by controller
here is my controller code to insert data into database

```<code>$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0'
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);
</code>```

this was working perfectly but when I try to add time like this:

```<code>$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0',
    'time' => NOW()
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);
</code>```

it returns an error like

Fatal error: Call to undefined function NOW() in
  D:\xampp\htdocs\iiht\application\controllers\Status.php on line 47

答:
NOW() is sql function you should use

```<code>date("Y-m-d H:i:s")
</code>```

So your code should be

```<code>$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0',
    'time' => date("Y-m-d H:i:s")
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);
</code>```

Body:
here is my controller code to insert data into database

$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0'
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);

this was working perfectly but when I try to add time like this:

$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0',
    'time' => NOW()
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);

it returns an error like

Fatal error: Call to undefined function NOW() in
  D:\xampp\htdocs\iiht\application\controllers\Status.php on line 47

Body:
NOW() is sql function you should use

date("Y-m-d H:i:s")

So your code should be

$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0',
    'time' => date("Y-m-d H:i:s")
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);


问:
CSS for placeholder box (design-time WYSIWYG)
This is a "silly" but hopefully legitimate if not particularly needful challenge, one that can be reused everywhere by designers, I'm sure, if an answer can be had.

I'm using a WYSIWYG-ish editor (MS Expression Web 4) and am trying to produce HTML-based wireframes which I intend to be the base for actual production. With raw/clean HTML being the #1 objective, I'd like to have a pattern for placeholders whereby I might specify the following HTML (and nothing else, except height, width, and text will vary), which should appear as a rectangular box with an 'X' through it and the text (in this case "logo") appearing at the bottom, or in the middle with white background behind the text:

```<code><div class="placeholder" style="width: 200px; height: 50px;">Logo</div>
</code>```

My question is what is the CSS and the minimum amount of HTML mucking (e.g. img tag) that is required to achieve what I want? For example, if the following HTML is used instead:

```<code><div class="placeholder">
    <img src="placeholder-xbox.png" width="200" height="200"/>
    Logo
</div>
</code>```

or

```<code><div class="placeholder">
    Logo
    <img src="placeholder-xbox.png" width="200" height="200"/>
</div>
</code>```

This would be an acceptable compromise on the HTML side, but then what would be the CSS to make this work?

I know I can use jQuery to hijack clean HTML to generate mucky HTML to achieve what I'm trying to do, but I need this  at design-time.

This fake screenshot below is what I'm looking for. I want to drop a tiny snippet of clean HTML and possibly use the anchor points in the WYSIWYG interface to scale the placeholder, while the label stays in the center-bottom or center-middle.

I have an image that is white with a black X through it.

I'm highly doubtful that CSS will support what I want without mucking up the HTML. However, I'd like to see if anyone knows if it's doable. Here's what I started with, which of course didn't work because the background image won't scale, the text won't vertically align, etc., etc.

```<code>.placeholder {
 display: inline;
 background-image: url('placeholder-xbox.png');
 border: 2px solid black;
    vertical-align: bottom;
}
</code>```

So now I have to figure out what compromises to make. I hate mucking up the HTML and don't mind mucked up CSS because a CSS class is reusable.

答:
To make the X change aspect with the placeholder (as in your screenshot) I would do something like

```<code><div class="placeholder">
    <img src="placeholder-xbox.png" />
</div>
</code>```

with

```<code>.placeholder {
    display: block;/* or display: inline-block; */
    width: 200px;
    height: 50px;
    background: url(logo.png) no-repeat center bottom;
}

.placeholder img {
    width: 100%;
    height: 100%;
    border: 2px solid black;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is a "silly" but hopefully legitimate if not particularly needful challenge, one that can be reused everywhere by designers, I'm sure, if an answer can be had.

I'm using a WYSIWYG-ish editor (MS Expression Web 4) and am trying to produce HTML-based wireframes which I intend to be the base for actual production. With raw/clean HTML being the #1 objective, I'd like to have a pattern for placeholders whereby I might specify the following HTML (and nothing else, except height, width, and text will vary), which should appear as a rectangular box with an 'X' through it and the text (in this case "logo") appearing at the bottom, or in the middle with white background behind the text:

Logo

My question is what is the CSS and the minimum amount of HTML mucking (e.g. img tag) that is required to achieve what I want? For example, if the following HTML is used instead:

    Logo

or

    Logo

This would be an acceptable compromise on the HTML side, but then what would be the CSS to make this work?

I know I can use jQuery to hijack clean HTML to generate mucky HTML to achieve what I'm trying to do, but I need this  at design-time.

This fake screenshot below is what I'm looking for. I want to drop a tiny snippet of clean HTML and possibly use the anchor points in the WYSIWYG interface to scale the placeholder, while the label stays in the center-bottom or center-middle.

I have an image that is white with a black X through it.

I'm highly doubtful that CSS will support what I want without mucking up the HTML. However, I'd like to see if anyone knows if it's doable. Here's what I started with, which of course didn't work because the background image won't scale, the text won't vertically align, etc., etc.

.placeholder {
 display: inline;
 background-image: url('placeholder-xbox.png');
 border: 2px solid black;
    vertical-align: bottom;
}

So now I have to figure out what compromises to make. I hate mucking up the HTML and don't mind mucked up CSS because a CSS class is reusable.

Body:
To make the X change aspect with the placeholder (as in your screenshot) I would do something like

<div class="placeholder">
    <img src="placeholder-xbox.png" />
</div>

with

.placeholder {
    display: block;/* or display: inline-block; */
    width: 200px;
    height: 50px;
    background: url(logo.png) no-repeat center bottom;
}

.placeholder img {
    width: 100%;
    height: 100%;
    border: 2px solid black;
}


答:
use date function instead

```<code>'time' => date('H:i:s',strtotime('now'));
</code>```

If it needs full date time then

```<code>'time' => date('Y-m-d H:i:s',strtotime('now'));
</code>```

Title: codeigniter insert current time in database by controller

Body:
use date function instead

'time' => date('H:i:s',strtotime('now'));

If it needs full date time then

'time' => date('Y-m-d H:i:s',strtotime('now'));


问:
How to render the emojis in webbrowser in js?
I'm using get the emojis from the mobile app as unicodes
\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude18\ud83d\ude18\ud83d\ude18.

When I'm trying to render this in webbrowser it is not rendering. So I wrote another function

```<code>emojiString = function(s) {
       try{
        return eval("(function(){ return '" + s + "'})()");
       }catch(err){
           console.log("error in EmojiString"+err.stack);
           return s;
       }
    };
</code>```

When I send the unicodes to this function everything was fine. But, when my string has () and for some special characters it is showing some error like unexpected token or "Uncaught SyntaxError: Invalid Unicode escape sequence".

How I can render the emojis in browser with unicodes?

答:
Your strings contain \u200b and \u200c - zero-width spaces

This fails because of the invisible zero-width spaces

 var s = "\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude18\ud83d\ude18\ud83d\ude18".replace(/[\u200b-\u200d]/,"")

console.log(s)```
</div>
</div>
</p>

<p>This will work:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var s = document.getElementById("x").innerHTML;
console.log("before removing zero-width spaces",s.length);
s=s.replace(/[\u200b\u200c\u200d\ufeff]/g,"");
console.log("after removing zero-width spaces",s.length)
var em = JSON.parse('{"x":"'+s+'"}')
document.getElementById("y").innerHTML = em.x;</code>```

The div below contain zero-width spaces:

\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude18\ud83d\ude18\ud83d\ude18

```

Body:
I'm using get the emojis from the mobile app as unicodes
\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude18\ud83d\ude18\ud83d\ude18.

When I'm trying to render this in webbrowser it is not rendering. So I wrote another function

emojiString = function(s) {
       try{
        return eval("(function(){ return '" + s + "'})()");
       }catch(err){
           console.log("error in EmojiString"+err.stack);
           return s;
       }
    };

When I send the unicodes to this function everything was fine. But, when my string has () and for some special characters it is showing some error like unexpected token or "Uncaught SyntaxError: Invalid Unicode escape sequence".

How I can render the emojis in browser with unicodes?

Body:
Your strings contain \u200b and \u200c - zero-width spaces

This fails because of the invisible zero-width spaces

 var s = "\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude18\ud83d\ude18\ud83d\ude18".replace(/[\u200b-\u200d]/,"")

console.log(s)

This will work:

var s = document.getElementById("x").innerHTML;
console.log("before removing zero-width spaces",s.length);
s=s.replace(/[\u200b\u200c\u200d\ufeff]/g,"");
console.log("after removing zero-width spaces",s.length)
var em = JSON.parse('{"x":"'+s+'"}')
document.getElementById("y").innerHTML = em.x;

The div below contain zero-width spaces:

<div id="x">\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude18\ud83d\ude18\ud83d\ude18</div>
<div id="y"></div>


问:
Read and write files with accents
I have an input file in XML format and it is well formed, with accents well written. The file is created with a PHP script that works fine.
But when i read the XML File and write it in another XML using a Java program, it puts strange characters instead of the characters with accents.

This is the method that reads the XML File:

```<code>public static String getArchivo(FileInputStream fileinputstream)
{
    String s = null;
    try
    {
        byte abyte0[] = new byte[1024];
        int i = fileinputstream.read(abyte0);
        if(i != -1)
        {
            s = new String(abyte0, 0, i);
            for(int j = fileinputstream.read(abyte0); j != -1; j = fileinputstream.read(abyte0))
            {
                s = s + new String(abyte0, 0, j);
            }

        }
    }
    catch(IOException ioexception)
    {
        s = null;
    }
    return s;
}
</code>```

Due to the fact that the file is read byte per byte, How do i replace the "bad" bytes for the correct bytes for the accented characters?
If reading files like these byte per byte is not a good idea, how can i do it better?

The characters that i need are: á, é, í, ó, ú, Á, É, Í, Ó, Ú, ñ, Ñ and °.

Thanks in advance

答:
When you read the file use encoding utf-8 is best

```<code>BufferedReader rd = new BufferedReader(new InputStreamReader(is, "utf-8"));
</code>```

In writing also use utf-8

```<code>OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(filePath, true), "utf-8");
</code>```

This worked for me.

When read file in vi editor or other editor change default encoding into utf-8

locale charmap
  LANG=en_US.UTF-8

Title: Read and write files with accents

Body:
I have an input file in XML format and it is well formed, with accents well written. The file is created with a PHP script that works fine.
But when i read the XML File and write it in another XML using a Java program, it puts strange characters instead of the characters with accents.

This is the method that reads the XML File:

public static String getArchivo(FileInputStream fileinputstream)
{
    String s = null;
    try
    {
        byte abyte0[] = new byte[1024];
        int i = fileinputstream.read(abyte0);
        if(i != -1)
        {
            s = new String(abyte0, 0, i);
            for(int j = fileinputstream.read(abyte0); j != -1; j = fileinputstream.read(abyte0))
            {
                s = s + new String(abyte0, 0, j);
            }

        }
    }
    catch(IOException ioexception)
    {
        s = null;
    }
    return s;
}

Due to the fact that the file is read byte per byte, How do i replace the "bad" bytes for the correct bytes for the accented characters?
If reading files like these byte per byte is not a good idea, how can i do it better?

The characters that i need are: á, é, í, ó, ú, Á, É, Í, Ó, Ú, ñ, Ñ and °.

Thanks in advance

Body:
When you read the file use encoding utf-8 is best

BufferedReader rd = new BufferedReader(new InputStreamReader(is, "utf-8"));

In writing also use utf-8

OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(filePath, true), "utf-8");

This worked for me.

When read file in vi editor or other editor change default encoding into utf-8

locale charmap
  LANG=en_US.UTF-8


问:
Can't run rails server after installing custom-err-msg
After I install the custom-err-msg plugin, I get an error when I try to run rails server:

```<code>$ rails server
=> Booting WEBrick
=> Rails 3.0.3 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/home/jason/rails/snip/vendor/plugins/custom-err-msg/init.rb:3: uninitialized constant ActiveRecord::Errors (NameError)
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/plugin.rb:81
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:25:in `instance_exec'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:25:in `run'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:50:in `run_initializers'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:49:in `each'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:49:in `run_initializers'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:134:in `initialize!'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:77:in `send'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:77:in `method_missing'
    from /home/jason/rails/snip/config/environment.rb:5
    from /home/jason/rails/snip/config.ru:3:in `require'
    from /home/jason/rails/snip/config.ru:3
    from /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/builder.rb:46:in `instance_eval'
    from /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/builder.rb:46:in `initialize'
    from /home/jason/rails/snip/config.ru:1:in `new'
    from /home/jason/rails/snip/config.ru:1
</code>```

Any idea why this is happening?

答: This plugin is not compatible with Rails 3. I would recommend finding a fork that is or forking it and updating yourself.</p>

Body:
After I install the custom-err-msg plugin, I get an error when I try to run rails server:

$ rails server
=> Booting WEBrick
=> Rails 3.0.3 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/home/jason/rails/snip/vendor/plugins/custom-err-msg/init.rb:3: uninitialized constant ActiveRecord::Errors (NameError)
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/plugin.rb:81
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:25:in `instance_exec'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:25:in `run'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:50:in `run_initializers'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:49:in `each'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/initializable.rb:49:in `run_initializers'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:134:in `initialize!'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:77:in `send'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.3/lib/rails/application.rb:77:in `method_missing'
    from /home/jason/rails/snip/config/environment.rb:5
    from /home/jason/rails/snip/config.ru:3:in `require'
    from /home/jason/rails/snip/config.ru:3
    from /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/builder.rb:46:in `instance_eval'
    from /usr/lib/ruby/gems/1.8/gems/rack-1.2.1/lib/rack/builder.rb:46:in `initialize'
    from /home/jason/rails/snip/config.ru:1:in `new'
    from /home/jason/rails/snip/config.ru:1

Any idea why this is happening?


问:
bash: using find with multiple file types, provided as an array
In a bash function, I want to list all the files in a given folder which correspond to a given set of file types. In pseudo-code, I am imagining something like this:

```<code>getMatchingFiles() {
  output=$1
  directory=$2
  shift 2
  _types_=("$@")

  file_array=find $directory -type f where-name-matches-item-in-_types_

  # do other stuff with $file_array, such as trimming file names to
  # just the basename with no extension

  eval $output="${file_array[@]}"
}

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types
echo "${result[@]}"
</code>```

For your amusement, here are the multiple workarounds, based on my current knowledge of bash, that I am using to achieve this. I have a problem with the way the function returns the array of files: the final command tries to execute each file, rather than to set the output parameter.

```<code>getMatchingFiles() {
  local _output=$1
  local _dir=$2
  shift 2
  local _type=("$@")
  local _files=($_dir/$_type/*)
  local -i ii=${#_files[@]}
  local -a _filetypes
  local _file _regex

  case $_type in
    audio )
      _filetypes=(ogg mp3)
      ;;
    images )
      _filetypes=(jpg png)
      ;;
  esac

  _regex="^.*\.("
  for _filetype in "${_filetypes[@]}"
  do
     _regex+=$_filetype"|"
  done

  _regex=${_regex:0:-1}
  _regex+=")$"

  for (( ; ii-- ; ))
  do
    _file=${_files[$ii]}
    if ! [[ $_file =~ $_regex ]];then
      unset _files[ii]
    fi
  done

  echo "${_files[@]}"

  # eval $_output="${_files[@]}" # tries to execute the files
}

dir=/path/to/parent
getMatchingFiles result $dir audio
echo "${result[@]}"
</code>```

答:
As a matter of fact, it is possible to use nameref (note that you need bash 4.3 or later) to reference an array. If you want to put the output of find to an array specified by a name, you can reference it like this:

```<code>#!/usr/bin/env bash

getMatchingFiles() {

   local -n output=$1
   local dir=$2
   shift 2
   local types=("$@")
   local ext file
   local -a find_ext

   [[ ${#types[@]} -eq 0 ]] && return 1

   for ext in "${types[@]}"; do
      find_ext+=(-o -name "*.${ext}")
   done

   unset 'find_ext[0]'
   output=()

   while IFS=  read -r -d $'\0' file; do
      output+=("$file")
   done < <(find "$dir" -type f \( "${find_ext[@]}" \) -print0)
}

dir=/some/path

getMatchingFiles result "$dir" mp3 txt
printf '%s\n' "${result[@]}"

getMatchingFiles other_result /some/other/path txt
printf '%s\n' "${other_result[@]}"
</code>```

Don't pass your variable $dir as a reference, pass it as a value instead. You will be able to pass a literal as well.

Body:
In a bash function, I want to list all the files in a given folder which correspond to a given set of file types. In pseudo-code, I am imagining something like this:

getMatchingFiles() {
  output=$1
  directory=$2
  shift 2
  _types_=("$@")

  file_array=find $directory -type f where-name-matches-item-in-_types_

  # do other stuff with $file_array, such as trimming file names to
  # just the basename with no extension

  eval $output="${file_array[@]}"
}

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types
echo "${result[@]}"

For your amusement, here are the multiple workarounds, based on my current knowledge of bash, that I am using to achieve this. I have a problem with the way the function returns the array of files: the final command tries to execute each file, rather than to set the output parameter.

getMatchingFiles() {
  local _output=$1
  local _dir=$2
  shift 2
  local _type=("$@")
  local _files=($_dir/$_type/*)
  local -i ii=${#_files[@]}
  local -a _filetypes
  local _file _regex

  case $_type in
    audio )
      _filetypes=(ogg mp3)
      ;;
    images )
      _filetypes=(jpg png)
      ;;
  esac

  _regex="^.*\.("
  for _filetype in "${_filetypes[@]}"
  do
     _regex+=$_filetype"|"
  done

  _regex=${_regex:0:-1}
  _regex+=")$"

  for (( ; ii-- ; ))
  do
    _file=${_files[$ii]}
    if ! [[ $_file =~ $_regex ]];then
      unset _files[ii]
    fi
  done

  echo "${_files[@]}"

  # eval $_output="${_files[@]}" # tries to execute the files
}

dir=/path/to/parent
getMatchingFiles result $dir audio
echo "${result[@]}"

Body:
As a matter of fact, it is possible to use nameref (note that you need bash 4.3 or later) to reference an array. If you want to put the output of find to an array specified by a name, you can reference it like this:

#!/usr/bin/env bash

getMatchingFiles() {

   local -n output=$1
   local dir=$2
   shift 2
   local types=("$@")
   local ext file
   local -a find_ext

   [[ ${#types[@]} -eq 0 ]] && return 1

   for ext in "${types[@]}"; do
      find_ext+=(-o -name "*.${ext}")
   done

   unset 'find_ext[0]'
   output=()

   while IFS=  read -r -d $'\0' file; do
      output+=("$file")
   done < <(find "$dir" -type f \( "${find_ext[@]}" \) -print0)
}

dir=/some/path

getMatchingFiles result "$dir" mp3 txt
printf '%s\n' "${result[@]}"

getMatchingFiles other_result /some/other/path txt
printf '%s\n' "${other_result[@]}"

Don't pass your variable $dir as a reference, pass it as a value instead. You will be able to pass a literal as well.


答:
now() is a MySql function and will not work in php, use the time() function instead to store a Unix timestamp:

```<code>'time' => time();
</code>```

Body:
now() is a MySql function and will not work in php, use the time() function instead to store a Unix timestamp:

'time' => time();


问:
Concurrent requests handling on Google App Engine
I was experimenting with concurrent request handling on few platforms.

The aim of the experiment was to have a broad measure of the capacity bounds of some selected technologies.

I set up a Linux VM on my machine with a basic Go http server (the vanilla http.HandleFunc of the http default package).
The server would then compute a modified version of the fasta algorithm that restricted threads and processes to 1, and return the result. N was set to 100000.
The algorithm runs in roughly 2 seconds.
I used the same algorithm and logic on a Google App Engine project.

The algorithm is written using the same code, just the handler set up is done on init() instead of main() as per GAE requirements.

On the other end an Android client is spawning 500 threads each one issuing in parallel a GET request to the fasta computing server, with a request timeout of 5000 ms.

I was expecting the GAE application to scale and answer back to each request and the local Go server to fail on some of the 500 requests but results were the opposite:
the local server correctly replied to each request within the timeout bounds while the GAE application was able to handle just 160 requests out of 500. The remaining requests timed out.

I checked on the Cloud Console and I verified that 18 GAE instances were spawned, but still the vast majority of requests failed.

I thought that most of them failed because of the start-up time of each GAE instance, so I repeated the experiment right after but I had the same results: most of the requests timed out.

I was expecting GAE to scale to accomodate ALL the requests, believing that if a single local VM could successfully reply to 500 concurrent requests GAE would have done the same, but this is not what happened.

The GAE console doesn't show any error and correctly reports the number of incoming requests.

What could be the cause of this?
Also, if a single instance could handle all the incoming requests on my machine by virtue of only goroutines, how come that GAE needed to scale so much at all?

答:
Extending on Alexander's answer.

The GAE scaling logic is based on incoming traffic trend analysis.

The key for being able to handle your case - sudden spikes in traffic (which can't be takes into account in the trend analysis due to its variation speed) - is to have sufficient resident (idle) instances configured for your application to handle such traffic until GAE spins up additional dynamic instances. It can handle as high peaks as you want (if your pockets are deep enough).

See Scaling dynamic instances for more details.


问:
How to run a function when the page is loaded?
I want to run a function when the page is loaded, but I don’t want to use it in the  tag.

I have a script that runs if I initialise it in the , like this:

function codeAddress() {
  // code
}
```

<pre class="lang-html prettyprint-override"><code><body onLoad="codeAddress()">
</code>```

But I want to run it without the  and I have tried a lot of things, e.g. this:

```<code>window.onload = codeAddress;
</code>```

But it is not working.

So how do I run it when the page is loaded?

答:
window.onload = function() { ... etc. is not a great answer.

This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours.
So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.

A more robust answer here:

```<code>if(window.attachEvent) {
    window.attachEvent('onload', yourFunctionName);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            yourFunctionName(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = yourFunctionName;
    }
}
</code>```

Some code I have been using, I forget where I found it to give the author credit.

```<code>function my_function() {
    // whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}
</code>```

Hope this helps :)

ContentLicense: CC BY-SA 4.0

Body:
I want to run a function when the page is loaded, but I don’t want to use it in the  tag.

I have a script that runs if I initialise it in the , like this:

function codeAddress() {
  // code
}

But I want to run it without the  and I have tried a lot of things, e.g. this:

window.onload = codeAddress;

But it is not working.

So how do I run it when the page is loaded?

Body:
window.onload = function() { ... etc. is not a great answer.

This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours.
So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.

A more robust answer here:

if(window.attachEvent) {
    window.attachEvent('onload', yourFunctionName);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            yourFunctionName(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = yourFunctionName;
    }
}

Some code I have been using, I forget where I found it to give the author credit.

function my_function() {
    // whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}

Hope this helps :)


问:
custom routing in rails
I have a rails application that has a model named graphic and as any rails application there is normal routing like this

```<code>something.com/graphics/1
something.com/graphics/2
something.com/graphics/3
</code>```

which will take you to the appropriate show pages. That I understand this is done in my routes by this statement

resources :graphics

Now come to find out the client wants to have the url to be like this

```<code>something.com/1
something.com/2
something.com/3
</code>```

so if there is a number directly after the root url then like it to the graphic show action....any ideas on how to do this without messing up any other models

答:
Seems like you are looking for:

```<code>match "/:id" => "graphics#show"
</code>```

You can refer to http://guides.rubyonrails.org/routing.html for any further modifications.

Title: custom routing in rails

Body:
I have a rails application that has a model named graphic and as any rails application there is normal routing like this

something.com/graphics/1
something.com/graphics/2
something.com/graphics/3

which will take you to the appropriate show pages. That I understand this is done in my routes by this statement

resources :graphics

Now come to find out the client wants to have the url to be like this

something.com/1
something.com/2
something.com/3

so if there is a number directly after the root url then like it to the graphic show action....any ideas on how to do this without messing up any other models

Body:
Seems like you are looking for:

match "/:id" => "graphics#show"

You can refer to http://guides.rubyonrails.org/routing.html for any further modifications.


问:
Get all logs of the current Jenkins build with currentBuild.rawBuild.getLog
I want all my jenkins logs of my current build in groovy

```<code>env.logs = currentBuild.rawBuild.getLog(1000).join('\n')
</code>```

This works, but the problem here is I have to specify the amount of lines.
When I use:

```<code>env.logs = currentBuild.rawBuild.getLog().join('\n')
</code>```

env.logs is empty. What is the right command to get all the logs without specifying the amount of lines. Is this possible?

currentBuild.rawBuild.log seems to work but is deprecated?

答: You can use the getLog method with a max value getLog(Integer.MAX_VALUE)

Body:
I want all my jenkins logs of my current build in groovy

env.logs = currentBuild.rawBuild.getLog(1000).join('\n')

This works, but the problem here is I have to specify the amount of lines.
When I use:

env.logs = currentBuild.rawBuild.getLog().join('\n')

env.logs is empty. What is the right command to get all the logs without specifying the amount of lines. Is this possible?

currentBuild.rawBuild.log seems to work but is deprecated?


问:
Single quote ( ' ) is not supporting in angularjs ng-click() if multiple parameter is passed

How to escape single quote( ' ) in angularjs ng-click

```<code>ng-click="editQuesAnsDetails('${fn:escapeXml(quesAnsList.querysearchBO.query)}','${fn:escapeXml(anslist.query_answer)}',

'${anslist.editUrl}','${anslist.filepath}');"
</code>```

this my angular controller:

```<code>App.controller('AskedQuesAnsController',['$scope','$window','AskedQuesAnsServices',function($scope,$window,AskedQuesAnsServices) {
$scope.quesAnsUpdateCommand={"query":"","answer":"","editUrl":"","deleteUrl":""};
 $scope.editQuesAnsDetails = function(query,answer,editUrl,deleteUrl,filepath){

    $scope.quesAnsUpdateCommand.query=query;

    $scope.quesAnsUpdateCommand.answer=answer;
    $scope.quesAnsUpdateCommand.editUrl=editUrl;
    $scope.quesAnsUpdateCommand.deleteUrl=deleteUrl;
    $scope.quesAnsUpdateCommand.filepath=filepath;
    //alert($scope.moduleUpdateCommand.editModule);
 }
</code>```

the above code should work for any special symboles

答:
You can try using fn:replace() function to escape single quote( ').

```<code><c:set var="singleQuotes">'</c:set>
<c:set var="singleQuotesReplace">\'</c:set>

ng-click="editQuesAnsDetails('${fn:escapeXml(
 fn:replace(quesAnsList.querysearchBO.query,singleQuotes,singleQuotesReplace))}'"
</code>```

Also JSP javascript escape with JSTL

Body:
How to escape single quote( ' ) in angularjs ng-click

ng-click="editQuesAnsDetails('${fn:escapeXml(quesAnsList.querysearchBO.query)}','${fn:escapeXml(anslist.query_answer)}',

'${anslist.editUrl}','${anslist.filepath}');"

this my angular controller:

App.controller('AskedQuesAnsController',['$scope','$window','AskedQuesAnsServices',function($scope,$window,AskedQuesAnsServices) {
$scope.quesAnsUpdateCommand={"query":"","answer":"","editUrl":"","deleteUrl":""};
 $scope.editQuesAnsDetails = function(query,answer,editUrl,deleteUrl,filepath){

    $scope.quesAnsUpdateCommand.query=query;

    $scope.quesAnsUpdateCommand.answer=answer;
    $scope.quesAnsUpdateCommand.editUrl=editUrl;
    $scope.quesAnsUpdateCommand.deleteUrl=deleteUrl;
    $scope.quesAnsUpdateCommand.filepath=filepath;
    //alert($scope.moduleUpdateCommand.editModule);
 }

the above code should work for any special symboles

Body:
You can try using fn:replace() function to escape single quote( ').

<c:set var="singleQuotes">'</c:set>
<c:set var="singleQuotesReplace">\'</c:set>

ng-click="editQuesAnsDetails('${fn:escapeXml(
 fn:replace(quesAnsList.querysearchBO.query,singleQuotes,singleQuotesReplace))}'"

Also JSP javascript escape with JSTL


问:
DbUnit DbComparisonFailure expected:<uniqueidentifier>
We do databas / dataset comparison.

Source DB: SQL Server

Target DB: SAP HANA

Error message:

org.dbunit.assertion.DbComparisonFailure: Incompatible data types: (table=dataset, col=JobId) expected:<uniqueidentifier> but was:<VARCHAR>

Work-around: cast(JobId as varchar(36)) JobId

But why does this error occure? JobId is defined as varchar(36) in the source table

How to make this work (The SQLs are generated and manually adding a cast is cumbersome)

答:
Thanks to Lars Br answer:

I made the following solution:

Remove DbUnit jar from classpath (version 2.5.4)

Add DbUnit source code (also version 2.4.5)

Edit the class org.dbunit.ext.mssql.MsSqlDataTypeFactory

Method public DataType createDataType(int sqlType, String sqlTypeName) throws DataTypeException

```<code>if(sqlType == Types.CHAR)
{
    if (UniqueIdentifierType.UNIQUE_IDENTIFIER_TYPE.equals(sqlTypeName))
    {
        return new UniqueIdentifierType();
    }
}
</code>```

to

```<code>/* Do not generate UNIQUE_IDENTIFIER_TYPE since it would not match varchar on SAP HANA
if(sqlType == Types.CHAR)
{
    if (UniqueIdentifierType.UNIQUE_IDENTIFIER_TYPE.equals(sqlTypeName))
    {
        return new UniqueIdentifierType();
    }
}*/
</code>```

Body:
Thanks to Lars Br answer:

I made the following solution:

Remove DbUnit jar from classpath (version 2.5.4)

Add DbUnit source code (also version 2.4.5)

Edit the class org.dbunit.ext.mssql.MsSqlDataTypeFactory

Method public DataType createDataType(int sqlType, String sqlTypeName) throws DataTypeException

if(sqlType == Types.CHAR)
{
    if (UniqueIdentifierType.UNIQUE_IDENTIFIER_TYPE.equals(sqlTypeName))
    {
        return new UniqueIdentifierType();
    }
}

to

/* Do not generate UNIQUE_IDENTIFIER_TYPE since it would not match varchar on SAP HANA
if(sqlType == Types.CHAR)
{
    if (UniqueIdentifierType.UNIQUE_IDENTIFIER_TYPE.equals(sqlTypeName))
    {
        return new UniqueIdentifierType();
    }
}*/


问:
Django EmailField accepts invalid values
I'm currently using the default EmailField attribute on my form. The issue I'm running into is that the form considers an invalid email such as name@mail.56 to be valid. Do I need to implement my own validators on this field to make it work correctly?

I was under the impression that having:

```<code>#models.py
email = models.EmailField(max_length=254, blank=False, unique=True,
        error_messages={'required': 'Please provide your email address.',
                        'unique': 'An account with this email exist.'},)
</code>```

Or having:

```<code>#forms.py
email = forms.EmailField()
</code>```

will take care of this type of validation for me but it doesn't seem so.

答:
For DB level only validation you will have to call full_clean manually.

Three important citations from documentation:

How validators are run

See the form validation for more information on how validators are run
  in forms, and Validating objects for how they’re run in models. Note
  that validators will not be run automatically when you save a model,
  but if you are using a ModelForm, it will run your validators on any
  fields that are included in your form. See the ModelForm documentation
  for information on how model validation interacts with forms.

Model.clean_fields

The second step full_clean() performs is to call Model.clean(). This
  method should be overridden to perform custom validation on your
  model.

Model.full_clean

Note that full_clean() will not be called automatically when you call
  your model’s save() method. You’ll need to call it manually when you
  want to run one-step model validation for your own manually created
  models.

```<code>from django.db import models

class MyTable(models.Model):
    email = models.EmailField(unique=True)

    def save(self, *args, **kwargs):
        super().full_clean()
        super().save(*args, **kwargs)
</code>```

Body:
I'm currently using the default EmailField attribute on my form. The issue I'm running into is that the form considers an invalid email such as name@mail.56 to be valid. Do I need to implement my own validators on this field to make it work correctly?

I was under the impression that having:

#models.py
email = models.EmailField(max_length=254, blank=False, unique=True,
        error_messages={'required': 'Please provide your email address.',
                        'unique': 'An account with this email exist.'},)

Or having:

#forms.py
email = forms.EmailField()

will take care of this type of validation for me but it doesn't seem so.

Body:
For DB level only validation you will have to call full_clean manually.

Three important citations from documentation:

How validators are run

See the form validation for more information on how validators are run
  in forms, and Validating objects for how they’re run in models. Note
  that validators will not be run automatically when you save a model,
  but if you are using a ModelForm, it will run your validators on any
  fields that are included in your form. See the ModelForm documentation
  for information on how model validation interacts with forms.

Model.clean_fields

The second step full_clean() performs is to call Model.clean(). This
  method should be overridden to perform custom validation on your
  model.

Model.full_clean

Note that full_clean() will not be called automatically when you call
  your model’s save() method. You’ll need to call it manually when you
  want to run one-step model validation for your own manually created
  models.

from django.db import models

class MyTable(models.Model):
    email = models.EmailField(unique=True)

    def save(self, *args, **kwargs):
        super().full_clean()
        super().save(*args, **kwargs)


问:
How can I Copy to clipboard, a ListView's multiple selected items?
This code is working for one single selected item:
In the top:

```<code>ContextMenuStrip menuStrip;
</code>```

Then in the constructor:

```<code>menuStrip = new ContextMenuStrip();
menuStrip.ItemClicked += menuStrip_ItemClicked;
menuStrip.Items.Add("Cut");
menuStrip.Items.Add("Copy");
menuStrip.Items.Add("Paste");
</code>```

The menuStrip itemclicked event:

```<code>ListViewItem item;
        private void menuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Text == "Copy")
            {
                Clipboard.SetText(item.SubItems[1].Text);

            }
        }
</code>```

Then the ListView mouse click event:

```<code>private void lstDisplayHardware_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                item = lstDisplayHardware.GetItemAt(e.X, e.Y);
                menuStrip.Show(lstDisplayHardware, e.Location);
            }
        }
</code>```

This code is working for single selected item.
For example I click on an item in the ListView, right click on the item and select Copy: the selected item's subitem is copied to the Clipboard.

But now I want to do the same thing for multiple selection.

So if I use Ctrl+Left mouse click and for example selected 4 items and invoke Copy command from the context menu, I expect all subitems of the 4 selected items text to be copied into the Clipboard.

For example I have these items:

danny    hello world

daniel   hi all

dan      rain today

daniels  sunny day

I select the items:

danny

daniel

dan

daniels

Then right click and click on Copy.
When I paste anywhere from the clipboard I want it to show:

hello world

hi all

rain today

sunny day

All of the sub items of the selected items in the same order and format.

答:
For ListView, not ListBox code will be:</p>

```<code>    private void listView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.C)
        {
            CopyListBox(listView1);
        }
    }
    public void CopyListBox(ListView list)
    {
        StringBuilder sb = new StringBuilder();
        foreach (var item in list.SelectedItems)
        {
            ListViewItem l = item as ListViewItem;
            if (l != null)
                foreach (ListViewItem.ListViewSubItem sub in l.SubItems)
                    sb.Append(sub.Text+"\t");
            sb.AppendLine();
        }
        Clipboard.SetDataObject(sb.ToString());

    }
</code>```

Body:
This code is working for one single selected item:
In the top:

ContextMenuStrip menuStrip;

Then in the constructor:

menuStrip = new ContextMenuStrip();
menuStrip.ItemClicked += menuStrip_ItemClicked;
menuStrip.Items.Add("Cut");
menuStrip.Items.Add("Copy");
menuStrip.Items.Add("Paste");

The menuStrip itemclicked event:

ListViewItem item;
        private void menuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Text == "Copy")
            {
                Clipboard.SetText(item.SubItems[1].Text);

            }
        }

Then the ListView mouse click event:

private void lstDisplayHardware_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                item = lstDisplayHardware.GetItemAt(e.X, e.Y);
                menuStrip.Show(lstDisplayHardware, e.Location);
            }
        }

This code is working for single selected item.
For example I click on an item in the ListView, right click on the item and select Copy: the selected item's subitem is copied to the Clipboard.

But now I want to do the same thing for multiple selection.

So if I use Ctrl+Left mouse click and for example selected 4 items and invoke Copy command from the context menu, I expect all subitems of the 4 selected items text to be copied into the Clipboard.

For example I have these items:

danny    hello world

daniel   hi all

dan      rain today

daniels  sunny day

I select the items:

danny

daniel

dan

daniels

Then right click and click on Copy.
When I paste anywhere from the clipboard I want it to show:

hello world

hi all

rain today

sunny day

All of the sub items of the selected items in the same order and format.

Body:
For ListView, not ListBox code will be:

    private void listView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.C)
        {
            CopyListBox(listView1);
        }
    }
    public void CopyListBox(ListView list)
    {
        StringBuilder sb = new StringBuilder();
        foreach (var item in list.SelectedItems)
        {
            ListViewItem l = item as ListViewItem;
            if (l != null)
                foreach (ListViewItem.ListViewSubItem sub in l.SubItems)
                    sb.Append(sub.Text+"\t");
            sb.AppendLine();
        }
        Clipboard.SetDataObject(sb.ToString());

    }


问:
Actionscript 3 and XML with CDATA
I am trying to convert a AS2 xmas card that we have to AS3 an I am stuck with displaying XML with CDATA. Basically the HMTL tags still get ouput.

Here is my XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<config>
<data>
  <textblock>
     <![CDATA[<h1>Seasons Greetings!</h1><p>from everyone at Honda</p>]]>
  </textblock>
</data>
</config>
</code>```

CSS

```<code>h1 {
    font-size:55;
    color:#333333;
}

p {
    font-size:25;
    color:#333333;
}
</code>```

and my AS3:

```<code>import flash.net.URLLoader;
import flash.text.StyleSheet;

var myXML:XML = new XML();
var XML_URL:String = "config.xml";
var myXMLURL:URLRequest = new URLRequest(XML_URL);
var myLoader:URLLoader = new URLLoader(myXMLURL);
myLoader.addEventListener(Event.COMPLETE, xmlLoaded);

function xmlLoaded(event:Event):void
{
    myXML = XML(myLoader.data);
    trace("Data loaded.");
    blocktext.text = myXML.data.textblock;
}

var textStyleSheet:StyleSheet;
function loadCSS():void
{
    var loader:URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, onCSSLoadComplete);
    loader.load(new URLRequest("config.css"));
}
function onCSSLoadComplete(event:Event):void
{
    textStyleSheet = new StyleSheet();
    textStyleSheet.parseCSS(event.target.data);
    //loadXML();
}
</code>```

It sill outputs the H1 and P html tags and doesn't use the styling.

Any help appreciated.

答:
I think you could start with</p>

```<code>blocktext.styleSheet = textStyleSheet;
blocktext.htmlText = myXML.data.textblock.children.toString();
</code>```

Title: Actionscript 3 and XML with CDATA

Body:
I am trying to convert a AS2 xmas card that we have to AS3 an I am stuck with displaying XML with CDATA. Basically the HMTL tags still get ouput.

Here is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<config>
<data>
  <textblock>
     <![CDATA[
Seasons Greetings!

from everyone at Honda
]]>
  </textblock>
</data>
</config>

CSS

h1 {
    font-size:55;
    color:#333333;
}

p {
    font-size:25;
    color:#333333;
}

and my AS3:

import flash.net.URLLoader;
import flash.text.StyleSheet;

var myXML:XML = new XML();
var XML_URL:String = "config.xml";
var myXMLURL:URLRequest = new URLRequest(XML_URL);
var myLoader:URLLoader = new URLLoader(myXMLURL);
myLoader.addEventListener(Event.COMPLETE, xmlLoaded);

function xmlLoaded(event:Event):void
{
    myXML = XML(myLoader.data);
    trace("Data loaded.");
    blocktext.text = myXML.data.textblock;
}

var textStyleSheet:StyleSheet;
function loadCSS():void
{
    var loader:URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, onCSSLoadComplete);
    loader.load(new URLRequest("config.css"));
}
function onCSSLoadComplete(event:Event):void
{
    textStyleSheet = new StyleSheet();
    textStyleSheet.parseCSS(event.target.data);
    //loadXML();
}

It sill outputs the H1 and P html tags and doesn't use the styling.

Any help appreciated.

Body:
I think you could start with

blocktext.styleSheet = textStyleSheet;
blocktext.htmlText = myXML.data.textblock.children.toString();


问:
Best way to store locators in Robotramework
I am building a Robotframework automation project.

As the project grows, it also becomes more difficult to maintain, with the increasing of selectors number in project.

+10K selectors in project (a big one) and almost no changes occur in each one;

Now I have the following structure:

```<code> .
 |-- Project
 |   |-- Generic Keywords
 |   |   |-- Web App A
 |   |   |   `-- GUI_Actions.robot
 |   |   |-- Web App B
 |   |   |   |-- GUI_Actions.robot
 |   |   |   |-- DB_Actions.robot
 |   |   |   |-- ...
 |   |   `-- ...
 |   |-- Tests
 |   |   `-- Web App A
 |   |       |-- Suite1.robot
 |   |       |-- Suite2.robot
 |   |       |-- ...
 |   |   `-- Web App B
 |   |       |-- Suite1.robot
 |   |       |-- Suite2.robot
 |   |       |-- ...
</code>```

What is the best way to keep these locators(separate from the code) in a way that makes the project scalable and maintainable?

Separated folder "Locators" (in root) with files (resources) and one variable per locator?

One locators file (one by application) inside "Generic Keywords" and "Web App" folders?

... etc

There are many ways to do that, which one is the best?

I appreciate some ideas/suggestions. Thank you.

答:
First off, there is no "best". What is best for one organization or team won't be best for another. How many do you have? How often do they change? How much are they re-used between pages or between applications? Do you use them in your tests, or only in keywords? Are most of your keywords written in robot syntax, or in python or some other programming language?

Personally I'm a pretty big believer in not storing or managing locators for the project as a whole. I do not think tests should have locators in them at all.

I am of the opinion that robot framework works best when you use it as a framework, by creating your own custom keywords. The locators only need to be visible to the keyword or keywords that use them, rather than sprinkled throughout your code.

I'm a strong proponent of using the page object pattern, where each page or each section of a page is represented as an object. Within that object you only need the locators for the elements in that page or section of a page. In my experience that usually means just a very few locators per page.

For an example of how to implement page objects with robot, see my open source project, robotframework-pageobjectlibrary. This implementation has a data structure for storing locators, but over the past year I've found myself rarely using that, opting instead to hard-code the locators in each function.

Body:
I am building a Robotframework automation project.

As the project grows, it also becomes more difficult to maintain, with the increasing of selectors number in project.

+10K selectors in project (a big one) and almost no changes occur in each one;

Now I have the following structure:

 .
 |-- Project
 |   |-- Generic Keywords
 |   |   |-- Web App A
 |   |   |   `-- GUI_Actions.robot
 |   |   |-- Web App B
 |   |   |   |-- GUI_Actions.robot
 |   |   |   |-- DB_Actions.robot
 |   |   |   |-- ...
 |   |   `-- ...
 |   |-- Tests
 |   |   `-- Web App A
 |   |       |-- Suite1.robot
 |   |       |-- Suite2.robot
 |   |       |-- ...
 |   |   `-- Web App B
 |   |       |-- Suite1.robot
 |   |       |-- Suite2.robot
 |   |       |-- ...

What is the best way to keep these locators(separate from the code) in a way that makes the project scalable and maintainable?

Separated folder "Locators" (in root) with files (resources) and one variable per locator?

One locators file (one by application) inside "Generic Keywords" and "Web App" folders?

... etc

There are many ways to do that, which one is the best?

I appreciate some ideas/suggestions. Thank you.


问:
Normalising image album database

Above is my normalised database structure for my app. I am going to store Users, and their favorited Images. Images might be alone (hosted on reddit) or in albums (hosted on imgur), and they always have a title.

Question is - is the database set up correctly? I have this feeling that i have something wrong with ImageAlbum and Image table relationship.

EDIT: This might work?

答:
The main issue with the original design is that the intended relationship between a user and an image would not be possible, as the two tables are not connected.

As a general rule of thumb, if there's a 1-1 or a 1-many relationship between tables, you can rely on constraints. I.e. 1 customer can place many orders. You have a Customer table with a CustomerID PK column, and an Order table containing an OrderID PK column, and a Foreign Key constraint to the CustomerID column of the Customer table. That establishes the relationship, and ensures that you cannot place an order if you are not a customer.

An order typically consists of one or more products, and a product typically can be purchases in multiple orders. In cases like this, you cannot set up this relationship the same way. A common workaround for that is to do so using an intermediate table that establishes the many-to-many relationship.

So building on the earlier tables, we also have a Product table, with a ProductID column as a PK. To set up the relationship between Order and Product, you would then credit an OrderProduct table, with FKs pointing to the OrderID and ProductID in question (and probably also something indicating quantity of products for this particular order, and perhaps something like a FK to a Discount or campaign table, and whatnot).

So in your scenario, I would establish the relationship between Image and User using a similar approach, and simply adding a UserImage table to allow for the many-to-many relationship. You then also add an AlbumImage table to determine the many-to-many relationship between images and albums.

As indicated in the comments, there's no need to have an AlbumTitle table, really. It would naturally belong to the Album table. The ImageTitle would belong in the UserImage table, because every user can add their own title to an image.

Title: Normalising image album database