问:
Detecting signed overflow in C/C++
At first glance, this question may seem like a duplicate of How to detect integer overflow?, however it is actually significantly different.

I've found that while detecting an unsigned integer overflow is pretty trivial, detecting a signed overflow in C/C++ is actually more difficult than most people think.

The most obvious, yet naive, way to do it would be something like:

```<code>int add(int lhs, int rhs)
{
 int sum = lhs + rhs;
 if ((lhs >= 0 && sum < rhs) || (lhs < 0 && sum > rhs)) {
  /* an overflow has occurred */
  abort();
 }
 return sum;
}
</code>```

The problem with this is that according to the C standard, signed integer overflow is undefined behavior.  In other words, according to the standard, as soon as you even cause a signed overflow, your program is just as invalid as if you dereferenced a null pointer.  So you can't cause undefined behavior, and then try to detect the overflow after the fact, as in the above post-condition check example.

Even though the above check is likely to work on many compilers, you can't count on it.  In fact, because the C standard says signed integer overflow is undefined, some compilers (like GCC) will optimize away the above check when optimization flags are set, because the compiler assumes a signed overflow is impossible.  This totally breaks the attempt to check for overflow.

So, another possible way to check for overflow would be:

```<code>int add(int lhs, int rhs)
{
 if (lhs >= 0 && rhs >= 0) {
  if (INT_MAX - lhs <= rhs) {
   /* overflow has occurred */
   abort();
  }
 }
 else if (lhs < 0 && rhs < 0) {
  if (lhs <= INT_MIN - rhs) {
   /* overflow has occurred */
   abort();
  }
 }

 return lhs + rhs;
}
</code>```

This seems more promising, since we don't actually add the two integers together until we make sure in advance that performing such an add will not result in overflow.  Thus, we don't cause any undefined behavior.

However, this solution is unfortunately a lot less efficient than the initial solution, since you have to perform a subtract operation just to test if your addition operation will work.  And even if you don't care about this (small) performance hit, I'm still not entirely convinced this solution is adequate.  The expression lhs <= INT_MIN - rhs seems exactly like the sort of expression the compiler might optimize away, thinking that signed overflow is impossible.

So is there a better solution here?  Something that is guaranteed to 1) not cause undefined behavior, and 2) not provide the compiler with an opportunity to optimize away overflow checks?  I was thinking there might be some way to do it by casting both operands to unsigned, and performing checks by rolling your own two's-complement arithmetic, but I'm not really sure how to do that.

答:
In case of adding two long values, portable code can split the long value into low and high int parts (or into short parts in case long has the same size as int):

```<code>static_assert(sizeof(long) == 2*sizeof(int), "");
long a, b;
int ai[2] = {int(a), int(a >> (8*sizeof(int)))};
int bi[2] = {int(b), int(b >> (8*sizeof(int))});
... use the 'long' type to add the elements of 'ai' and 'bi'
</code>```

Using inline assembly is the fastest way if targeting a particular CPU:

```<code>long a, b;
bool overflow;
#ifdef __amd64__
    asm (
        "addq %2, %0; seto %1"
        : "+r" (a), "=ro" (overflow)
        : "ro" (b)
    );
#else
    #error "unsupported CPU"
#endif
if(overflow) ...
// The result is stored in variable 'a'
</code>```

Title: Detecting signed overflow in C/C++

Body:
At first glance, this question may seem like a duplicate of How to detect integer overflow?, however it is actually significantly different.

I've found that while detecting an unsigned integer overflow is pretty trivial, detecting a signed overflow in C/C++ is actually more difficult than most people think.

The most obvious, yet naive, way to do it would be something like:

int add(int lhs, int rhs)
{
 int sum = lhs + rhs;
 if ((lhs >= 0 && sum < rhs) || (lhs < 0 && sum > rhs)) {
  /* an overflow has occurred */
  abort();
 }
 return sum;
}

The problem with this is that according to the C standard, signed integer overflow is undefined behavior.  In other words, according to the standard, as soon as you even cause a signed overflow, your program is just as invalid as if you dereferenced a null pointer.  So you can't cause undefined behavior, and then try to detect the overflow after the fact, as in the above post-condition check example.

Even though the above check is likely to work on many compilers, you can't count on it.  In fact, because the C standard says signed integer overflow is undefined, some compilers (like GCC) will optimize away the above check when optimization flags are set, because the compiler assumes a signed overflow is impossible.  This totally breaks the attempt to check for overflow.

So, another possible way to check for overflow would be:

int add(int lhs, int rhs)
{
 if (lhs >= 0 && rhs >= 0) {
  if (INT_MAX - lhs <= rhs) {
   /* overflow has occurred */
   abort();
  }
 }
 else if (lhs < 0 && rhs < 0) {
  if (lhs <= INT_MIN - rhs) {
   /* overflow has occurred */
   abort();
  }
 }

 return lhs + rhs;
}

This seems more promising, since we don't actually add the two integers together until we make sure in advance that performing such an add will not result in overflow.  Thus, we don't cause any undefined behavior.

However, this solution is unfortunately a lot less efficient than the initial solution, since you have to perform a subtract operation just to test if your addition operation will work.  And even if you don't care about this (small) performance hit, I'm still not entirely convinced this solution is adequate.  The expression lhs <= INT_MIN - rhs seems exactly like the sort of expression the compiler might optimize away, thinking that signed overflow is impossible.

So is there a better solution here?  Something that is guaranteed to 1) not cause undefined behavior, and 2) not provide the compiler with an opportunity to optimize away overflow checks?  I was thinking there might be some way to do it by casting both operands to unsigned, and performing checks by rolling your own two's-complement arithmetic, but I'm not really sure how to do that.

Body:
In case of adding two long values, portable code can split the long value into low and high int parts (or into short parts in case long has the same size as int):

static_assert(sizeof(long) == 2*sizeof(int), "");
long a, b;
int ai[2] = {int(a), int(a >> (8*sizeof(int)))};
int bi[2] = {int(b), int(b >> (8*sizeof(int))});
... use the 'long' type to add the elements of 'ai' and 'bi'

Using inline assembly is the fastest way if targeting a particular CPU:

long a, b;
bool overflow;
#ifdef __amd64__
    asm (
        "addq %2, %0; seto %1"
        : "+r" (a), "=ro" (overflow)
        : "ro" (b)
    );
#else
    #error "unsupported CPU"
#endif
if(overflow) ...
// The result is stored in variable 'a'


来源: stackexchange

问:
Java orm problem
There is a big table business_apply in our system. It's used to store business apply information, and contains hundreds of columns.

When business type differs, a column may mean different things.

What kind of orm framework can make our life easier? Hibernate, iBatis or something else?

答: The Hibernate is already a standard. This fits in almost all situations and is simple to use. I would also recommend Hibernate.</p>

ContentLicense: CC BY-SA 2.5

Title: Java orm problem


问:
get output from python script to django
I'm looking for get the outputs from a python script to my django web server.

I will use pySmartDL in my script, so i need it to run even when django close itself and django needs to get data from a running script when it start-up.

pySmartDL exemple script :

```<code>import time
from pySmartDL import SmartDL

url_100mb_file = ['http://ipv4.download.thinkbroadband.com/100MB.zip']
obj = SmartDL(url_100mb_file, progress_bar=False)
obj.start(blocking=False)

while not obj.isFinished():
        print("Speed: %s" % obj.get_speed(human=True))
        print("Already downloaded: %s" % obj.get_dl_size(human=True))
        print("Eta: %s" % obj.get_eta(human=True))
        print("Progress: %d%%" % (obj.get_progress()*100))
        print("Progress bar: %s" % obj.get_progress_bar())
        print("Status: %s" % obj.get_status())
        print("\n"*2+"="*50+"\n"*2)
        time.sleep(0.2)

if obj.isSuccessful():
        print("downloaded file to '%s'" % obj.get_dest())
        print("download task took %ss" % obj.get_dl_time(human=True))
        print("File hashes:")
        print(" * MD5: %s" % obj.get_data_hash('md5'))
        print(" * SHA1: %s" % obj.get_data_hash('sha1'))
        print(" * SHA256: %s" % obj.get_data_hash('sha256'))
else:
        print("There were some errors:")
        for e in obj.get_errors():
                print(str(e))

# Do something with obj.get_dest()
</code>```

As you can see here the script will print output several times while a file is downloading with this :

```<code>time.sleep(0.2)
</code>```

So i need to get the output dynamically.

I found some answer with websocket (with redis and django-channels or django-redis) and nodeJS but i can't find code example for sending the script output to redis server and how to get them from django. And i don't know much about nodeJS.

Thanks for your time!

答:
Don't complicated matters by involving node.js and django channels. This is something that you can do with just redis.

```<code>rdb = redis.Redis()

while not obj.isFinished():
    print("Speed: %s" % obj.get_speed(human=True))
    print("Already downloaded: %s" % obj.get_dl_size(human=True))
    print("Eta: %s" % obj.get_eta(human=True))
    print("Progress: %d%%" % (obj.get_progress()*100))
    print("Progress bar: %s" % obj.get_progress_bar())
    print("Status: %s" % obj.get_status())
    print("\n"*2+"="*50+"\n"*2)
    rbd.set('download_progress',obj.get_progress_bar())

    time.sleep(0.2)
</code>```

Then in your django views that need to know about this download

```<code>rdb = redis.Redis()
val = rdb.get('download_progress')
</code>```

ContentLicense: CC BY-SA 3.0

Title: get output from python script to django

Body:
I'm looking for get the outputs from a python script to my django web server.

I will use pySmartDL in my script, so i need it to run even when django close itself and django needs to get data from a running script when it start-up.

pySmartDL exemple script :

import time
from pySmartDL import SmartDL

url_100mb_file = ['http://ipv4.download.thinkbroadband.com/100MB.zip']
obj = SmartDL(url_100mb_file, progress_bar=False)
obj.start(blocking=False)

while not obj.isFinished():
        print("Speed: %s" % obj.get_speed(human=True))
        print("Already downloaded: %s" % obj.get_dl_size(human=True))
        print("Eta: %s" % obj.get_eta(human=True))
        print("Progress: %d%%" % (obj.get_progress()*100))
        print("Progress bar: %s" % obj.get_progress_bar())
        print("Status: %s" % obj.get_status())
        print("\n"*2+"="*50+"\n"*2)
        time.sleep(0.2)

if obj.isSuccessful():
        print("downloaded file to '%s'" % obj.get_dest())
        print("download task took %ss" % obj.get_dl_time(human=True))
        print("File hashes:")
        print(" * MD5: %s" % obj.get_data_hash('md5'))
        print(" * SHA1: %s" % obj.get_data_hash('sha1'))
        print(" * SHA256: %s" % obj.get_data_hash('sha256'))
else:
        print("There were some errors:")
        for e in obj.get_errors():
                print(str(e))

# Do something with obj.get_dest()

As you can see here the script will print output several times while a file is downloading with this :

time.sleep(0.2)

So i need to get the output dynamically.

I found some answer with websocket (with redis and django-channels or django-redis) and nodeJS but i can't find code example for sending the script output to redis server and how to get them from django. And i don't know much about nodeJS.

Thanks for your time!

Body:
Don't complicated matters by involving node.js and django channels. This is something that you can do with just redis.

rdb = redis.Redis()

while not obj.isFinished():
    print("Speed: %s" % obj.get_speed(human=True))
    print("Already downloaded: %s" % obj.get_dl_size(human=True))
    print("Eta: %s" % obj.get_eta(human=True))
    print("Progress: %d%%" % (obj.get_progress()*100))
    print("Progress bar: %s" % obj.get_progress_bar())
    print("Status: %s" % obj.get_status())
    print("\n"*2+"="*50+"\n"*2)
    rbd.set('download_progress',obj.get_progress_bar())

    time.sleep(0.2)

Then in your django views that need to know about this download

rdb = redis.Redis()
val = rdb.get('download_progress')


问:
@PropertySource() is not working in bean defined in XML imported by @ImportResource()
Can not find correct answer to next situation in Internet. So, if it was already discussed somewher, just point out.

I jave UnitTest that is run by Spring:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/app-core-config.xml")
public class ConcurrentProcessingTest extends AbstractLSTest {
  public void testMethod1(){
    ...
  }
}
</code>```

spring/app-core-config.xml contains some beans that use @PropertySource.

For example, Service1Impl:

```<code>@Service
@PropertySource("classpath:system/service1.properties")
public class Service1Impl {
    @Value("${event.ack.warning}")
    private String eventAckWarningComm;

    @Value("${event.ack.info}")
    private String eventAckInfoComm;
}
</code>```

So, few classes with similar usage of @PropertySource are defined in spring/app-core-config.xml.

When I run mentioned UnitTest all works fine.

But I need some additional Java configuration for specific UnitTest.
So, I written next simple configuration for previous UnitTest:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ConcurrentProcessingTest.AppCoreConfiguration.class})
public class ConcurrentProcessingTest extends AbstractLSTest {

  @Configuration
  @ImportResource("classpath:spring/app-core-config.xml")
  //@PropertySource("classpath:system/service1.properties")  -- if uncommented, UT works
  //But it is annoying to add all propery-files here
  static class AppCoreConfiguration {
    //Here I want to add extra configuration in Java style
  }

  public void testMethod1(){
    ...
  }
}
</code>```

But when I run this UnitTest, I get next exception:

```<code>Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'event.ack.warning' in string value "${event.ack.warning}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:194)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:158)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:800)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:871)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 184 more
</code>```

Could someone explain me why @PropertySource is not working in bean defined in XML imported by @ImportResource  ?

答:
After you have demarcated your class with respective propertysource you need to declare static propertySourcesPlaceHolderConfigurer bean like below in your configuration class</p>

```<code>@Bean
    public static PropertySourcesPlaceholderConfigurer xxxpropertyConfig() {
        return new PropertySourcesPlaceholderConfigurer();
    }
</code>```

Body:
Can not find correct answer to next situation in Internet. So, if it was already discussed somewher, just point out.

I jave UnitTest that is run by Spring:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/app-core-config.xml")
public class ConcurrentProcessingTest extends AbstractLSTest {
  public void testMethod1(){
    ...
  }
}

spring/app-core-config.xml contains some beans that use @PropertySource.

For example, Service1Impl:

@Service
@PropertySource("classpath:system/service1.properties")
public class Service1Impl {
    @Value("${event.ack.warning}")
    private String eventAckWarningComm;

    @Value("${event.ack.info}")
    private String eventAckInfoComm;
}

So, few classes with similar usage of @PropertySource are defined in spring/app-core-config.xml.

When I run mentioned UnitTest all works fine.

But I need some additional Java configuration for specific UnitTest.
So, I written next simple configuration for previous UnitTest:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ConcurrentProcessingTest.AppCoreConfiguration.class})
public class ConcurrentProcessingTest extends AbstractLSTest {

  @Configuration
  @ImportResource("classpath:spring/app-core-config.xml")
  //@PropertySource("classpath:system/service1.properties")  -- if uncommented, UT works
  //But it is annoying to add all propery-files here
  static class AppCoreConfiguration {
    //Here I want to add extra configuration in Java style
  }

  public void testMethod1(){
    ...
  }
}

But when I run this UnitTest, I get next exception:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'event.ack.warning' in string value "${event.ack.warning}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:194)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:158)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:800)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:871)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 184 more

Could someone explain me why @PropertySource is not working in bean defined in XML imported by @ImportResource  ?

Body:
After you have demarcated your class with respective propertysource you need to declare static propertySourcesPlaceHolderConfigurer bean like below in your configuration class

@Bean
    public static PropertySourcesPlaceholderConfigurer xxxpropertyConfig() {
        return new PropertySourcesPlaceholderConfigurer();
    }


问:
How to save TextBox text to text file using streamwriter
Firstoff I have to say that I am new to the c# programming. My problem is, that I have a window with a textbox and a button in it and what I am trying to accomplish is to write some text into the textbox and on button click I'd like to save that text into the ukony.txt file. But using the code bellow, after clicking a button nothing happens.</p>

```<code>public partial class Window1 : Window {
    public Window1() {
        InitializeComponent();

    }

    private void button_Click(object sender, RoutedEventArgs e)
        {
        string writerfile = @"D:\Games\ukony.txt";
        Window1 a = new Window1();
        using (StreamWriter writer = new StreamWriter(writerfile))
            {
            writer.WriteLine(a.textBlock.Text);
            writer.WriteLine(a.textBlock1.Text);
            }
        }
    }
</code>```

答:
The reason for not working is the newly created instance of the Window1 class. which is entirely different from the UI that you are actually seeing. So you need not to create an instance at that place, directly use the textBox name to access the text

```<code>private void button_Click(object sender, RoutedEventArgs e)
{
    string writerfile = @"D:\Games\ukony.txt";
    using (StreamWriter writer = new StreamWriter(writerfile))
    {
        writer.WriteLine(textBlock.Text);
        writer.WriteLine(textBlock1.Text);
    }
}
</code>```

Body:
Firstoff I have to say that I am new to the c# programming. My problem is, that I have a window with a textbox and a button in it and what I am trying to accomplish is to write some text into the textbox and on button click I'd like to save that text into the ukony.txt file. But using the code bellow, after clicking a button nothing happens.

public partial class Window1 : Window {
    public Window1() {
        InitializeComponent();

    }

    private void button_Click(object sender, RoutedEventArgs e)
        {
        string writerfile = @"D:\Games\ukony.txt";
        Window1 a = new Window1();
        using (StreamWriter writer = new StreamWriter(writerfile))
            {
            writer.WriteLine(a.textBlock.Text);
            writer.WriteLine(a.textBlock1.Text);
            }
        }
    }

Body:
The reason for not working is the newly created instance of the Window1 class. which is entirely different from the UI that you are actually seeing. So you need not to create an instance at that place, directly use the textBox name to access the text

private void button_Click(object sender, RoutedEventArgs e)
{
    string writerfile = @"D:\Games\ukony.txt";
    using (StreamWriter writer = new StreamWriter(writerfile))
    {
        writer.WriteLine(textBlock.Text);
        writer.WriteLine(textBlock1.Text);
    }
}


问:
Why does htmlElement only return content of element when returned in javascript function?
I am trying to dynamically create a tabel containing name and three radio buttons. The output should be:

```<code><tr>
   <td>Jane Doe</td>
   <td><label class="radio-inline" id="foo"><input type="radio" name="bar"></label></td>
   <td><label class="radio-inline" id="foo"><input type="radio" name="bar"></label></td>
   <td><label class="radio-inline" id="foo"><input type="radio" name="bar"></label></td>
</tr>
</code>```

in javascript I am using functions to create the TD, containing the label containing the input:

```<code>function createRadioTdElement(naam, value){
    var radioTdElement = document.createElement('TD');
    var labelElement = createLabelElement(value);
    var radioElement = createRadioElement(naam);
    labelElement.appendChild(radioElement);
    return radioTdElement.appendChild(labelElement);
}

function createLabelElement(value){
    var labelElement = document.createElement('label');
    labelElement.className = 'radio-inline';
    labelElement.id = value;
    return labelElement;
}

function createRadioElement(naam) {
    var inputElement = document.createElement('input');
    inputElement.type = 'radio';
    inputElement.name = naam;
    return inputElement;
}
</code>```

however when I call this function to append it to a TR element:

```<code>eTR.appendChild(createRadioTdElement(naam, value));
</code>```

the createRadioTdElement only returns:

```<code><label class="radio-inline" id="foo"><input type="radio" name="bar"></label>
</code>```

why does it not return it with the "td" tags like:

```<code><td><label class="radio-inline" id="foo"><input type="radio" name="bar"></label></td>
</code>```

答:
The comments answered the question but I figured I would write a working example for completeness.

Kevin mentioned that appendChild returns the appended child, not the parent. So you want to return the  element which I commented below.

Additionally, the id attribute should be unique. So I also changed the id in my example below.

function createRadioTdElement(naam, value){
    var radioTdElement = document.createElement('TD');
    var labelElement = createLabelElement(value);
    var radioElement = createRadioElement(naam);
    labelElement.appendChild(radioElement);
    radioTdElement.appendChild(labelElement);
    return radioTdElement; // return td element
}

function createLabelElement(value){
    var labelElement = document.createElement('label');
    labelElement.className = 'radio-inline';
    labelElement.id = value;
    return labelElement;
}

function createRadioElement(naam) {
    var inputElement = document.createElement('input');
    inputElement.type = 'radio';
    inputElement.name = naam;
    return inputElement;
}

var td = createRadioTdElement('bar', 'four');
var tr = document.querySelector('tr');
tr.appendChild(td);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
     <td>Jane Doe</td>
     <td><label class="radio-inline" id="one"><input type="radio" name="bar"></label></td>
     <td><label class="radio-inline" id="two"><input type="radio" name="bar"></label></td>
     <td><label class="radio-inline" id="three"><input type="radio" name="bar"></label></td>
  </tr>
</table></code>```

Body:
I am trying to dynamically create a tabel containing name and three radio buttons. The output should be:

   Jane Doe
   <input type="radio" name="bar">
   <input type="radio" name="bar">
   <input type="radio" name="bar">

in javascript I am using functions to create the TD, containing the label containing the input:

function createRadioTdElement(naam, value){
    var radioTdElement = document.createElement('TD');
    var labelElement = createLabelElement(value);
    var radioElement = createRadioElement(naam);
    labelElement.appendChild(radioElement);
    return radioTdElement.appendChild(labelElement);
}

function createLabelElement(value){
    var labelElement = document.createElement('label');
    labelElement.className = 'radio-inline';
    labelElement.id = value;
    return labelElement;
}

function createRadioElement(naam) {
    var inputElement = document.createElement('input');
    inputElement.type = 'radio';
    inputElement.name = naam;
    return inputElement;
}

however when I call this function to append it to a TR element:

eTR.appendChild(createRadioTdElement(naam, value));

the createRadioTdElement only returns:

<input type="radio" name="bar">

why does it not return it with the "td" tags like:

<input type="radio" name="bar">

Body:
The comments answered the question but I figured I would write a working example for completeness.

Kevin mentioned that appendChild returns the appended child, not the parent. So you want to return the <td> element which I commented below.

Additionally, the id attribute should be unique. So I also changed the id in my example below.

function createRadioTdElement(naam, value){
    var radioTdElement = document.createElement('TD');
    var labelElement = createLabelElement(value);
    var radioElement = createRadioElement(naam);
    labelElement.appendChild(radioElement);
    radioTdElement.appendChild(labelElement);
    return radioTdElement; // return td element
}

function createLabelElement(value){
    var labelElement = document.createElement('label');
    labelElement.className = 'radio-inline';
    labelElement.id = value;
    return labelElement;
}

function createRadioElement(naam) {
    var inputElement = document.createElement('input');
    inputElement.type = 'radio';
    inputElement.name = naam;
    return inputElement;
}

var td = createRadioTdElement('bar', 'four');
var tr = document.querySelector('tr');
tr.appendChild(td);

<table>
  <tr>
     <td>Jane Doe</td>
     <td><label class="radio-inline" id="one"><input type="radio" name="bar"></label></td>
     <td><label class="radio-inline" id="two"><input type="radio" name="bar"></label></td>
     <td><label class="radio-inline" id="three"><input type="radio" name="bar"></label></td>
  </tr>
</table>


问:
How to define allowed_address_pairs for openstack instance's port in Cloudify blueprint?
I am trying to write a Cloudify blueprint for a basic network topology that contains a firewall instance (just be iptables) that is responsible for filtering traffic (I integrated Cloudify with OpenStack for application orchestration).

However, I realised that OpenStack does not allow an instance to route traffic because of port_security. I solved this problem manually by disabling port_security or adding specific source IP addresses (hosts or subnets) to firewall's port using an option called allowed_address_pairs.

Now I want to know how this can be solved automatically by defining one of above options in Cloudify blueprint?

Many thanks!

答: I solved my problem after reading carefully documents about OpenStack API and OpenStack plugin's Cloudify.</p>


问:
Conditionally Count Value from Array into New Field
Consider the following data:

```<code>{
    "_id" : ObjectId("592ffb3d257acc76fc0eecd7"),
    "primaryProcessName" : "BI",
    "dateTimeStamp" : ISODate("2017-06-01T11:32:12.834+0000"),
    "tag" : [
        {
            "key" : "processname",
            "value" : "NEUpdateService",
            "value_original" : "NEUpdateService"
        },
        {
            "key" : "processstageid",
            "value" : "inprocess",
            "value_original" : "InProcess"
        },
    ]
}
{
    "_id" : ObjectId("592ffb3d257acc76fc0eecdd"),
    "primaryProcessName" : "BI",
    "dateTimeStamp" : ISODate("2017-06-01T11:32:13.345+0000"),
    "tag" : [
        {
            "key" : "processname",
            "value" : "CommissionPaymentSend",
            "value_original" : "CommissionPaymentSend"
        },
        {
            "key" : "processstageid",
            "value" : "faulted",
            "value_original" : "Faulted"
        },
    ]
}
{
    "_id" : ObjectId("592ffb3d257acc76fc0eece4"),
    "primaryProcessName" : "BI",
    "dateTimeStamp" : ISODate("2017-06-01T11:32:13.745+0000"),
    "tag" : [
        {
            "key" : "processname",
            "value" : "commonbusinessintegratorservice",
            "value_original" : "CommonBusinessIntegratorService"
        },
        {
            "key" : "processstageid",
            "value" : "inprocess",
            "value_original" : "InProcess"
        },
    ]
}
{
    "_id" : ObjectId("592ffb3d257acc76fc0eecea"),
    "primaryProcessName" : "BI",
    "dateTimeStamp" : ISODate("2017-06-01T11:32:13.876+0000"),
    "tag" : [
        {
            "key" : "processname",
            "value" : "commonbusinessintegratorservice",
            "value_original" : "CommonBusinessIntegratorService"
        },
        {
            "key" : "processstageid",
            "value" : "inprocess",
            "value_original" : "InProcess"
        },
    ]
}
{
    "_id" : ObjectId("592ffb3e257acc76fc0eecf1"),
    "primaryProcessName" : "BI",
    "dateTimeStamp" : ISODate("2017-06-01T11:32:14.193+0000"),
    "tag" : [
        {
            "key" : "processname",
            "value" : "SmartComplianceMessenger",
            "value_original" : "SmartComplianceMessenger"
        },
        {
            "key" : "processstageid",
            "value" : "complete",
            "value_original" : "Complete"
        },
    ]
}
</code>```

I am trying to write a query to aggregate this data to show in the following format:

```<code>{
    "Total" : 1982, "InProcess" : 991, "Complete" : 991, "Faulted" : 0,
    "name" : "SmartComplianceMessenger",
    "displayName" : "SmartComplianceMessenger",
    "drillDownUrl" : "process/forprimary/name/SmartComplianceMessenger"
},

{
    "Total" : 122333, "InProcess" : 56375, "Complete" : 54856, "Faulted" : 11102,
    "name" : "NEUpdateService",
    "displayName" : "NEUpdateService",
    "drillDownUrl" : "process/forprimary/name/NEUpdateService"
},
....
</code>```

This is what I have so far:

```<code>db.ActivityNotice.aggregate([
    {$match: {
        dateTimeStamp: {
            $gte: ISODate("2017-06-01T11:00:00.000Z")
            , $lt: ISODate("2017-06-01T11:45:00.000Z")
        }
    }},
    {$group :
      {
        _id: {process: "$primaryProcessName"} //, status:"$processStageId"
        , Total:{$sum:1}
        , InProcess: {$sum:0}// { $sum: {$cond: [{$eq: ["$processStageId","InProcess"]},1,0]}}
        , Complete: {$sum:0} // { $sum: {$cond: [{$eq: ["$processStageId","Complete"]},1,0]}}
        , Faulted: {$sum:0} // { $sum: {$cond: [{$eq: ["$processStageId","Faulted"]},1,0]}}
        , Test: { $sum: {$cond: [{$eq: ["tag.key","processstageid"]},1,0]}}
    }},
    {$project: {
      _id: 0,
      name: "$_id.process", displayName: "$_id.process",
      drillDownUrl: { $concat: [ "process/forprimary/name/", "$_id.process" ] },
      Total: 1, InProcess: 1 , Complete: 1, Faulted: 1, Test: 1
    }}
])
</code>```

The challenge I am facing is selecting the value for the "processname" key from tags into a new field, called processName and the value for "processtageid" into a new field so I can do the sum on those values.

Any help would be greatly appreciated.

答:
You want $filter and $size for the most efficient way:

{ "$group": {
  "_id": "$primaryProcessName",
  "Total": { "$sum": 1 },
  "InProcess": {
    "$sum": {
      "$size": {
        "$filter": {
          "input": "$tag",
          "as": "t",
          "cond": {
            "$and": [
              { "$eq": [ "$$t.key", "processstageid" ] },
              { "$eq": [ "$$t.value","inprocess"] }
            ]
          }
        }
      }
    }
  },
  "Complete": {
    "$sum": {
      "$size": {
        "$filter": {
          "input": "$tag",
          "as": "t",
          "cond": {
            "$and": [
              { "$eq": [ "$$t.key", "processstageid" ] },
              { "$eq": [ "$$t.value","complete"] }
            ]
          }
        }
      }
    }
  },
  "Faulted": {
    "$sum": {
      "$size": {
        "$filter": {
          "input": "$tag",
          "as": "t",
          "cond": {
            "$and": [
              { "$eq": [ "$$t.key", "processstageid" ] },
              { "$eq": [ "$$t.value","faulted"] }
            ]
          }
        }
      }
    }
  }
}}
```

$filter has it's own condition for which we can use $and to match the multiple conditions of different properties of the array element. This reduces the array to only the entries that match, where you can then take the $size

Body:
Consider the following data:

{
    "_id" : ObjectId("592ffb3d257acc76fc0eecd7"),
    "primaryProcessName" : "BI",
    "dateTimeStamp" : ISODate("2017-06-01T11:32:12.834+0000"),
    "tag" : [
        {
            "key" : "processname",
            "value" : "NEUpdateService",
            "value_original" : "NEUpdateService"
        },
        {
            "key" : "processstageid",
            "value" : "inprocess",
            "value_original" : "InProcess"
        },
    ]
}
{
    "_id" : ObjectId("592ffb3d257acc76fc0eecdd"),
    "primaryProcessName" : "BI",
    "dateTimeStamp" : ISODate("2017-06-01T11:32:13.345+0000"),
    "tag" : [
        {
            "key" : "processname",
            "value" : "CommissionPaymentSend",
            "value_original" : "CommissionPaymentSend"
        },
        {
            "key" : "processstageid",
            "value" : "faulted",
            "value_original" : "Faulted"
        },
    ]
}
{
    "_id" : ObjectId("592ffb3d257acc76fc0eece4"),
    "primaryProcessName" : "BI",
    "dateTimeStamp" : ISODate("2017-06-01T11:32:13.745+0000"),
    "tag" : [
        {
            "key" : "processname",
            "value" : "commonbusinessintegratorservice",
            "value_original" : "CommonBusinessIntegratorService"
        },
        {
            "key" : "processstageid",
            "value" : "inprocess",
            "value_original" : "InProcess"
        },
    ]
}
{
    "_id" : ObjectId("592ffb3d257acc76fc0eecea"),
    "primaryProcessName" : "BI",
    "dateTimeStamp" : ISODate("2017-06-01T11:32:13.876+0000"),
    "tag" : [
        {
            "key" : "processname",
            "value" : "commonbusinessintegratorservice",
            "value_original" : "CommonBusinessIntegratorService"
        },
        {
            "key" : "processstageid",
            "value" : "inprocess",
            "value_original" : "InProcess"
        },
    ]
}
{
    "_id" : ObjectId("592ffb3e257acc76fc0eecf1"),
    "primaryProcessName" : "BI",
    "dateTimeStamp" : ISODate("2017-06-01T11:32:14.193+0000"),
    "tag" : [
        {
            "key" : "processname",
            "value" : "SmartComplianceMessenger",
            "value_original" : "SmartComplianceMessenger"
        },
        {
            "key" : "processstageid",
            "value" : "complete",
            "value_original" : "Complete"
        },
    ]
}

I am trying to write a query to aggregate this data to show in the following format:

{
    "Total" : 1982, "InProcess" : 991, "Complete" : 991, "Faulted" : 0,
    "name" : "SmartComplianceMessenger",
    "displayName" : "SmartComplianceMessenger",
    "drillDownUrl" : "process/forprimary/name/SmartComplianceMessenger"
},

{
    "Total" : 122333, "InProcess" : 56375, "Complete" : 54856, "Faulted" : 11102,
    "name" : "NEUpdateService",
    "displayName" : "NEUpdateService",
    "drillDownUrl" : "process/forprimary/name/NEUpdateService"
},
....

This is what I have so far:

db.ActivityNotice.aggregate([
    {$match: {
        dateTimeStamp: {
            $gte: ISODate("2017-06-01T11:00:00.000Z")
            , $lt: ISODate("2017-06-01T11:45:00.000Z")
        }
    }},
    {$group :
      {
        _id: {process: "$primaryProcessName"} //, status:"$processStageId"
        , Total:{$sum:1}
        , InProcess: {$sum:0}// { $sum: {$cond: [{$eq: ["$processStageId","InProcess"]},1,0]}}
        , Complete: {$sum:0} // { $sum: {$cond: [{$eq: ["$processStageId","Complete"]},1,0]}}
        , Faulted: {$sum:0} // { $sum: {$cond: [{$eq: ["$processStageId","Faulted"]},1,0]}}
        , Test: { $sum: {$cond: [{$eq: ["tag.key","processstageid"]},1,0]}}
    }},
    {$project: {
      _id: 0,
      name: "$_id.process", displayName: "$_id.process",
      drillDownUrl: { $concat: [ "process/forprimary/name/", "$_id.process" ] },
      Total: 1, InProcess: 1 , Complete: 1, Faulted: 1, Test: 1
    }}
])

The challenge I am facing is selecting the value for the "processname" key from tags into a new field, called processName and the value for "processtageid" into a new field so I can do the sum on those values.

Any help would be greatly appreciated.

Body:
You want $filter and $size for the most efficient way:

{ "$group": {
  "_id": "$primaryProcessName",
  "Total": { "$sum": 1 },
  "InProcess": {
    "$sum": {
      "$size": {
        "$filter": {
          "input": "$tag",
          "as": "t",
          "cond": {
            "$and": [
              { "$eq": [ "$$t.key", "processstageid" ] },
              { "$eq": [ "$$t.value","inprocess"] }
            ]
          }
        }
      }
    }
  },
  "Complete": {
    "$sum": {
      "$size": {
        "$filter": {
          "input": "$tag",
          "as": "t",
          "cond": {
            "$and": [
              { "$eq": [ "$$t.key", "processstageid" ] },
              { "$eq": [ "$$t.value","complete"] }
            ]
          }
        }
      }
    }
  },
  "Faulted": {
    "$sum": {
      "$size": {
        "$filter": {
          "input": "$tag",
          "as": "t",
          "cond": {
            "$and": [
              { "$eq": [ "$$t.key", "processstageid" ] },
              { "$eq": [ "$$t.value","faulted"] }
            ]
          }
        }
      }
    }
  }
}}

$filter has it's own condition for which we can use $and to match the multiple conditions of different properties of the array element. This reduces the array to only the entries that match, where you can then take the $size


问:
unique field validations in model based on foriegn key yii2
I have a table called menusoffered where I am storing menuname based on restaurantid which is a foreign key.

In my menusoffered model I have declared that menuname has a unique validator, but this is checking the uniqueness from the entire table.

I want it to check uniqueness based on restaurantid,
Can any one help me how to make this menuname unique for particular restaurantid?

Below is my given menu model,

```<code>class Menusoffered extends \yii\db\ActiveRecord
{

/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'menusoffered';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
            ['phase_id', 'required', 'message' => 'Please select Phase'],
            ['menuname', 'required'],
            ['price', 'required'],
            [['price'],'integer' , 'message' =>'Price should be in digits'],
            [['image_url'], 'file'],
            [['description', 'status'], 'string'],
            [['createdts','restaurantid'], 'safe'],
            ['master_menu_sepcality_id', 'required', 'message' => 'Please select Speciality'],
            ['master_menu_type_id', 'required', 'message' => 'Please select Type'],
            ['menuname', 'unique', 'with'=>'restaurantid'],
            [['restaurantid'], 'exist', 'skipOnError' => true, 'targetClass' => Restaurant::className(), 'targetAttribute' => ['restaurantid' => 'id']],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'master_menu_sepcality_id' => 'Master Menu Sepcality ID',
        'master_menu_type_id' => 'Master Menu Type ID',
        'item' => 'Item',
        'price' => 'Price',
        'restaurantid' => 'Restaurantid',
        'phase_id' => 'Phase ID',
        'description' => 'Description',
        'image_url' => 'Image Url',
        'status' => 'Status',
        'createdts' => 'Createdts',
    ];
} }
</code>```

答:
Try this: Yii2 Unique Validator:</p>

```<code>// a1 and a2 need to be unique together, only a1 will receive error message
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
</code>```

Body:
I have a table called menusoffered where I am storing menuname based on restaurantid which is a foreign key.

In my menusoffered model I have declared that menuname has a unique validator, but this is checking the uniqueness from the entire table.

I want it to check uniqueness based on restaurantid,
Can any one help me how to make this menuname unique for particular restaurantid?

Below is my given menu model,

class Menusoffered extends \yii\db\ActiveRecord
{

/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'menusoffered';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
            ['phase_id', 'required', 'message' => 'Please select Phase'],
            ['menuname', 'required'],
            ['price', 'required'],
            [['price'],'integer' , 'message' =>'Price should be in digits'],
            [['image_url'], 'file'],
            [['description', 'status'], 'string'],
            [['createdts','restaurantid'], 'safe'],
            ['master_menu_sepcality_id', 'required', 'message' => 'Please select Speciality'],
            ['master_menu_type_id', 'required', 'message' => 'Please select Type'],
            ['menuname', 'unique', 'with'=>'restaurantid'],
            [['restaurantid'], 'exist', 'skipOnError' => true, 'targetClass' => Restaurant::className(), 'targetAttribute' => ['restaurantid' => 'id']],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'master_menu_sepcality_id' => 'Master Menu Sepcality ID',
        'master_menu_type_id' => 'Master Menu Type ID',
        'item' => 'Item',
        'price' => 'Price',
        'restaurantid' => 'Restaurantid',
        'phase_id' => 'Phase ID',
        'description' => 'Description',
        'image_url' => 'Image Url',
        'status' => 'Status',
        'createdts' => 'Createdts',
    ];
} }

Body:
Try this: Yii2 Unique Validator:

// a1 and a2 need to be unique together, only a1 will receive error message
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]


问:
Fastest way to compute a factorial in a numba nopython function
I have a function that I want to compile with numba, however I need to calculate a factorial inside that function. Unfortunatly numba doesn't support math.factorial:

```<code>import math
import numba as nb

@nb.njit
def factorial1(x):
    return math.factorial(x)

factorial1(10)
# UntypedAttributeError: Failed at nopython (nopython frontend)
</code>```

I saw that it supported math.gamma (which could be used to calculate the factorial), however contrary to the real math.gamma function it doesn't return floats that represent "integral values":

```<code>@nb.njit
def factorial2(x):
    return math.gamma(x+1)

factorial2(10)
# 3628799.9999999995  <-- not exact

math.gamma(11)
# 3628800.0  <-- exact
</code>```

and it's slow compared to math.factorial:

```<code>%timeit factorial2(10)
# 1.12 µs ± 11.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit math.factorial(10)
# 321 ns ± 6.12 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
</code>```

So I decided to define my own function:

```<code>@nb.njit
def factorial3(x):
    n = 1
    for i in range(2, x+1):
        n *= i
    return n

factorial3(10)
# 3628800

%timeit factorial3(10)
# 821 ns ± 12.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
</code>```

It's still slower than math.factorial but it's faster than a math.gamma based numba function and the value is "exact".

So I'm looking for the fastest way to compute the factorial of a positive integer number (<= 20; to avoid overflow) inside a nopython numba function.

答:
For values <= 20, python is using a lookup table, as was suggested in the comments.
https://github.com/python/cpython/blob/3.6/Modules/mathmodule.c#L1452

```<code>LOOKUP_TABLE = np.array([
    1, 1, 2, 6, 24, 120, 720, 5040, 40320,
    362880, 3628800, 39916800, 479001600,
    6227020800, 87178291200, 1307674368000,
    20922789888000, 355687428096000, 6402373705728000,
    121645100408832000, 2432902008176640000], dtype='int64')

@nb.jit
def fast_factorial(n):
    if n > 20:
        raise ValueError
    return LOOKUP_TABLE[n]
</code>```

Called from python it's slightly slower than the python version due to the numba dispatch overhead.

```<code>In [58]: %timeit math.factorial(10)
10000000 loops, best of 3: 79.4 ns per loop

In [59]: %timeit fast_factorial(10)
10000000 loops, best of 3: 173 ns per loop
</code>```

But called inside another numba function can be much faster.

```<code>def loop_python():
    for i in range(10000):
        for n in range(21):
            math.factorial(n)

@nb.njit
def loop_numba():
    for i in range(10000):
        for n in range(21):
            fast_factorial(n)

In [65]: %timeit loop_python()
10 loops, best of 3: 36.7 ms per loop

In [66]: %timeit loop_numba()
10000000 loops, best of 3: 73.6 ns per loop
</code>```

Body:
I have a function that I want to compile with numba, however I need to calculate a factorial inside that function. Unfortunatly numba doesn't support math.factorial:

import math
import numba as nb

@nb.njit
def factorial1(x):
    return math.factorial(x)

factorial1(10)
# UntypedAttributeError: Failed at nopython (nopython frontend)

I saw that it supported math.gamma (which could be used to calculate the factorial), however contrary to the real math.gamma function it doesn't return floats that represent "integral values":

@nb.njit
def factorial2(x):
    return math.gamma(x+1)

factorial2(10)
# 3628799.9999999995  <-- not exact

math.gamma(11)
# 3628800.0  <-- exact

and it's slow compared to math.factorial:

%timeit factorial2(10)
# 1.12 µs ± 11.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit math.factorial(10)
# 321 ns ± 6.12 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

So I decided to define my own function:

@nb.njit
def factorial3(x):
    n = 1
    for i in range(2, x+1):
        n *= i
    return n

factorial3(10)
# 3628800

%timeit factorial3(10)
# 821 ns ± 12.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

It's still slower than math.factorial but it's faster than a math.gamma based numba function and the value is "exact".

So I'm looking for the fastest way to compute the factorial of a positive integer number (<= 20; to avoid overflow) inside a nopython numba function.

Body:
For values <= 20, python is using a lookup table, as was suggested in the comments.
https://github.com/python/cpython/blob/3.6/Modules/mathmodule.c#L1452

LOOKUP_TABLE = np.array([
    1, 1, 2, 6, 24, 120, 720, 5040, 40320,
    362880, 3628800, 39916800, 479001600,
    6227020800, 87178291200, 1307674368000,
    20922789888000, 355687428096000, 6402373705728000,
    121645100408832000, 2432902008176640000], dtype='int64')

@nb.jit
def fast_factorial(n):
    if n > 20:
        raise ValueError
    return LOOKUP_TABLE[n]

Called from python it's slightly slower than the python version due to the numba dispatch overhead.

In [58]: %timeit math.factorial(10)
10000000 loops, best of 3: 79.4 ns per loop

In [59]: %timeit fast_factorial(10)
10000000 loops, best of 3: 173 ns per loop

But called inside another numba function can be much faster.

def loop_python():
    for i in range(10000):
        for n in range(21):
            math.factorial(n)

@nb.njit
def loop_numba():
    for i in range(10000):
        for n in range(21):
            fast_factorial(n)

In [65]: %timeit loop_python()
10 loops, best of 3: 36.7 ms per loop

In [66]: %timeit loop_numba()
10000000 loops, best of 3: 73.6 ns per loop


问:
npm request.post giving error everytime but the same post works with JQuery
I am trying to make a post request from express js to an api, from serverside.

Here is the code for it

```<code>request.post({
                url: $url,
                crossDomain: true,
                data: {id : '392', sid: 'abc'}
                }, function(error, response, body){
                    console.log(response.statusCode);
                    console.log(body);
            });
</code>```

this always returns with a response statusCode 500;

On the other hand, I tried the same post request from server side using Jquery.

Here is the code for it.

```<code>$.ajax({
    url: $url,
    crossDomain:true,
    data: {
        id : $id,
        sid: $sid
    },
    type: "POST",
    // dataType: "json",

    //on success
    success: function(response){
        //do something after something is received data
    },
    //on error
    error: function(jqXHR, exception){
        //bad request
        console.log(jqXHR.status);
        console.log(exception);
    }
});
</code>```

The $url and all the other variables are same in both the cases. Though, I get proper response and status code 200 for the post I do with Jquery, unlike the one I do with npm request module.

Where am I going wrong?

答:
And what about this code?

I also don't seem to find any reference to the 'crossDomain' option in the request.js docs

```<code>var request = require('request');
request.post(
    {
        headers: {'content-type':'application/json'},
        url: $url,
        form: {id : '392', sid: 'abc'}
    },
    function(error, response, body){
        console.log(response.statusCode);
        console.log(body)
    }
);
</code>```

Body:
I am trying to make a post request from express js to an api, from serverside.

Here is the code for it

request.post({
                url: $url,
                crossDomain: true,
                data: {id : '392', sid: 'abc'}
                }, function(error, response, body){
                    console.log(response.statusCode);
                    console.log(body);
            });

this always returns with a response statusCode 500;

On the other hand, I tried the same post request from server side using Jquery.

Here is the code for it.

$.ajax({
    url: $url,
    crossDomain:true,
    data: {
        id : $id,
        sid: $sid
    },
    type: "POST",
    // dataType: "json",

    //on success
    success: function(response){
        //do something after something is received data
    },
    //on error
    error: function(jqXHR, exception){
        //bad request
        console.log(jqXHR.status);
        console.log(exception);
    }
});

The $url and all the other variables are same in both the cases. Though, I get proper response and status code 200 for the post I do with Jquery, unlike the one I do with npm request module.

Where am I going wrong?

Body:
And what about this code?

I also don't seem to find any reference to the 'crossDomain' option in the request.js docs

var request = require('request');
request.post(
    {
        headers: {'content-type':'application/json'},
        url: $url,
        form: {id : '392', sid: 'abc'}
    },
    function(error, response, body){
        console.log(response.statusCode);
        console.log(body)
    }
);


问:
How to create a customized text area in Java for Java code
I want to add GUI to my software and I'm trying to create a text area designed for java code.

In other words, I want to create a small java editor area. How can I do that?
I'm using IntelliJ and SWING if it matters.

答:
I think this is what you are looking for: https://github.com/bobbylight/RSyntaxTextArea

Its is a text editor for Java swing applications.


问:
php artisan serve -- throws error
So I just beginning learning Laravel today and installed Composer and Laravel

I created a new application using :-

```<code>laravel new application
</code>```

in my folder :-

```<code>/Library/WebServer/Documents/
</code>```

However, when I try to run :-

```<code>php artisan serve
</code>```

I get this error :-

```<code>Warning: require(/Library/WebServer/Documents/application/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /Library/WebServer/Documents/application/bootstrap/autoload.php on line 17

Fatal error: require(): Failed opening required '/Library/WebServer/Documents/application/bootstrap/../vendor/autoload.php' (include_path='.:') in /Library/WebServer/Documents/application/bootstrap/autoload.php on line 17
</code>```

I've already tried updating my composer, didn't work.
What am I doing wrong here?

Edit

Running composer install gives this :-

```<code>Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - This package requires php >=5.6.4 but your PHP version (5.5.34) does not satisfy that requirement.
  Problem 2
    - Installation request for laravel/framework v5.4.24 -> satisfiable by laravel/framework[v5.4.24].
    - laravel/framework v5.4.24 requires php >=5.6.4 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 3
    - Installation request for phpunit/php-code-coverage 4.0.8 -> satisfiable by phpunit/php-code-coverage[4.0.8].
    - phpunit/php-code-coverage 4.0.8 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 4
    - Installation request for phpunit/phpunit 5.7.20 -> satisfiable by phpunit/phpunit[5.7.20].
    - phpunit/phpunit 5.7.20 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 5
    - Installation request for phpunit/phpunit-mock-objects 3.4.3 -> satisfiable by phpunit/phpunit-mock-objects[3.4.3].
    - phpunit/phpunit-mock-objects 3.4.3 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 6
    - Installation request for sebastian/code-unit-reverse-lookup 1.0.1 -> satisfiable by sebastian/code-unit-reverse-lookup[1.0.1].
    - sebastian/code-unit-reverse-lookup 1.0.1 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 7
    - Installation request for sebastian/environment 2.0.0 -> satisfiable by sebastian/environment[2.0.0].
    - sebastian/environment 2.0.0 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 8
    - Installation request for sebastian/object-enumerator 2.0.1 -> satisfiable by sebastian/object-enumerator[2.0.1].
    - sebastian/object-enumerator 2.0.1 requires php >=5.6 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 9
    - Installation request for sebastian/resource-operations 1.0.0 -> satisfiable by sebastian/resource-operations[1.0.0].
    - sebastian/resource-operations 1.0.0 requires php >=5.6.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 10
    - Installation request for sebastian/version 2.0.1 -> satisfiable by sebastian/version[2.0.1].
    - sebastian/version 2.0.1 requires php >=5.6 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 11
    - laravel/framework v5.4.24 requires php >=5.6.4 -> your PHP version (5.5.34) does not satisfy that requirement.
    - laravel/tinker v1.0.1 requires illuminate/console ~5.1 -> satisfiable by laravel/framework[v5.4.24].
    - Installation request for laravel/tinker v1.0.1 -> satisfiable by laravel/tinker[v1.0.1].
</code>```

答:
You have to install your project's vendor dependencies with composer install:

```<code># go to the app root folder
cd /Library/WebServer/Documents/application/
# install vendor dependecies
composer install
</code>```

Edit

After your question edit, it the error message says clearly that you have an old php version that can not run your new laravel app. You have two options:

upgrade your php to php 5.6.25 (preferably to php7)

downgrade your app( to laravel 5.2.*, the script below will delete it and install a new fresh one

```<code># go to the app root folder
cd /Library/WebServer/Documents/
rm -rf application
# install vendor dependecies
composer create-project --prefer-dist laravel/laravel application 5.2.*
</code>```

Title: php artisan serve -- throws error

Body:
So I just beginning learning Laravel today and installed Composer and Laravel

I created a new application using :-

laravel new application

in my folder :-

/Library/WebServer/Documents/

However, when I try to run :-

php artisan serve

I get this error :-

Warning: require(/Library/WebServer/Documents/application/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /Library/WebServer/Documents/application/bootstrap/autoload.php on line 17

Fatal error: require(): Failed opening required '/Library/WebServer/Documents/application/bootstrap/../vendor/autoload.php' (include_path='.:') in /Library/WebServer/Documents/application/bootstrap/autoload.php on line 17

I've already tried updating my composer, didn't work.
What am I doing wrong here?

Edit

Running composer install gives this :-

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - This package requires php >=5.6.4 but your PHP version (5.5.34) does not satisfy that requirement.
  Problem 2
    - Installation request for laravel/framework v5.4.24 -> satisfiable by laravel/framework[v5.4.24].
    - laravel/framework v5.4.24 requires php >=5.6.4 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 3
    - Installation request for phpunit/php-code-coverage 4.0.8 -> satisfiable by phpunit/php-code-coverage[4.0.8].
    - phpunit/php-code-coverage 4.0.8 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 4
    - Installation request for phpunit/phpunit 5.7.20 -> satisfiable by phpunit/phpunit[5.7.20].
    - phpunit/phpunit 5.7.20 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 5
    - Installation request for phpunit/phpunit-mock-objects 3.4.3 -> satisfiable by phpunit/phpunit-mock-objects[3.4.3].
    - phpunit/phpunit-mock-objects 3.4.3 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 6
    - Installation request for sebastian/code-unit-reverse-lookup 1.0.1 -> satisfiable by sebastian/code-unit-reverse-lookup[1.0.1].
    - sebastian/code-unit-reverse-lookup 1.0.1 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 7
    - Installation request for sebastian/environment 2.0.0 -> satisfiable by sebastian/environment[2.0.0].
    - sebastian/environment 2.0.0 requires php ^5.6 || ^7.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 8
    - Installation request for sebastian/object-enumerator 2.0.1 -> satisfiable by sebastian/object-enumerator[2.0.1].
    - sebastian/object-enumerator 2.0.1 requires php >=5.6 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 9
    - Installation request for sebastian/resource-operations 1.0.0 -> satisfiable by sebastian/resource-operations[1.0.0].
    - sebastian/resource-operations 1.0.0 requires php >=5.6.0 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 10
    - Installation request for sebastian/version 2.0.1 -> satisfiable by sebastian/version[2.0.1].
    - sebastian/version 2.0.1 requires php >=5.6 -> your PHP version (5.5.34) does not satisfy that requirement.
  Problem 11
    - laravel/framework v5.4.24 requires php >=5.6.4 -> your PHP version (5.5.34) does not satisfy that requirement.
    - laravel/tinker v1.0.1 requires illuminate/console ~5.1 -> satisfiable by laravel/framework[v5.4.24].
    - Installation request for laravel/tinker v1.0.1 -> satisfiable by laravel/tinker[v1.0.1].

Body:
You have to install your project's vendor dependencies with composer install:

# go to the app root folder
cd /Library/WebServer/Documents/application/
# install vendor dependecies
composer install

Edit

After your question edit, it the error message says clearly that you have an old php version that can not run your new laravel app. You have two options:

upgrade your php to php 5.6.25 (preferably to php7)

downgrade your app( to laravel 5.2.*, the script below will delete it and install a new fresh one

# go to the app root folder
cd /Library/WebServer/Documents/
rm -rf application
# install vendor dependecies
composer create-project --prefer-dist laravel/laravel application 5.2.*


问:
How to use different datasources to seed/clean database and running the tests?
We are trying to setup Arquillian for our projects to run automatic tests. We would like to make use of the arquillian persistence extension to write tests using the persistance layer. So we would like to seed the database using the @UsingDataSet and/or @CreateSchema@ annotations.

All of our application components have own database users which have only access to those tables/attributes the component needs. None of the components has rights to execute delete or DDL statements. So we need to switch between a database user/datasource seed/clean the schema before/after the tests and executing the tests like this:

Seed database, drop and recreate sequences using datasaource A

Run the test using datasource B

Clean database using datasource A

It should be obvious that if we would grant the needed delete/DDL-rights to the component database user for the arquillian tests the test results would not be reliable per defintion.

So how can we use different datasources, definied in the arquillian.xml, to seed/clean the database and running the tests?

答: Currently this is not supported yet (we are working on it), but in version 2.0.0 (currently are on alpha stage are on maven central) there is a workaround by using programmatic way instead of declarative way (using annotations). You can see an example here https://github.com/arquillian/arquillian-extension-persistence/blob/2.0.0/arquillian-ape-sql/container/int-tests/src/test/java/org/arquillian/integration/ape/dsl/ApeDslIncontainerTest.java</p>


问:
Issues Applying css styles conditionally to a twitter-bootstrap table
I have a table containing a list of products.  Below the table I have a text field where a barcode is entered, if the barcode is found the matching row in the table should be highlighted.  i've read through many similar scenarios and as far as I can tell i'm doing everything as I should.  I can see in the  google dev console that the barcode I enter matches the only product currently in my table however for some reason the css doesn't get applied...  Any idea what i'm doing wrong here?/how I can go about fixing it?

my css:

```<code>.found {
    background-color: green;
}
</code>```

my html table and input field:

```<code><table class="table table-striped">
   <thead>
      <tr>
         <th>Description</th>
         <th>Price</th>
         <th>Qty</th>
         <th>Barcode</th>
       </tr>
     </thead>
     <tbody>
        <tr *ngFor="let item of ticket.items" [class.found]="item.Barcode === spotCheckBarcode">
            <td>{{item?.ProductDetail_Name}}</td>
            <td>{{item?.Amount}}</td>
            <td>{{item?.Qty}}</td>
            <td>{{item?.Barcode}}</td>
          </tr>
       </tbody>
   </table>

   <form role="form" [formGroup]="spotCheckForm" (ngSubmit)="spotCheck(spotCheckForm.value.itemBarcode)">
        <input class="form-control" type="tel" placeholder="Enter item barcode" [formControl]="spotCheckForm.controls['itemBarcode']">
        <button class="btn btn-block" [disabled]="!spotCheckForm.controls['itemBarcode'].valid && busy"><span class="glyphicon glyphicon-search"></span> Search</button>
    </form>
</code>```

//my ts component function that sets spotCheckBarcode

```<code>spotCheck(itemBarcode: number) {
    let found: boolean = false;
     for (var i: number = 0; i < this.ticket.items.length; i++) {
        if (itemBarcode === this.ticket.items[i].Barcode) {
            console.log('found!');
            found = true;
            this.spotCheckBarcode = itemBarcode;
        }
    }
    if (found == false) {
        console.log(`found in if statement: ${found}`);
        this.showError("Item not found on ticket");
    }
}
</code>```

答:
Err, that looks right, but let's dig it apart.

So for the css class not being applied, have you tried inspecting the element to see if the class is added to the tr and maybe the styling is being overwritten?

Body:
I have a table containing a list of products.  Below the table I have a text field where a barcode is entered, if the barcode is found the matching row in the table should be highlighted.  i've read through many similar scenarios and as far as I can tell i'm doing everything as I should.  I can see in the  google dev console that the barcode I enter matches the only product currently in my table however for some reason the css doesn't get applied...  Any idea what i'm doing wrong here?/how I can go about fixing it?

my css:

.found {
    background-color: green;
}

my html table and input field:

         Description
         Price
         Qty
         Barcode

            {{item?.ProductDetail_Name}}
            {{item?.Amount}}
            {{item?.Qty}}
            {{item?.Barcode}}

   <form role="form" [formGroup]="spotCheckForm" (ngSubmit)="spotCheck(spotCheckForm.value.itemBarcode)">
        <input class="form-control" type="tel" placeholder="Enter item barcode" [formControl]="spotCheckForm.controls['itemBarcode']">
        <button class="btn btn-block" [disabled]="!spotCheckForm.controls['itemBarcode'].valid && busy"> Search</button>
    </form>

//my ts component function that sets spotCheckBarcode

spotCheck(itemBarcode: number) {
    let found: boolean = false;
     for (var i: number = 0; i < this.ticket.items.length; i++) {
        if (itemBarcode === this.ticket.items[i].Barcode) {
            console.log('found!');
            found = true;
            this.spotCheckBarcode = itemBarcode;
        }
    }
    if (found == false) {
        console.log(`found in if statement: ${found}`);
        this.showError("Item not found on ticket");
    }
}


问:
Get list of a class' instance methods
I have a class:

```<code>class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end
</code>```

How can I get a list of my methods in this class (method1, method2, method3)?

答:
According to Ruby Doc instance_methods

Returns an array containing the names of the public and protected
  instance methods in the receiver. For a module, these are the public
  and protected methods; for a class, they are the instance (not
  singleton) methods. If the optional parameter is false, the methods of
  any ancestors are not included.
  I am taking the official documentation example.

```<code>module A
  def method1()
    puts "method1 say hi"
  end
end
class B
  include A #mixin
  def method2()
     puts "method2 say hi"
  end
end
class C < B #inheritance
  def method3()
     puts "method3 say hi"
  end
end
</code>```

Let's see the output.

```<code>A.instance_methods(false)
  => [:method1]

A.instance_methods
  => [:method1]
B.instance_methods
 => [:method2, :method1, :nil?, :===, ...# ] # methods inherited from parent class, most important :method1 is also visible because we mix module A in class B

B.instance_methods(false)
  => [:method2]
C.instance_methods
  => [:method3, :method2, :method1, :nil?, :===, ...#] # same as above
C.instance_methods(false)
 => [:method3]
</code>```

Title: Get list of a class' instance methods

Body:
I have a class:

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

How can I get a list of my methods in this class (method1, method2, method3)?

Body:
According to Ruby Doc instance_methods

Returns an array containing the names of the public and protected
  instance methods in the receiver. For a module, these are the public
  and protected methods; for a class, they are the instance (not
  singleton) methods. If the optional parameter is false, the methods of
  any ancestors are not included.
  I am taking the official documentation example.

module A
  def method1()
    puts "method1 say hi"
  end
end
class B
  include A #mixin
  def method2()
     puts "method2 say hi"
  end
end
class C < B #inheritance
  def method3()
     puts "method3 say hi"
  end
end

Let's see the output.

A.instance_methods(false)
  => [:method1]

A.instance_methods
  => [:method1]
B.instance_methods
 => [:method2, :method1, :nil?, :===, ...# ] # methods inherited from parent class, most important :method1 is also visible because we mix module A in class B

B.instance_methods(false)
  => [:method2]
C.instance_methods
  => [:method3, :method2, :method1, :nil?, :===, ...#] # same as above
C.instance_methods(false)
 => [:method3]


问:
How to select all fields but show certain in DataGridView in C#
I am showing some data on DataGridView in c# windows form App. Here I want to select ID because I have to use it as foreign key but I don't want to show that ID field on grid.

```<code> using (SqlConnection con = new SqlConnection(constr))
            {
                con.Open();
                using (SqlCommand command = new SqlCommand("select * from PatientInfo", con))
                {
                    SqlDataReader reader = command.ExecuteReader();
                    if (reader.HasRows)
                    {
                        DataTable dt = new DataTable();
                        dt.Load(reader);
                        datagridpatient.DataSource = dt;
                        con.Close();
                    }
                }
            }
</code>```

I want to show just name, email, phone. At the same time for further use I need to select ID too.

答:
you can hide the column,

dataGridView.Columns["ColumnName"].Visible = false;

Ex:

```<code>    using (SqlConnection con = new SqlConnection(constr))
         {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
                using (SqlCommand command = new SqlCommand("select * from PatientInfo", con))
                {
                    SqlDataReader reader = command.ExecuteReader();
                    if (reader.HasRows)
                    {
                        DataTable dt = new DataTable();
                        dt.Load(reader);
                        datagridpatient.DataSource = dt;
                        if (datagridpatient.Columns.Contains("ID")
                           datagridpatient.Columns["ID"].Visible = false;
                        con.Close();
                    }
                }
            }
         }
</code>```

Body:
I am showing some data on DataGridView in c# windows form App. Here I want to select ID because I have to use it as foreign key but I don't want to show that ID field on grid.

 using (SqlConnection con = new SqlConnection(constr))
            {
                con.Open();
                using (SqlCommand command = new SqlCommand("select * from PatientInfo", con))
                {
                    SqlDataReader reader = command.ExecuteReader();
                    if (reader.HasRows)
                    {
                        DataTable dt = new DataTable();
                        dt.Load(reader);
                        datagridpatient.DataSource = dt;
                        con.Close();
                    }
                }
            }

I want to show just name, email, phone. At the same time for further use I need to select ID too.

Body:
you can hide the column,

dataGridView.Columns["ColumnName"].Visible = false;

Ex:

    using (SqlConnection con = new SqlConnection(constr))
         {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
                using (SqlCommand command = new SqlCommand("select * from PatientInfo", con))
                {
                    SqlDataReader reader = command.ExecuteReader();
                    if (reader.HasRows)
                    {
                        DataTable dt = new DataTable();
                        dt.Load(reader);
                        datagridpatient.DataSource = dt;
                        if (datagridpatient.Columns.Contains("ID")
                           datagridpatient.Columns["ID"].Visible = false;
                        con.Close();
                    }
                }
            }
         }


问:
DOJO with spring framework
I am new to Spring as well as Dojo. I need to use Dojo with one of my mvc project in Spring 3.0

I came accross below link which talks about using spring-js with Dojo.spring-js part of spring framework?

http://static.springsource.org/spring-webflow/docs/2.0.x/reference/html/ch11.html

I could not really follow that link, is there any step by step tutorial which will show me how to use dojo with spring framework 3.0 ?

I need to start with simple things with Dojo like client side validation of forms.

Thanks in advance!

答: Spring Roo uses Dojo, so you can create a Roo Project and have a look like they did it.</p>

Title: DOJO with spring framework


问:
AWS CLI in Windows EC2 cannot use role to access S3
I am very new to AWS. I created an IAM role which has full access to S3. I assigned this role to a Windows Server EC2 instance. I then installed CLI on that instance. I then remoted into that instance using RDP, and started a CMD windows, and typed in

```<code>aws s3 ls
</code>```

It complained that

```<code>Unable to locate credentials. You can configure credentials by running "aws configure".
</code>```

Now that this EC2 has been assigned the role that has full access to S3, why can't I directly access S3?

答: Thank you John Rotenstein for your help. You pointed me to the right direction. I created a new instance from scratch, and everything worked. The previous instance I installed IIS and ASP.NET on it. Would it be possibly the reason?</p>

Body:
I am very new to AWS. I created an IAM role which has full access to S3. I assigned this role to a Windows Server EC2 instance. I then installed CLI on that instance. I then remoted into that instance using RDP, and started a CMD windows, and typed in

aws s3 ls

It complained that

Unable to locate credentials. You can configure credentials by running "aws configure".

Now that this EC2 has been assigned the role that has full access to S3, why can't I directly access S3?


问:
how to remove \ from json data?
I use .net wcf services in my angular project, but i get the response like that:

```<code>{
  "stateResult": "[{\"state_id\":\"1\",\"state_name\":\"Madhya Pradesh\",\"IsActive\":\"True\"},{\"state_id\":\"2\",\"state_name\":\"Gujrat\",\"IsActive\":\"True\"},{\"state_id\":\"3\",\"state_name\":\"Goa\",\"IsActive\":\"True\"},{\"state_id\":\"4\",\"state_name\":\"Maharashtra\",\"IsActive\":\"True\"}]"
}
</code>```

but the desired result;

```<code>[{"state_id":"1","state_name":"Madhya Pradesh","IsActive":"True"},{"state_id":"2","state_name":"Gujrat","IsActive":"True"},{"state_id":"3","state_name":"Goa","IsActive":"True"},{"state_id":"4","state_name":"Maharashtra","IsActive":"True"}]
</code>```

答:
It looks like the json data is double encoded, for example in php I was wrongly doing php_encode() twice.

Not sure from the question who is doing the encoding on your side but it looks like this may be the case for you too.

Title: how to remove \ from json data?

Body:
I use .net wcf services in my angular project, but i get the response like that:

{
  "stateResult": "[{\"state_id\":\"1\",\"state_name\":\"Madhya Pradesh\",\"IsActive\":\"True\"},{\"state_id\":\"2\",\"state_name\":\"Gujrat\",\"IsActive\":\"True\"},{\"state_id\":\"3\",\"state_name\":\"Goa\",\"IsActive\":\"True\"},{\"state_id\":\"4\",\"state_name\":\"Maharashtra\",\"IsActive\":\"True\"}]"
}

but the desired result;

[{"state_id":"1","state_name":"Madhya Pradesh","IsActive":"True"},{"state_id":"2","state_name":"Gujrat","IsActive":"True"},{"state_id":"3","state_name":"Goa","IsActive":"True"},{"state_id":"4","state_name":"Maharashtra","IsActive":"True"}]


问:
Should we combine masterdata calls into one call?
WE have a REST Based application with Angular 2 client, In the application we hit some master data api's like country , agreement etc all the time at login some 6-7 calls would it be good (performance aspect) to combine all these calls into one call?</p>

答:
I prefer to do so unless the API endpoints doesn't return some big data. But in the back end I still keep different functions to for each items.

Here is an example. For the dashboard I have to populate 3 dropdown menus (They are the filters). So I combined all 3 calls under a /api/dashboard/filters call. In the backend I do fetch each of these separately but using Promise.all to ensure concurrency. It will look like as bellow

```<code>  try {
    let [businessUnits, departments, filter3] = await Promise.all([
      Employee.getBusinessUnits(),
      EmployeeStatus.getDepartments(),
      Employee.getFilter3()
    ]);

    res.json({ businessUnits, departments, filter3 });
  } catch (e) {
    res.json({ error: e });
  }
</code>```

But if you use http/2, I think it is not necessary to combine these calls

Body:
I prefer to do so unless the API endpoints doesn't return some big data. But in the back end I still keep different functions to for each items.

Here is an example. For the dashboard I have to populate 3 dropdown menus (They are the filters). So I combined all 3 calls under a /api/dashboard/filters call. In the backend I do fetch each of these separately but using Promise.all to ensure concurrency. It will look like as bellow

  try {
    let [businessUnits, departments, filter3] = await Promise.all([
      Employee.getBusinessUnits(),
      EmployeeStatus.getDepartments(),
      Employee.getFilter3()
    ]);

    res.json({ businessUnits, departments, filter3 });
  } catch (e) {
    res.json({ error: e });
  }

But if you use http/2, I think it is not necessary to combine these calls


答: To transform a string to JSON you can use JSON.parse(jsonString); but as already stated, you should send the JSON object itself and not a string.

Title: how to remove \ from json data?


问:
How can I implement a label file for regions that integrates well with MVC application structure?
Background:

I am working on a site that will be available in multiple regions. Each region can have a different language, or different spellings for the same language. We are planning on using an XML label file which will contain all the text that will be displayed for any given region.

So regionA will load RegionALabels.xml and all of its text will come from that. RegionB will load RegionBLabels.xml, and so on.

I'm thinking of implementing this by structuring the XML file so that it follows the same structure as my application. For example,

```<code><Base> <!--BaseController-->
  <Home> <!--HomeController-->
    <HomePartial1>
      <lblFirstName>text for label with ID lblFirstName</lblFirstName>
      <lblLastName>text for label with ID lblLastName</lblLastName>
    </HomePartial1>
    <HomePartial2>
      <!--a bunch of labels-->
    </HomePartial2>
  </Home>
  <Accounts>
    <AccountsPartial1>
      <!--a bunch of labels-->
    </AccountsPartial1>
    <AccountsPartial2>
      <!--a bunch of labels-->
    </AccountsPartial2>
  </Accounts>
</Base>
</code>```

The reason I want to do it this way is because I want to imploy Convention over Configuration, so it becomes implicit where to find the text for any given partial view.

using this structure, I can use Linq-to-XML to select the text relevant to the partial view I'm going to Render. For example, if I'm rendering the partial view HomePartial1, I can get the labels associated with that partial view with something like:

```<code>        var nodes = from f in
                        (from res in this.XmlConfiguration.Descendants("Base")
                         select res).Descendants("Home")
                    select f;

        var HomePartial1Labels = nodes.Elements("HomePartial1").ToList();
</code>```

Question:

So this being the case, basically what I want to ask is if anyone can point out any obvious holes in this approach before I attempt to implement this? Can anyone who has dealt with this before suggest something better?

also, I have one specific requriement to render a partial view with a number of tabs, each of which has to display text & a number of results associated with that tab. For example, I have 3 tabs:

```<code>Fund
Company
Group
</code>```

If somebody does a search, the tabs have to display the number of results the search term returns for the tab, so if I search for 'JP Morgan' they become:

```<code>Fund (10) // 10 funds contain the name 'JP Morgan'
Company (12) // 12 companies contain the name 'JP Morgan'
Group (15) // 15 groups contain the name 'JP Morgan'
</code>```

In order to contain the text "Fund", "Company" and "Group" in the label file, I'm going to have to supply the "(" and ")" also, which means I think I'll have to use a place holder and replace it with the actual value when I'm rendering the partial. So the XML will begin to look like:

```<code><Base> <!--BaseController-->
  <Home> <!--HomeController-->
    <Tabs>
      <lblFundTab>Funds (#value#)</lblFundTab>
      <lblCompanyTab>Company (#value#)</lblCompanyTab>
      <lblGroupTab>Group (#value#)</lblGroupTab>
    </Tabs>
  </Home>
</Base>
</code>```

but I think this is going to start to look messy and a little hackish. Can somebody suggest something better? Thanks.

答:
I have recently had the same thing in a project.

I implemented a LabelService that essesntially wrapped a Singleton array of "LabelFiles" which were loaded into memory on application_start. So my code looks similar but is working on in memory objects and not xml files avoiding a lot of potential IO issues (locks etc).

Your xml label file is fine, assuming it is to be edited by an application or possibly a developer but if it is going to be edited by the client /non-techie how are they to know what "base" is? Or controller? Etc etc - I'm a fan of CoC but sometimes it is better to stick closer to the domain terminology for domain-specific apps.

Body:
Background:

I am working on a site that will be available in multiple regions. Each region can have a different language, or different spellings for the same language. We are planning on using an XML label file which will contain all the text that will be displayed for any given region.

So regionA will load RegionALabels.xml and all of its text will come from that. RegionB will load RegionBLabels.xml, and so on.

I'm thinking of implementing this by structuring the XML file so that it follows the same structure as my application. For example,

<Base>
  <Home>
    <HomePartial1>
      <lblFirstName>text for label with ID lblFirstName</lblFirstName>
      <lblLastName>text for label with ID lblLastName</lblLastName>
    </HomePartial1>
    <HomePartial2>

    </HomePartial2>
  </Home>
  <Accounts>
    <AccountsPartial1>

    </AccountsPartial1>
    <AccountsPartial2>

    </AccountsPartial2>
  </Accounts>
</Base>

The reason I want to do it this way is because I want to imploy Convention over Configuration, so it becomes implicit where to find the text for any given partial view.

using this structure, I can use Linq-to-XML to select the text relevant to the partial view I'm going to Render. For example, if I'm rendering the partial view HomePartial1, I can get the labels associated with that partial view with something like:

        var nodes = from f in
                        (from res in this.XmlConfiguration.Descendants("Base")
                         select res).Descendants("Home")
                    select f;

        var HomePartial1Labels = nodes.Elements("HomePartial1").ToList();

Question:

So this being the case, basically what I want to ask is if anyone can point out any obvious holes in this approach before I attempt to implement this? Can anyone who has dealt with this before suggest something better?

also, I have one specific requriement to render a partial view with a number of tabs, each of which has to display text & a number of results associated with that tab. For example, I have 3 tabs:

Fund
Company
Group

If somebody does a search, the tabs have to display the number of results the search term returns for the tab, so if I search for 'JP Morgan' they become:

Fund (10) // 10 funds contain the name 'JP Morgan'
Company (12) // 12 companies contain the name 'JP Morgan'
Group (15) // 15 groups contain the name 'JP Morgan'

In order to contain the text "Fund", "Company" and "Group" in the label file, I'm going to have to supply the "(" and ")" also, which means I think I'll have to use a place holder and replace it with the actual value when I'm rendering the partial. So the XML will begin to look like:

<Base>
  <Home>
    <Tabs>
      <lblFundTab>Funds (#value#)</lblFundTab>
      <lblCompanyTab>Company (#value#)</lblCompanyTab>
      <lblGroupTab>Group (#value#)</lblGroupTab>
    </Tabs>
  </Home>
</Base>

but I think this is going to start to look messy and a little hackish. Can somebody suggest something better? Thanks.


问:
Outline detection from patterns in a list of textual articles
Are there NLP algorithms dealing with detecting the repeating
patterns in a a list of texts from which a topic keywords
and other associative keywords can be derived?

I will show it as an example:
You have a search query "vegan food for something health"
(where something is a part of body you need an advice about).

The search engine will return a list of articles.

The algorithm will search for patterns in these articles.
E.g. it notices that 80 % of them have a paragraph with
at least 4 multiple instances of a word orange, similarly
carrot, apples, cucumbers.

So it will give you an outline (textual mindmap)

orange

carrot -->
 vitamin A

apple

banana -->
 vitamin B

run a lot

Once I watched a video about semantic web on youtube and know that Tim Berners-Lee talked about something similar, but I have lost the link. Could you
keyword me to that direction again?

答: Probably you are looking for word2vec -- described patterns can be described in terms of distance between words.


问:
Relative path to images in access reports
It is my first time building a database and I wanted to share a solution to a problem I encountered.

My problem was that I wanted to show different images for each record in a report, but I also wanted to be able to move the database. This was a problem. I search in all the forums and all the different solutions didn’t work. I also found an article written by Microsoft saying that the only way is to either store the full path to the images or to store the image in the database. But this causes a problem if the database is moved, or storing the images in the database will take up a lot of storage space.

The problem is that the codes doesn’t work for each record in the report, the codes are for the entire report. So writing codes to find the backend and the image folder would result in displaying the first image in the report for all the records in that report.

However I discovered, when only storing the name of the image in a table, it would sometimes work (but it shouldn’t have, because I didn’t have the path) but when I restarted the database it would stop working. Investigating further I discovered that whenever you open the file browser it will store the path in some kind of memory. As long as the path to the images is stored in the memory it will be able to link the images to the path.

So my solution…

When the form, from where you access the reports is opened, the file browser is opened and the path to the images is pasted in (using codes to find backend and the image folder) and then the browser is closed. And this creates a link to the image names (stored in a table) with the path. And each different images will be shows for each different records in the report.

Not a pretty solution. Whenever the form is opened, you will see a flash of the file browser. But it gets the job done.

In the load form event:

`'    this will find the backend and the image folder:

```<code>Dim filepath As String
Dim strBackEndPath As String
Dim lenPath As Integer
Dim i As Integer
Dim j As Integer

strBackEndPath = CurrentDb.TableDefs("yourTabeInBackend").Connect
j = InStrRev(strBackEndPath, "=") + 1
strBackEndPath = Mid(strBackEndPath, j)
BackPath = Left(strBackEndPath, InStrRev(strBackEndPath, "\"))

filepath = BackPath & "YourImageFolder\"

'this will open the folder browser and paste in the path and close it:

Dim f As Object
Set f = Application.FileDialog(msoFileDialogFolderPicker)
Dim varFile As Variant
Dim strPath As String
Dim fileName As String

With f
.InitialFileName = (filepath)
.AllowMultiSelect = False
SendKeys "{ESC}", True
f.Show

For Each varFile In .SelectedItems
Next varFile
End With
</code>```

`

答:
You can move the pictures to a subfolder of the folder of your database.

Then save the pictures' names like this:

```<code>Picture1.jpg
Picture2.jpg
</code>```

etc.

When you run the application, obtain the path to the pictures:

```<code>PictureFolder = CurrentProject.Path & "\FolderName\"
</code>```

Then the path to a picture will be:

```<code>PictureFolder & Me!PictureFileName.Value
</code>```

When you "move" your database, move both the database file and the folder with the picture files with it.

Body:
It is my first time building a database and I wanted to share a solution to a problem I encountered.

My problem was that I wanted to show different images for each record in a report, but I also wanted to be able to move the database. This was a problem. I search in all the forums and all the different solutions didn’t work. I also found an article written by Microsoft saying that the only way is to either store the full path to the images or to store the image in the database. But this causes a problem if the database is moved, or storing the images in the database will take up a lot of storage space.

The problem is that the codes doesn’t work for each record in the report, the codes are for the entire report. So writing codes to find the backend and the image folder would result in displaying the first image in the report for all the records in that report.

However I discovered, when only storing the name of the image in a table, it would sometimes work (but it shouldn’t have, because I didn’t have the path) but when I restarted the database it would stop working. Investigating further I discovered that whenever you open the file browser it will store the path in some kind of memory. As long as the path to the images is stored in the memory it will be able to link the images to the path.

So my solution…

When the form, from where you access the reports is opened, the file browser is opened and the path to the images is pasted in (using codes to find backend and the image folder) and then the browser is closed. And this creates a link to the image names (stored in a table) with the path. And each different images will be shows for each different records in the report.

Not a pretty solution. Whenever the form is opened, you will see a flash of the file browser. But it gets the job done.

In the load form event:

`'    this will find the backend and the image folder:

Dim filepath As String
Dim strBackEndPath As String
Dim lenPath As Integer
Dim i As Integer
Dim j As Integer

strBackEndPath = CurrentDb.TableDefs("yourTabeInBackend").Connect
j = InStrRev(strBackEndPath, "=") + 1
strBackEndPath = Mid(strBackEndPath, j)
BackPath = Left(strBackEndPath, InStrRev(strBackEndPath, "\"))

filepath = BackPath & "YourImageFolder\"

'this will open the folder browser and paste in the path and close it:

Dim f As Object
Set f = Application.FileDialog(msoFileDialogFolderPicker)
Dim varFile As Variant
Dim strPath As String
Dim fileName As String

With f
.InitialFileName = (filepath)
.AllowMultiSelect = False
SendKeys "{ESC}", True
f.Show

For Each varFile In .SelectedItems
Next varFile
End With

`

Body:
You can move the pictures to a subfolder of the folder of your database.

Then save the pictures' names like this:

Picture1.jpg
Picture2.jpg

etc.

When you run the application, obtain the path to the pictures:

PictureFolder = CurrentProject.Path & "\FolderName\"

Then the path to a picture will be:

PictureFolder & Me!PictureFileName.Value

When you "move" your database, move both the database file and the folder with the picture files with it.


问:
JSP fmt:formatDate increase value of Date
I was creating a .tagx file such that it would render a selection of days (within 30-days period) without passing the collection of java.util.Date.

So far here's what I've done. I can't get the date variable to increase the value of day by one. I've tried to re-set the value of date using <c:set> tag with the formula index * (24 * 24 * 60 * 1000) and it returns javax.el.ELException on that line.

Here's the code I've done so far.

```<code><code>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:fmt="http://java.sun.com/jstl/fmt_rt"
xmlns:spring="http://www.springframework.org/tags"
xmlns:form="http://www.springframework.org/tags/form"
version="2.0">
<jsp:output omit-xml-declaration="yes" />
<jsp:useBean id="date" class="java.util.Date" />

<jsp:directive.attribute name="path" type="String" required="true" rtexprvalue="true" description="The name and id of select tag" />
<jsp:directive.attribute name="classVal" type="String" required="true" rtexprvalue="true" description="The class style to be used by this select" />
<jsp:directive.attribute name="noOfDays" type="Integer" required="true" rtexprvalue="true" description="Number of days to be printed on the selection" />

<select id="${path }" name="${path }" class="${classVal }">
    <option value=""></option>
    <c:forEach var="index" begin="1" end="${noOfDays }">
        <fmt:formatDate value="${date }" pattern="yyyy/MM/dd" var="dateKey" />
        <fmt:formatDate value="${date }" pattern="MM/dd (EEE)" var="dateValue" />
        <option value="${dateKey }">${dateValue }</option>
    </c:forEach>
</select>

</jsp:root>
</code>
</code>```

答:
I ran into the same problem when I used fmt:formatDate with
 Expression Language (EL) like this

```<code><fmt:formatDate pattern="yyyy" value="${coverDate}" var="year" />
</code>```

and the error was something tike this

```<code> EL expression '${coverDate}' is only allowed for attributes with rtexprvalue='true'.
</code>```

the whole problem was just because of a wrong import

```<code><%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
</code>```

and the correct import should be

```<code><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
</code>```

hope this saves your time

Body:
I was creating a .tagx file such that it would render a selection of days (within 30-days period) without passing the collection of java.util.Date.

So far here's what I've done. I can't get the date variable to increase the value of day by one. I've tried to re-set the value of date using <c:set> tag with the formula index * (24 * 24 * 60 * 1000) and it returns javax.el.ELException on that line.

Here's the code I've done so far.

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:fmt="http://java.sun.com/jstl/fmt_rt"
xmlns:spring="http://www.springframework.org/tags"
xmlns:form="http://www.springframework.org/tags/form"
version="2.0">
<jsp:output omit-xml-declaration="yes" />
<jsp:useBean id="date" class="java.util.Date" />

<jsp:directive.attribute name="path" type="String" required="true" rtexprvalue="true" description="The name and id of select tag" />
<jsp:directive.attribute name="classVal" type="String" required="true" rtexprvalue="true" description="The class style to be used by this select" />
<jsp:directive.attribute name="noOfDays" type="Integer" required="true" rtexprvalue="true" description="Number of days to be printed on the selection" />

<select id="${path }" name="${path }" class="${classVal }">
    <option value=""></option>
    <c:forEach var="index" begin="1" end="${noOfDays }">
        <fmt:formatDate value="${date }" pattern="yyyy/MM/dd" var="dateKey" />
        <fmt:formatDate value="${date }" pattern="MM/dd (EEE)" var="dateValue" />
        <option value="${dateKey }">${dateValue }</option>
    </c:forEach>
</select>

</jsp:root>

Body:
I ran into the same problem when I used fmt:formatDate with
 Expression Language (EL) like this

<fmt:formatDate pattern="yyyy" value="${coverDate}" var="year" />

and the error was something tike this

 EL expression '${coverDate}' is only allowed for attributes with rtexprvalue='true'.

the whole problem was just because of a wrong import

<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>

and the correct import should be

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

hope this saves your time