问:
Spontaneous up spring boot context in test
I have an issue with spring-boot-test during deep dive in spring TestContext configuration.

Example project: github example project

I have three Spring configurations with some beans (Config1 - heavyweight config, and I need to cache it)

I use @ContextHierarchy for separate configs in the context, and I expect that Config1 will be loaded only once. (Used @ContextHierarchy because I did not find an analogue in spring-boot-test)

Full code:

```<code>@ContextHierarchy({
    @ContextConfiguration(classes = {Config1.class}),
    @ContextConfiguration(classes = {Config2.class}),
})
</code>```

If I run the test, the Config1 was really cached! However, I see the following:

```<code>Started ConfigTest1
</code>```

Two times
And

```<code>Started ConfigTest2
</code>```

Only once. In my opinion, it is possible because ConfigTest1 already cached as TestContext (it happens, because ConfigTest1 and ConfigTest2 contained in the same package)

That means spring boot up my spring context three times! Why?
See spring boot logo three times in log:

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.2.RELEASE)
</code>```

What do you mean about this behaviour? Is it a bug or a feature? Maybe I do something wrong?

Update1:

Thanks a lot. However, if i set properties (or classes) in @SpringBootTest in different order in two test classes – no configuration will be cached :(

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@ContextHierarchy({
    @ContextConfiguration(classes = {Config1.class}),
    @ContextConfiguration(classes = {Config2.class}),
})
public class ConfigTest1 {
</code>```

and

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(properties = "property1=1")
@ContextHierarchy({
    @ContextConfiguration(classes = {Config1.class}),
    @ContextConfiguration(classes = {Config3.class}),
})
public class ConfigTest2 {
</code>```

In case there is no properties – config1 really will be cached! And in this case – nothing cached

答:
Everything is working as it should!

You're just confused because of the fact that Spring Boot logs the name of the test class for which the ApplicationContext was loaded. Thus, you see ConfigTest1 twice in the log, because two contexts are loaded for that test class.

If you add logging.level.org.springframework.test.context.cache=debug to application.properties, you'll see the following log output.

```<code>DEBUG ... c.DefaultCacheAwareContextLoaderDelegate : Storing ApplicationContext in cache under key [[WebMergedContextConfiguration@7a765367 testClass = ConfigTest1, locations = '{}', classes = '{class spring.test.mistake.delete.Config1}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@643b1d11, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6d00a15d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@475530b9], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]
DEBUG ... c.DefaultCacheAwareContextLoaderDelegate : Storing ApplicationContext in cache under key [[WebMergedContextConfiguration@52feb982 testClass = ConfigTest1, locations = '{}', classes = '{class spring.test.mistake.delete.Config2}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@643b1d11, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6d00a15d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@475530b9], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [WebMergedContextConfiguration@7a765367 testClass = ConfigTest1, locations = '{}', classes = '{class spring.test.mistake.delete.Config1}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@643b1d11, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6d00a15d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@475530b9], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]]
DEBUG ... c.DefaultCacheAwareContextLoaderDelegate : Storing ApplicationContext in cache under key [[WebMergedContextConfiguration@5ddcc487 testClass = ConfigTest2, locations = '{}', classes = '{class spring.test.mistake.delete.Config3}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@643b1d11, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6d00a15d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@475530b9], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [WebMergedContextConfiguration@44c73c26 testClass = ConfigTest2, locations = '{}', classes = '{class spring.test.mistake.delete.Config1}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@643b1d11, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6d00a15d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@475530b9], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]]
DEBUG ... org.springframework.test.context.cache   : Spring test ApplicationContext cache statistics: [DefaultContextCache@478db956 size = 3, maxSize = 32, parentContextCount = 1, hitCount = 11, missCount = 3]
</code>```

Thus, there are in fact only three contexts loaded, namely the three you expect.

Body:
I have an issue with spring-boot-test during deep dive in spring TestContext configuration.

Example project: github example project

I have three Spring configurations with some beans (Config1 - heavyweight config, and I need to cache it)

I use @ContextHierarchy for separate configs in the context, and I expect that Config1 will be loaded only once. (Used @ContextHierarchy because I did not find an analogue in spring-boot-test)

Full code:

@ContextHierarchy({
    @ContextConfiguration(classes = {Config1.class}),
    @ContextConfiguration(classes = {Config2.class}),
})

If I run the test, the Config1 was really cached! However, I see the following:

Started ConfigTest1

Two times
And

Started ConfigTest2

Only once. In my opinion, it is possible because ConfigTest1 already cached as TestContext (it happens, because ConfigTest1 and ConfigTest2 contained in the same package)

That means spring boot up my spring context three times! Why?
See spring boot logo three times in log:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.2.RELEASE)

What do you mean about this behaviour? Is it a bug or a feature? Maybe I do something wrong?

Update1:

Thanks a lot. However, if i set properties (or classes) in @SpringBootTest in different order in two test classes – no configuration will be cached :(

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextHierarchy({
    @ContextConfiguration(classes = {Config1.class}),
    @ContextConfiguration(classes = {Config2.class}),
})
public class ConfigTest1 {

and

@RunWith(SpringRunner.class)
@SpringBootTest(properties = "property1=1")
@ContextHierarchy({
    @ContextConfiguration(classes = {Config1.class}),
    @ContextConfiguration(classes = {Config3.class}),
})
public class ConfigTest2 {

In case there is no properties – config1 really will be cached! And in this case – nothing cached

Body:
Everything is working as it should!

You're just confused because of the fact that Spring Boot logs the name of the test class for which the ApplicationContext was loaded. Thus, you see ConfigTest1 twice in the log, because two contexts are loaded for that test class.

If you add logging.level.org.springframework.test.context.cache=debug to application.properties, you'll see the following log output.

DEBUG ... c.DefaultCacheAwareContextLoaderDelegate : Storing ApplicationContext in cache under key [[WebMergedContextConfiguration@7a765367 testClass = ConfigTest1, locations = '{}', classes = '{class spring.test.mistake.delete.Config1}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@643b1d11, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6d00a15d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@475530b9], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]
DEBUG ... c.DefaultCacheAwareContextLoaderDelegate : Storing ApplicationContext in cache under key [[WebMergedContextConfiguration@52feb982 testClass = ConfigTest1, locations = '{}', classes = '{class spring.test.mistake.delete.Config2}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@643b1d11, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6d00a15d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@475530b9], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [WebMergedContextConfiguration@7a765367 testClass = ConfigTest1, locations = '{}', classes = '{class spring.test.mistake.delete.Config1}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@643b1d11, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6d00a15d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@475530b9], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]]
DEBUG ... c.DefaultCacheAwareContextLoaderDelegate : Storing ApplicationContext in cache under key [[WebMergedContextConfiguration@5ddcc487 testClass = ConfigTest2, locations = '{}', classes = '{class spring.test.mistake.delete.Config3}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@643b1d11, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6d00a15d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@475530b9], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [WebMergedContextConfiguration@44c73c26 testClass = ConfigTest2, locations = '{}', classes = '{class spring.test.mistake.delete.Config1}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@643b1d11, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6d00a15d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@475530b9], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]]
DEBUG ... org.springframework.test.context.cache   : Spring test ApplicationContext cache statistics: [DefaultContextCache@478db956 size = 3, maxSize = 32, parentContextCount = 1, hitCount = 11, missCount = 3]

Thus, there are in fact only three contexts loaded, namely the three you expect.


来源: stackexchange

问:
Efficient way of parsing Jax-ws Restful Response
I need to parse the jax-ws rest response and I tried the following two ways of parsing the response.Both works good.But I am in need to know the best efficient way of implementation.Please provide me your view.

First Approach:

Use getEntity Object and get the response as Input Stream.

Using Jackson ObjectMapper readValue() -covert the inputstream to java
object.

Using getters and setters of nested java class get the response objects member values.

Second Approach:

Use getEntity Object and get the response as Input Stream and and
convert the Input Stream to String.

Using Google Json API,convert the string to json object.

Using Json parser and get the nested objects member values.

答:
Maybe not a general answer to this question but another variant of what you're describing under "First approach". I would start with a generic data structure and would only introduce an extra bean if necessary. I wouldn't use String to pass structured data around.

Use jackson to convert the JSON response to a
  Map<String,Object> or JsonNode.

Advantage:

You don't need to implement a specialized bean class. Even a very simple bean can become unhandy over time (if format changes or new nested structures are added to the json response, etc.). It also introduces some kind of metaphor to your code which sometimes helps but also can be misleading.

Map<String,Object> is in the JDK and offers a good interface to access data. You don't have to change any interfaces even if the JSON format changes.
You can always pass your data in form of a Map<String,Object>

Disadvantage

Data Encapsulation. The map is a very close representation of the input data and therefore offers not same level of abstraction like a bean.

ContentLicense: CC BY-SA 3.0


问:
Assingning Refrences in Java
```<code>class A{}
class B extends A{}
class C extends A{}

public class Test {
     public static void main(String [] args){
    A a = new A();
    A b = new B();
    A c = new C();

    a = b;
    b = c;
    }
}
</code>```

Here how can we assign child reference to parent one ? and also b and c are different object types then how we can assign one to another ?

答:
how can we assign child reference to parent one?

In object-oriented concepts, when you say class B extends A then class B maintains IS-A relationship with class A. So you can assign the B object to the reference as type A.

b and c are different object types then how we can assign one to
  another?

Even though they are different types, because class B IA-A type of class A and class C (also) IS-A type of class A (in terms of their relationship), so you can assign both B & C objects to reference type A.

But one important point is that you can't call any of the B's specific members (methods/fields) with reference type A pointing to object B i.e., you can ONLY call A's members with reference type A (even though object is of B).

Title: Assingning Refrences in Java

Body:
class A{}
class B extends A{}
class C extends A{}

public class Test {
     public static void main(String [] args){
    A a = new A();
    A b = new B();
    A c = new C();

    a = b;
    b = c;
    }
}

Here how can we assign child reference to parent one ? and also b and c are different object types then how we can assign one to another ?


问:
Semantic UI : how to place an button at the bottom of a column?
This is a very simple question, but after some research, I can't find a way to do it properly: I have a grid with 3 columns in Semantic UI and the content of each column has a specific height. I try to add a button at the bottom of each column, but "bottom aligned" doesn't work.
Someone has a clue ?
Here is an example:

```<code><div class="ui basic segment">
  <div class="ui divided grid container">
    <div class="three column row">
      <div class="column">
        Hello <br>
        fdsfsd <br>
        fsfsd <br>
        fdsfsd <br>
        fsfsd <br>
        fsfsd <br>
        fdsfsd <br>
        fsfsd <br>
        fs
      </div>
      <div class="column">
        <div class="segments">
          <div class="ui segment">Hello</div>
          <div class="ui bottom aligned segment">
            fdsfsdf
          </div>
        </div>
      </div>
      <div class="column">
        Hello
      </div>
    </div>
  </div>
</div>
</code>```

Thanks for your help !

答:
One way to go about it is to use a flexbox inside the column to position the content and the .ui.segment div

JS Fiddle: https://jsfiddle.net/batrasoe/vq84trys/4/

```<code><div class="ui  segment">
  <div class="ui divided grid container">
    <div class="three column stretched row">
      <div class="column">
        <div class="segment-wrapper">
          <div class="content">

          </div>
          <div class="ui bottom segment">
          </div>
        </div>
      </div>
      <div class="column">
        <div class="segment-wrapper">
          <div class="content">

          </div>
          <div class="ui bottom segment">
          </div>
        </div>
      </div>

      <div class="column">
        <div class="segment-wrapper">
          <div class="content">

          </div>
          <div class="ui bottom segment">
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

And CSS:

```<code>    .segment-wrapper {
  background-color: #DDD;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  background-color: skyblue;
}

.ui.bottom.segment {
  margin-top: 0;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
</code>```

Body:
This is a very simple question, but after some research, I can't find a way to do it properly: I have a grid with 3 columns in Semantic UI and the content of each column has a specific height. I try to add a button at the bottom of each column, but "bottom aligned" doesn't work.
Someone has a clue ?
Here is an example:

        Hello

        fdsfsd

        fsfsd

        fdsfsd

        fsfsd

        fsfsd

        fdsfsd

        fsfsd

        fs

Hello

            fdsfsdf

        Hello

Thanks for your help !

Body:
One way to go about it is to use a flexbox inside the column to position the content and the .ui.segment div

JS Fiddle: https://jsfiddle.net/batrasoe/vq84trys/4/

<div class="ui  segment">
  <div class="ui divided grid container">
    <div class="three column stretched row">
      <div class="column">
        <div class="segment-wrapper">
          <div class="content">

          </div>
          <div class="ui bottom segment">
          </div>
        </div>
      </div>
      <div class="column">
        <div class="segment-wrapper">
          <div class="content">

          </div>
          <div class="ui bottom segment">
          </div>
        </div>
      </div>

      <div class="column">
        <div class="segment-wrapper">
          <div class="content">

          </div>
          <div class="ui bottom segment">
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

And CSS:

    .segment-wrapper {
  background-color: #DDD;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  background-color: skyblue;
}

.ui.bottom.segment {
  margin-top: 0;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}


问:
Django - Update one field after form submitting
I'm looking for update my Django form after user submission.
I filled my BirthCertificateForm with some data and I just have one field which is not filled : social_number.

Why ? Because after submitting form, I created a unique social number from data form. So, I would like to update my previous form and add this social number according to the good field and validate it.

My models.py file looks like :

```<code>class BirthCertificate(models.Model):

    lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    birthday = models.DateField(null=False, verbose_name='Date de naissance')
    birthhour = models.TimeField(null=True, verbose_name='Heure de naissance')
    birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    fk_parent1 = models.ForeignKey(Person, related_name='ID_Parent1', verbose_name='ID parent1', null=False)
    fk_parent2 = models.ForeignKey(Person, related_name='ID_Parent2', verbose_name='ID parent2', null=False)
    mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie')
    social_number = models.CharField(max_length=30, null=True, verbose_name='numero social')
    created = models.DateTimeField(auto_now_add=True)
</code>```

And my views.py file have 2 functions :

First function :

```<code># First function which let to fill the form with some conditions / restrictions

@login_required
def BirthCertificate_Form(request) :
    # Fonction permettant de créer le formulaire Acte de Naissance et le remplissage

    query_lastname_father = request.GET.get('lastname_father')
    query_lastname_mother = request.GET.get('lastname_mother')

    if request.method == 'POST':

        form = BirthCertificateForm(request.POST or None)

        if form.is_valid() :   # Vérification sur la validité des données
            post = form.save()
            return HttpResponseRedirect(reverse('BC_treated', kwargs={'id': post.id}))

    else:
        form = BirthCertificateForm()

        parent1 = Person.objects.filter(lastname=query_lastname_father)
        parent2 = Person.objects.filter(lastname=query_lastname_mother)

        form = BirthCertificateForm(request.POST or None)
        form.fields['fk_parent1'].queryset = parent1.filter(sex="Masculin")
        form.fields['fk_parent2'].queryset = parent2.filter(sex="Feminin")

    context = {
        "form" : form,
        "query_lastname" : query_lastname_father,
        "query_lastname_mother" : query_lastname_mother,
    }

    return render(request, 'BC_form.html', context)
</code>```

Second function :

```<code># Second function which resume the previous form and create my social number

@login_required
def BirthCertificate_Resume(request, id) :

    birthcertificate = get_object_or_404(BirthCertificate, pk=id)

    #Homme = 1 / Femme = 2
    sex_number = []
    if birthcertificate.sex == 'Masculin' :
        sex_number = 1
        print sex_number
    else :
        sex_number = 2
        print sex_number

    #Récupère année de naissance
    birthyear_temp = str(birthcertificate.birthday.year)
    birthyear_temp2 = str(birthyear_temp.split(" "))
    birthyear = birthyear_temp2[4] + birthyear_temp2[5]

    #Récupère mois de naissance
    birthmonth_temp = birthcertificate.birthday.month
    if len(str(birthmonth_temp)) == 1 :
        birthmonth = '0' + str(birthmonth_temp)
    else :
        birthmonth = birthmonth_temp

    #Récupère N° Mairie (ici récupère nom mais sera changé en n°)
    birth_mairie = birthcertificate.mairie
    print birth_mairie

    #Génère un nombre aléaloire :
    key_temp = randint(0,999)
    if len(str(key_temp)) == 1 :
        key = '00' + str(key_temp)
    elif len(str(key_temp)) ==2 :
        key = 'O' + str(key_temp)
    else :
        key = key_temp
    print key

    social_number = str(sex_number) + ' ' + str(birthyear) + ' ' + str(birthmonth) + ' ' + str(birth_mairie) + ' - ' + str(key)
    print social_number

    return render(request, 'BC_resume.html', {"birthcertificate" : birthcertificate})
</code>```

My question is : How I can take again my form and modify it in order to fill thesocial_number field just created ?

Thank you !

答:
I found a solution which works in order to update my models.

I had this function :

```<code>@login_required
def BirthCertificate_Resume(request, id) :

    birthcertificate = get_object_or_404(BirthCertificate, pk=id)

    #Homme = 1 / Femme = 2
    sex_number = []
    if birthcertificate.sex == 'Masculin' :
        sex_number = 1
        print sex_number
    else :
        sex_number = 2
        print sex_number

    #Récupère année de naissance
    birthyear_temp = str(birthcertificate.birthday.year)
    birthyear_temp2 = str(birthyear_temp.split(" "))
    birthyear = birthyear_temp2[4] + birthyear_temp2[5]

    #Récupère mois de naissance
    birthmonth_temp = birthcertificate.birthday.month
    if len(str(birthmonth_temp)) == 1 :
        birthmonth = '0' + str(birthmonth_temp)
    else :
        birthmonth = birthmonth_temp

    # #Récupère première lettre nom
    # lastname_temp = birthcertificate.lastname
    # lastname = lastname_temp[0]
    # print lastname

    # #Récupère première lettre prénom
    # firstname_temp = birthcertificate.firstname
    # firstname = firstname_temp[0]
    # print firstname

    #Récupère N° Mairie (ici récupère nom mais sera changé en n°)
    birth_mairie = birthcertificate.mairie
    print birth_mairie

    #Génère un nombre aléaloire :
    key_temp = randint(0,999999)
    if len(str(key_temp)) == 1 :
        key = '00000' + str(key_temp)
    elif len(str(key_temp)) == 2 :
        key = '0000' + str(key_temp)
    elif len(str(key_temp)) == 3 :
        key = '000' + str(key_temp)
    elif len(str(key_temp)) == 4 :
        key = '00' + str(key_temp)
    elif len(str(key_temp)) == 5 :
        key = '0' + str(key_temp)
    else :
        key = key_temp
    print key

    social_number = str(sex_number) + ' ' + str(birthyear) + ' ' + str(birthmonth) + ' ' + str(birth_mairie) + ' - ' + str(key)
    print social_number

    return render(request, 'BC_resume.html', {"birthcertificate" : birthcertificate, "social_number" : social_number})
</code>```

So I just add two lines and it seems to work pretty well :

```<code>birthcertificate.social_number = social_number
birthcertificate.save()
</code>```

What do you think about this method ?

Body:
I'm looking for update my Django form after user submission.
I filled my BirthCertificateForm with some data and I just have one field which is not filled : social_number.

Why ? Because after submitting form, I created a unique social number from data form. So, I would like to update my previous form and add this social number according to the good field and validate it.

My models.py file looks like :

class BirthCertificate(models.Model):

    lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    birthday = models.DateField(null=False, verbose_name='Date de naissance')
    birthhour = models.TimeField(null=True, verbose_name='Heure de naissance')
    birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    fk_parent1 = models.ForeignKey(Person, related_name='ID_Parent1', verbose_name='ID parent1', null=False)
    fk_parent2 = models.ForeignKey(Person, related_name='ID_Parent2', verbose_name='ID parent2', null=False)
    mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie')
    social_number = models.CharField(max_length=30, null=True, verbose_name='numero social')
    created = models.DateTimeField(auto_now_add=True)

And my views.py file have 2 functions :

First function :

# First function which let to fill the form with some conditions / restrictions

@login_required
def BirthCertificate_Form(request) :
    # Fonction permettant de créer le formulaire Acte de Naissance et le remplissage

    query_lastname_father = request.GET.get('lastname_father')
    query_lastname_mother = request.GET.get('lastname_mother')

    if request.method == 'POST':

        form = BirthCertificateForm(request.POST or None)

        if form.is_valid() :   # Vérification sur la validité des données
            post = form.save()
            return HttpResponseRedirect(reverse('BC_treated', kwargs={'id': post.id}))

    else:
        form = BirthCertificateForm()

        parent1 = Person.objects.filter(lastname=query_lastname_father)
        parent2 = Person.objects.filter(lastname=query_lastname_mother)

        form = BirthCertificateForm(request.POST or None)
        form.fields['fk_parent1'].queryset = parent1.filter(sex="Masculin")
        form.fields['fk_parent2'].queryset = parent2.filter(sex="Feminin")

    context = {
        "form" : form,
        "query_lastname" : query_lastname_father,
        "query_lastname_mother" : query_lastname_mother,
    }

    return render(request, 'BC_form.html', context)

Second function :

# Second function which resume the previous form and create my social number

@login_required
def BirthCertificate_Resume(request, id) :

    birthcertificate = get_object_or_404(BirthCertificate, pk=id)

    #Homme = 1 / Femme = 2
    sex_number = []
    if birthcertificate.sex == 'Masculin' :
        sex_number = 1
        print sex_number
    else :
        sex_number = 2
        print sex_number

    #Récupère année de naissance
    birthyear_temp = str(birthcertificate.birthday.year)
    birthyear_temp2 = str(birthyear_temp.split(" "))
    birthyear = birthyear_temp2[4] + birthyear_temp2[5]

    #Récupère mois de naissance
    birthmonth_temp = birthcertificate.birthday.month
    if len(str(birthmonth_temp)) == 1 :
        birthmonth = '0' + str(birthmonth_temp)
    else :
        birthmonth = birthmonth_temp

    #Récupère N° Mairie (ici récupère nom mais sera changé en n°)
    birth_mairie = birthcertificate.mairie
    print birth_mairie

    #Génère un nombre aléaloire :
    key_temp = randint(0,999)
    if len(str(key_temp)) == 1 :
        key = '00' + str(key_temp)
    elif len(str(key_temp)) ==2 :
        key = 'O' + str(key_temp)
    else :
        key = key_temp
    print key

    social_number = str(sex_number) + ' ' + str(birthyear) + ' ' + str(birthmonth) + ' ' + str(birth_mairie) + ' - ' + str(key)
    print social_number

    return render(request, 'BC_resume.html', {"birthcertificate" : birthcertificate})

My question is : How I can take again my form and modify it in order to fill thesocial_number field just created ?

Thank you !

Body:
I found a solution which works in order to update my models.

I had this function :

@login_required
def BirthCertificate_Resume(request, id) :

    birthcertificate = get_object_or_404(BirthCertificate, pk=id)

    #Homme = 1 / Femme = 2
    sex_number = []
    if birthcertificate.sex == 'Masculin' :
        sex_number = 1
        print sex_number
    else :
        sex_number = 2
        print sex_number

    #Récupère année de naissance
    birthyear_temp = str(birthcertificate.birthday.year)
    birthyear_temp2 = str(birthyear_temp.split(" "))
    birthyear = birthyear_temp2[4] + birthyear_temp2[5]

    #Récupère mois de naissance
    birthmonth_temp = birthcertificate.birthday.month
    if len(str(birthmonth_temp)) == 1 :
        birthmonth = '0' + str(birthmonth_temp)
    else :
        birthmonth = birthmonth_temp

    # #Récupère première lettre nom
    # lastname_temp = birthcertificate.lastname
    # lastname = lastname_temp[0]
    # print lastname

    # #Récupère première lettre prénom
    # firstname_temp = birthcertificate.firstname
    # firstname = firstname_temp[0]
    # print firstname

    #Récupère N° Mairie (ici récupère nom mais sera changé en n°)
    birth_mairie = birthcertificate.mairie
    print birth_mairie

    #Génère un nombre aléaloire :
    key_temp = randint(0,999999)
    if len(str(key_temp)) == 1 :
        key = '00000' + str(key_temp)
    elif len(str(key_temp)) == 2 :
        key = '0000' + str(key_temp)
    elif len(str(key_temp)) == 3 :
        key = '000' + str(key_temp)
    elif len(str(key_temp)) == 4 :
        key = '00' + str(key_temp)
    elif len(str(key_temp)) == 5 :
        key = '0' + str(key_temp)
    else :
        key = key_temp
    print key

    social_number = str(sex_number) + ' ' + str(birthyear) + ' ' + str(birthmonth) + ' ' + str(birth_mairie) + ' - ' + str(key)
    print social_number

    return render(request, 'BC_resume.html', {"birthcertificate" : birthcertificate, "social_number" : social_number})

So I just add two lines and it seems to work pretty well :

birthcertificate.social_number = social_number
birthcertificate.save()

What do you think about this method ?


问:
Calling a linked server fails after a snapshot connection has been disposed
We have a C# application using ADO.NET and an SQL-Server with SNAPSHOT Transaction Isolation Level. This is 'as is' and unfortunately cannot be modified.

Now we need insert stuff on a linked server.

We execute the following code (reduced to illustrate the problem):

```<code>// Create a snapshot Transaction and close the connection
using (var con = new SqlConnection(myConStr))
{
   con.BeginTransaction(TransactionLevel.Snapshot);
}

// do something with a linked server
using (var con = new SqlConnection(myConStr))
{
  using (var cmd = con.CreateCommand()
  {
    cmd.CommandText = "insert into LinkedServer.SomeDb..Table ...";
    cmd.ExecuteNonQuery();
  }
}
</code>```

We get can an exception when trying to insert something into the linked server

'Remote access is not supported for transaction isolation level "SNAPSHOT"'

I wonder why it is not possible: We open the connection, make sure it is disposed (clearing all transactions, I guess) and use a second connection for the linked server call.

Executing the stuff in SSMS using plain SQL seems to work.

What are we missing? Is there a proper way to do it?

Thanks for any hints in the right direction.

答:
The secret to understand the problem is the 'connection pooling' which is done by ADO.NET in the Background. The real connection is actually set to SNAPSHOT.

In the second part of the sample code, that connection simply gets reused thus still being in 'snapshot mode'.

The solution is to explicitly set the transaction isolation Level to something else right after opening the Connection.

```<code>using (var con = new SqlConnection(myConStr))
{
  using (var cmd = con.CreateCommand()
  {
     cmd.CommandText = "set transaction isolation Level read committed";
     cmd.ExecuteNonQuery();
  }

  using (var cmd = con.CreateCommand()
  {
     cmd.CommandText = "insert into LinkedServer.SomeDb..Table ...";
     cmd.ExecuteNonQuery();
  }
}
</code>```

Body:
We have a C# application using ADO.NET and an SQL-Server with SNAPSHOT Transaction Isolation Level. This is 'as is' and unfortunately cannot be modified.

Now we need insert stuff on a linked server.

We execute the following code (reduced to illustrate the problem):

// Create a snapshot Transaction and close the connection
using (var con = new SqlConnection(myConStr))
{
   con.BeginTransaction(TransactionLevel.Snapshot);
}

// do something with a linked server
using (var con = new SqlConnection(myConStr))
{
  using (var cmd = con.CreateCommand()
  {
    cmd.CommandText = "insert into LinkedServer.SomeDb..Table ...";
    cmd.ExecuteNonQuery();
  }
}

We get can an exception when trying to insert something into the linked server

'Remote access is not supported for transaction isolation level "SNAPSHOT"'

I wonder why it is not possible: We open the connection, make sure it is disposed (clearing all transactions, I guess) and use a second connection for the linked server call.

Executing the stuff in SSMS using plain SQL seems to work.

What are we missing? Is there a proper way to do it?

Thanks for any hints in the right direction.

Body:
The secret to understand the problem is the 'connection pooling' which is done by ADO.NET in the Background. The real connection is actually set to SNAPSHOT.

In the second part of the sample code, that connection simply gets reused thus still being in 'snapshot mode'.

The solution is to explicitly set the transaction isolation Level to something else right after opening the Connection.

using (var con = new SqlConnection(myConStr))
{
  using (var cmd = con.CreateCommand()
  {
     cmd.CommandText = "set transaction isolation Level read committed";
     cmd.ExecuteNonQuery();
  }

  using (var cmd = con.CreateCommand()
  {
     cmd.CommandText = "insert into LinkedServer.SomeDb..Table ...";
     cmd.ExecuteNonQuery();
  }
}


问:
EXPORT FAILED error using xcodebuild command line tool
I'm trying to export an ipa file through xcodebuild but I always receive this error.

IDEDistribution: Step failed: : Error Domain=IDEDistributionErrorDomain Code=14 "No
  applicable devices found." UserInfo={NSLocalizedDescription=No
  applicable devices found.} error: exportArchive: No applicable devices
  found.

Error Domain=IDEDistributionErrorDomain Code=14 "No applicable devices
  found." UserInfo={NSLocalizedDescription=No applicable devices found.}

** EXPORT FAILED **

Any hint?

This is the shell script I'm using (run in terminal through sh export_script.sh)

```<code>xcodebuild clean -project 'MyProject.xcodeproj' -configuration Debug -scheme MyProject -alltargets
xcodebuild -project 'MyProject.xcodeproj' -scheme MyProject archive -archivePath 'MyProject.xcarchive'
xcodebuild -exportArchive -archivePath 'MyProject.xcarchive' -exportPath 'Export' -exportOptionsPlist 'Options.plist'
</code>```

P.S. Point me out any error in my scripts, if present.

答:
In my case the issue was related to using RVM. Switching to the system Ruby solved the issue:

```<code>rvm use system
</code>```

Seams like some parts of xcodebuild are relying on the system version of Ruby and don't play nice with RVM.

Body:
I'm trying to export an ipa file through xcodebuild but I always receive this error.

IDEDistribution: Step failed: : Error Domain=IDEDistributionErrorDomain Code=14 "No
  applicable devices found." UserInfo={NSLocalizedDescription=No
  applicable devices found.} error: exportArchive: No applicable devices
  found.

Error Domain=IDEDistributionErrorDomain Code=14 "No applicable devices
  found." UserInfo={NSLocalizedDescription=No applicable devices found.}

** EXPORT FAILED **

Any hint?

This is the shell script I'm using (run in terminal through sh export_script.sh)

xcodebuild clean -project 'MyProject.xcodeproj' -configuration Debug -scheme MyProject -alltargets
xcodebuild -project 'MyProject.xcodeproj' -scheme MyProject archive -archivePath 'MyProject.xcarchive'
xcodebuild -exportArchive -archivePath 'MyProject.xcarchive' -exportPath 'Export' -exportOptionsPlist 'Options.plist'

P.S. Point me out any error in my scripts, if present.

Body:
In my case the issue was related to using RVM. Switching to the system Ruby solved the issue:

rvm use system

Seams like some parts of xcodebuild are relying on the system version of Ruby and don't play nice with RVM.


问:
Using getSimpleName() vs getName() for acquiring logger
I've seen code that uses log4j, which acquires logger for a given Logger using

```<code>static public Logger getLogger(String name)
</code>```

and

```<code>static public Logger getLogger(Class clazz)
</code>```

with the former api passed explicitly with getSimpleName(), while the latter uses getName() on the passed Class. Is there a difference between these two? Would it affect if I configure various packages to log at different level in log4j.properties file?

答:
Yes there is a huge difference.

I never use simpleName for Logger instance as it strips down the package name.
Apart from having problems when same class name exists in two different packages (leading to both classes getting the same logger instance), you lose the ability to control logger inheritance.

e.g. for two loggers:

```<code>com.foo.A
com.foo.B
</code>```

in properties, i can just have:

```<code>log4j.logger.com.foo=DEBUG,CONSOLE
</code>```

Body:
I've seen code that uses log4j, which acquires logger for a given Logger using

static public Logger getLogger(String name)

and

static public Logger getLogger(Class clazz)

with the former api passed explicitly with getSimpleName(), while the latter uses getName() on the passed Class. Is there a difference between these two? Would it affect if I configure various packages to log at different level in log4j.properties file?

Body:
Yes there is a huge difference.

I never use simpleName for Logger instance as it strips down the package name.
Apart from having problems when same class name exists in two different packages (leading to both classes getting the same logger instance), you lose the ability to control logger inheritance.

e.g. for two loggers:

com.foo.A
com.foo.B

in properties, i can just have:

log4j.logger.com.foo=DEBUG,CONSOLE

ContentLicense: CC BY-SA 2.5


问:
When to use ContextCompat class
I want to know when to use ContextCompact class in an application. Basically what is it used for and when to use it? I have read developers site, it says ContextCompact is a "helper for accessing features in Context". But what does this line mean?

答:
ContextCompat class is used when you would like to retrieve resources, such as drawable or color without bother about theme. It provide uniform interface to access resources and provides backward compatibility.

Common use case could be get color or drawable etc e.g..

ContextCompat.getDrawable(context, R.drawable.someimage));
  ContextCompat.getDrawable(context, R.color.blue));

Lets see the source code of getColor()

```<code>/*
 * Returns a color associated with a particular resource ID
 * <p>
 * Starting in {@link android.os.Build.VERSION_CODES#M}, the returned
 * color will be styled for the specified Context's theme.
 *
 * @param id The desired resource identifier, as generated by the aapt
 *           tool. This integer encodes the package, type, and resource
 *           entry. The value 0 is an invalid identifier.
 * @return A single color value in the form 0xAARRGGBB.
 * @throws android.content.res.Resources.NotFoundException if the given ID
 *         does not exist.
 */
@ColorInt
public static final int getColor(Context context, @ColorRes int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 23) {
        return ContextCompatApi23.getColor(context, id);
    } else {
        return context.getResources().getColor(id);
    }
}
</code>```

this method takes care the API level resolution and resolve states or theme automatically. Above 23, the color states are accessible, which is internally resolved for you, instead you should check it for each resource.

ContentLicense: CC BY-SA 4.0

Title: When to use ContextCompat class

Body:
ContextCompat class is used when you would like to retrieve resources, such as drawable or color without bother about theme. It provide uniform interface to access resources and provides backward compatibility.

Common use case could be get color or drawable etc e.g..

ContextCompat.getDrawable(context, R.drawable.someimage));
  ContextCompat.getDrawable(context, R.color.blue));

Lets see the source code of getColor()

/*
 * Returns a color associated with a particular resource ID
 * <p>
 * Starting in {@link android.os.Build.VERSION_CODES#M}, the returned
 * color will be styled for the specified Context's theme.
 *
 * @param id The desired resource identifier, as generated by the aapt
 *           tool. This integer encodes the package, type, and resource
 *           entry. The value 0 is an invalid identifier.
 * @return A single color value in the form 0xAARRGGBB.
 * @throws android.content.res.Resources.NotFoundException if the given ID
 *         does not exist.
 */
@ColorInt
public static final int getColor(Context context, @ColorRes int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 23) {
        return ContextCompatApi23.getColor(context, id);
    } else {
        return context.getResources().getColor(id);
    }
}

this method takes care the API level resolution and resolve states or theme automatically. Above 23, the color states are accessible, which is internally resolved for you, instead you should check it for each resource.


问:
How to use global scss files in angular-cli project
I am new to Angular 4 and to the Angular-CLI.
I cannot find any solution how to use root scss/css files for the whole application.
Thereby, my question, how to use global scss files in the project?</p>

答:
Simplest way is to load scss file in the very root component , in this way all the children components will get the styles.

And if there are many files , we can import those scss files into the one scss file by using @import "scss-file";

And if children component doesn't want to use that style , then we can also handle that via encapsulation property of component

Another way is to :

stackoverflow.com/a/42865933/1876949


问:
Session management mysql and nodejs
I am using passportjs passport-local for authentication (username and password) in my web application.

Technology/Framework

Node.js

Expressjs

mysql

passportjs

Problem:

Session destroyed when server goes down. I need to implement a mechanism to persist session for logged in user. So that when server is up he can access the application without login process.

Note:

I cannot able to use redis for session management since we often flushall to clear caching data.

Any suggestion will be grateful.

答:
I have implemented express mysql session

```<code>var mysql = require('mysql');
var session = require('express-session')
var mysql_store = require('express-mysql-session')(session),
var db_connection = mysql.createPool({
   canRetry: true,
   database: 'database',
   host: 'host',
   user: 'user',
   password: 'password',
   connectionLimit: 100
});

var sessionStore = new mysql_store({
    expiration: 60 * 2000
}, db_connection);

app.use(session({
    secret: '5151db3f77e7847337000000',
    resave: false,
    saveUninitialized: false,
    store: sessionStore,
    cookie: {
       expires: new Date(Date.now() + 60 * 2000),
       maxAge: 60 * 2000
    }
}));
</code>```

Thanks @robertklep and @Paul

Title: Session management mysql and nodejs

Body:
I have implemented express mysql session

var mysql = require('mysql');
var session = require('express-session')
var mysql_store = require('express-mysql-session')(session),
var db_connection = mysql.createPool({
   canRetry: true,
   database: 'database',
   host: 'host',
   user: 'user',
   password: 'password',
   connectionLimit: 100
});

var sessionStore = new mysql_store({
    expiration: 60 * 2000
}, db_connection);

app.use(session({
    secret: '5151db3f77e7847337000000',
    resave: false,
    saveUninitialized: false,
    store: sessionStore,
    cookie: {
       expires: new Date(Date.now() + 60 * 2000),
       maxAge: 60 * 2000
    }
}));

Thanks @robertklep and @Paul


问:
jQuery dispatch event? How to
how can i dispatch an event on my window ready?
For example in my code i've got:

```<code>$("#info").click(function(){
// do stuff
});
</code>```

I need to call this function the first time without have a click on #info, in the way // do stuff.

答: A better way might be to make a function that does the required stuff, then do $(document).ready(myFunc); and $("#info").click(myFunc);.

Title: jQuery dispatch event? How to

Body:
how can i dispatch an event on my window ready?
For example in my code i've got:

$("#info").click(function(){
// do stuff
});

I need to call this function the first time without have a click on #info, in the way // do stuff.


问:
Custom Log4j2 appender not working with storm
We have created below logger configuration  in worker.xml of storm cluster

```<code>       <!-- This is new appender we want to add -->
    <FDPRollingFile name="RollingFileInfo" filename="${sys:storm.log.dir}/userlogs/info-${sys:logfile.name}"
        filepattern="${sys:storm.log.dir}/userlogs/info-${sys:logfile.name}.%d{yyyy-MM-dd-HH-mm}" append="true">
            <PatternLayout>
             <pattern>${patternFdpNew}</pattern>
           </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB"/> <!-- Or every 100 MB -->
            </Policies>
        </FDPRollingFile>
    <FDPRollingFile name="RollingFileDebug" filename="${sys:storm.log.dir}/userlogs/debug-${sys:logfile.name}"
            filepattern="${sys:storm.log.dir}/userlogs/debug-${sys:logfile.name}.%d{yyyy-MM-dd-HH-mm}" append="true">
          <PatternLayout>
             <pattern>${patternFdpNew}</pattern>
           </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB"/> <!-- Or every 100 MB -->
            </Policies>
    </FDPRollingFile>
    <FDPRollingFile name="RollingFileError" filename="${sys:storm.log.dir}/userlogs/error-${sys:logfile.name}"
            filepattern="${sys:storm.log.dir}/userlogs/error-${sys:logfile.name}.%d{yyyy-MM-dd-HH-mm}" append="true">
        <PatternLayout>
             <pattern>${patternFdpNew}</pattern>
        </PatternLayout>
        <Policies>
            <SizeBasedTriggeringPolicy size="100 MB"/> <!-- Or every 100 MB -->
        </Policies>
    </FDPRollingFile>
<!-- This is new appender we want to add -->
</code>```

and custom logger defined in below fashion

```<code>    <Logger name="custom-logger" additivity="false" level="INFO">
     <appender-ref ref="RollingFileDebug" level="TRACE"/>
     <appender-ref ref="RollingFileError" level="WARN"/>
     <appender-ref ref="RollingFileInfo" level="INFO"/>
   </Logger>
</code>```

In storm topology builder main class

```<code>   config.put("topology.classpath","/usr/local/Cellar/storm/mylogger.jar");
</code>```

and In spout

```<code>     private static org.slf4j.Logger _logger = LoggerFactory.getLogger("custom-    logger");
</code>```

Now what happens it detect my jar  and write one line of log in  log file but post that doesn't log any line to th log file.

答:
The name attribute of the logger element should be your package name, are you sure "custom-logger" is correct?

If you are using slf4j in your code, you must add log4j2 slf4j binding to your classpath, see this for more details.

Hope it helps.

Body:
We have created below logger configuration  in worker.xml of storm cluster

    <FDPRollingFile name="RollingFileInfo" filename="${sys:storm.log.dir}/userlogs/info-${sys:logfile.name}"
        filepattern="${sys:storm.log.dir}/userlogs/info-${sys:logfile.name}.%d{yyyy-MM-dd-HH-mm}" append="true">
            <PatternLayout>
             <pattern>${patternFdpNew}</pattern>
           </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </FDPRollingFile>
    <FDPRollingFile name="RollingFileDebug" filename="${sys:storm.log.dir}/userlogs/debug-${sys:logfile.name}"
            filepattern="${sys:storm.log.dir}/userlogs/debug-${sys:logfile.name}.%d{yyyy-MM-dd-HH-mm}" append="true">
          <PatternLayout>
             <pattern>${patternFdpNew}</pattern>
           </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
    </FDPRollingFile>
    <FDPRollingFile name="RollingFileError" filename="${sys:storm.log.dir}/userlogs/error-${sys:logfile.name}"
            filepattern="${sys:storm.log.dir}/userlogs/error-${sys:logfile.name}.%d{yyyy-MM-dd-HH-mm}" append="true">
        <PatternLayout>
             <pattern>${patternFdpNew}</pattern>
        </PatternLayout>
        <Policies>
            <SizeBasedTriggeringPolicy size="100 MB"/>
        </Policies>
    </FDPRollingFile>

and custom logger defined in below fashion

    <Logger name="custom-logger" additivity="false" level="INFO">
     <appender-ref ref="RollingFileDebug" level="TRACE"/>
     <appender-ref ref="RollingFileError" level="WARN"/>
     <appender-ref ref="RollingFileInfo" level="INFO"/>
   </Logger>

In storm topology builder main class

   config.put("topology.classpath","/usr/local/Cellar/storm/mylogger.jar");

and In spout

     private static org.slf4j.Logger _logger = LoggerFactory.getLogger("custom-    logger");

Now what happens it detect my jar  and write one line of log in  log file but post that doesn't log any line to th log file.


问:
Youtube video upload limit exceeded
I use this cmd application https://github.com/tokland/youtube-upload

After uploading 50 videos i am getting this error:

```<code>[RequestError] Server response: {
 "error": {
  "errors": [
   {
    "domain": "youtube.video",
    "reason": "uploadLimitExceeded",
    "message": "The user has exceeded the number of videos they may upload."
   }
  ],
  "code": 400,
  "message": "The user has exceeded the number of videos they may upload."
 }
}
</code>```

And after this error i can upload 1 video per 15 minutes. But after waiting for aproximatley 2 hours i can upload 50 more videos but it does not work everytime. Sometimes even after waiting for 3 hours i still can't upload 50 videos.

Also i never exceeded my quota limit.
My quota statistic:

Queries per day

Till 20th of march i was getting this error:

```<code>{
 "error": {
  "errors": [
   {
    "domain": "youtube.common",
    "reason": "forbidden",
    "message": "Access forbidden. The request may not be properly authorized."
   }
  ],
  "code": 403,
  "message": "Access forbidden. The request may not be properly authorized."
 }
}
</code>```

Рow did you solve it? How do you upload videos to youtube in large quantities?

答:
badRequest (400)  uploadLimitExceeded The user has exceeded the number of videos they may upload.

This is a user based quota which can not be upgraded.  It means that the user in question has exceed their upload limit for the day.  The YouTube API has a slightly different quota system than other Google APIs. The ones listed in developer console are just the general ones.  You should check calculating quota usage

200,000 read operations that each retrieve two resource parts.

10,000 write operations and 90,000 additional read operations that each retrieve two resource parts.

400 video uploads, 1500 write operations, and 50,000 read operations that each retrieve two resource parts.

This quota should reset at midnight West Coast USA time.

Access forbidden. The request may not be properly authorized.

Means that either your access token or your refresh token is no longer working.  You should either use the access token to get a new refresh token.  Or re authenticate the application and get a new refresh token.  Yes refresh tokens can expire under different circumstances.

Title: Youtube video upload limit exceeded

Body:
I use this cmd application https://github.com/tokland/youtube-upload

After uploading 50 videos i am getting this error:

[RequestError] Server response: {
 "error": {
  "errors": [
   {
    "domain": "youtube.video",
    "reason": "uploadLimitExceeded",
    "message": "The user has exceeded the number of videos they may upload."
   }
  ],
  "code": 400,
  "message": "The user has exceeded the number of videos they may upload."
 }
}

And after this error i can upload 1 video per 15 minutes. But after waiting for aproximatley 2 hours i can upload 50 more videos but it does not work everytime. Sometimes even after waiting for 3 hours i still can't upload 50 videos.

Also i never exceeded my quota limit.
My quota statistic:

Queries per day

Till 20th of march i was getting this error:

{
 "error": {
  "errors": [
   {
    "domain": "youtube.common",
    "reason": "forbidden",
    "message": "Access forbidden. The request may not be properly authorized."
   }
  ],
  "code": 403,
  "message": "Access forbidden. The request may not be properly authorized."
 }
}

Рow did you solve it? How do you upload videos to youtube in large quantities?


问:
how to edit a text file without editing other lines (cmd)
First, I'm in Korea. So my English will very bad.

I want to edit third line with out touching first line and the second line.

Before:

```<code>echo sample
echo sample
echo sample
echo sample
</code>```

After:

```<code>echo sample
echo sample
echo hello
echo sample
</code>```

Just like this.
without using this command:

```<code>echo echo sample> test.txt
echo echo sample> test.txt
echo echo hello> test.txt
echo echo sample> test.txt
</code>```

So, I mean is not write 1,2,4's 'echo' and 'sample' things.
Only the third line's 'echo'.
What can I do?

答:
You can find the answer to your question here:

bash: replace an entire line in a text file

In your case, the command to use is:

```<code>sed -i '3s/.*/echo hello/' test.txt
</code>```

Body:
First, I'm in Korea. So my English will very bad.

I want to edit third line with out touching first line and the second line.

Before:

echo sample
echo sample
echo sample
echo sample

After:

echo sample
echo sample
echo hello
echo sample

Just like this.
without using this command:

echo echo sample> test.txt
echo echo sample> test.txt
echo echo hello> test.txt
echo echo sample> test.txt

So, I mean is not write 1,2,4's 'echo' and 'sample' things.
Only the third line's 'echo'.
What can I do?

Body:
You can find the answer to your question here:

bash: replace an entire line in a text file

In your case, the command to use is:

sed -i '3s/.*/echo hello/' test.txt


问:
Adding comma after MySQL query based on condition (desc or asc)
I am dynamically creating a query for search, based on search I need to append query with des|asc.

For example if the user click bydate I will append order by bydate desc, again if the user wants to search company name I append order by companyname asc. This is done on condition.

For example if the query is

```<code>select * from market
</code>```

and if the user searches by date query becomes

```<code> select * from market order by bydate desc
</code>```

and if the user searcher by companyname query becomes

Now if the previous query contains asc or desc I need to insert comma, so the query becomes

```<code>select * from market order by bydate desc, companyname
</code>```

If I don't check and insert comma query becomes

```<code>select * from market order by bydate desc companyname -- without comma
</code>```

So inserting comma based on condition

```<code> $query = 'select * from market order by bydate desc';

    if(  ($despos = false) && (  ( strripos($query, 'desc') !=== false && ($despos =  strripos($query, 'desc')) ) ||  ( strripos($query, 'asc') !=== false && ($despos =  strripos($query, 'asc'))  )   ) && $despost !===false   && $despos >(strlen($query)-7)  ) $query.=", ";
</code>```

But the query shows the following error:

( ! ) Parse error: syntax error, unexpected '=' in E:\wamp\www\sugumar\php\1.php on line 5

答:
```<code>$query = "select * from market";
$orderBy = array();
</code>```

if the user searches by date

```<code>array_push($orderBy, "bydate desc");
</code>```

if the user searcher by companyname query

```<code>array_push($orderBy, "companyname asc");

if(count($orderBy) > 0) {
   $query = $query." order by ".implode(",", $orderBy);
}
</code>```

Body:
I am dynamically creating a query for search, based on search I need to append query with des|asc.

For example if the user click bydate I will append order by bydate desc, again if the user wants to search company name I append order by companyname asc. This is done on condition.

For example if the query is

select * from market

and if the user searches by date query becomes

 select * from market order by bydate desc

and if the user searcher by companyname query becomes

Now if the previous query contains asc or desc I need to insert comma, so the query becomes

select * from market order by bydate desc, companyname

If I don't check and insert comma query becomes

select * from market order by bydate desc companyname -- without comma

So inserting comma based on condition

 $query = 'select * from market order by bydate desc';

    if(  ($despos = false) && (  ( strripos($query, 'desc') !=== false && ($despos =  strripos($query, 'desc')) ) ||  ( strripos($query, 'asc') !=== false && ($despos =  strripos($query, 'asc'))  )   ) && $despost !===false   && $despos >(strlen($query)-7)  ) $query.=", ";

But the query shows the following error:

( ! ) Parse error: syntax error, unexpected '=' in E:\wamp\www\sugumar\php\1.php on line 5

Body:
$query = "select * from market";
$orderBy = array();

if the user searches by date

array_push($orderBy, "bydate desc");

if the user searcher by companyname query

array_push($orderBy, "companyname asc");

if(count($orderBy) > 0) {
   $query = $query." order by ".implode(",", $orderBy);
}


问:
How to open local PDF file in WebView in Android?
I want to open local (SD card) PDF file in a WebView.

I already tried this:

```<code>webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.getSettings().setAllowFileAccess(true);
File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

final Uri uri = Uri.fromFile(file);

webview.loadUrl(uri.toString());
</code>```

But it's still not opening it, so let me know how I can open a PDF in WebView?

答:
I know, this question is old.

But I really like the approach of Xamarin to make use of the pdf.js from Mozilla. It works on older Android versions, you don't need a special PDF Viewer app for this and you can easily display a PDF inside of your apps views hierarchy.

Git for this:
https://mozilla.github.io/pdf.js/

Additional default options (like standard zoom):
https://github.com/mozilla/pdf.js/wiki/Viewer-options

Just add the pdfjs files to your Assets directory:

And call it the following way:

```<code>// Assuming you got your pdf file:
File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

webview = (WebView) findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setBuiltInZoomControls(true);
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + file.getAbsolutePath() + "#zoom=page-width");
</code>```

Cool thing: If you want to reduce the amount of functionalities / controls. Go to the Assets/pdfjs/web/viewer.html file and mark certain controls as hidden.
With

```<code>style="display: none;"
</code>```

E.g. If you don't like the right toolbar:

```<code><div id="toolbarViewerRight" style="display: none;">...</div>
</code>```

Update

'URL scheme "file" is not supported'

Might occur for newer versions of pdfjs. With version 1.8.188 this error does not appear.

Body:
I want to open local (SD card) PDF file in a WebView.

I already tried this:

webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.getSettings().setAllowFileAccess(true);
File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

final Uri uri = Uri.fromFile(file);

webview.loadUrl(uri.toString());

But it's still not opening it, so let me know how I can open a PDF in WebView?

Body:
I know, this question is old.

But I really like the approach of Xamarin to make use of the pdf.js from Mozilla. It works on older Android versions, you don't need a special PDF Viewer app for this and you can easily display a PDF inside of your apps views hierarchy.

Git for this:
https://mozilla.github.io/pdf.js/

Additional default options (like standard zoom):
https://github.com/mozilla/pdf.js/wiki/Viewer-options

Just add the pdfjs files to your Assets directory:

And call it the following way:

// Assuming you got your pdf file:
File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

webview = (WebView) findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setBuiltInZoomControls(true);
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + file.getAbsolutePath() + "#zoom=page-width");

Cool thing: If you want to reduce the amount of functionalities / controls. Go to the Assets/pdfjs/web/viewer.html file and mark certain controls as hidden.
With

style="display: none;"

E.g. If you don't like the right toolbar:

<div id="toolbarViewerRight" style="display: none;">...</div>

Update

'URL scheme "file" is not supported'

Might occur for newer versions of pdfjs. With version 1.8.188 this error does not appear.


问:
help with a two table linq query
I want to display categories and subcategories like so:

Category 1

  Subcategory 1

  Subcategory 2

  Subcategory 3

Category 2

  Subcategory 5

  Subcategory 6

  Subcategory 7

In other words, foreach category, display the subcategories that belong to each one underneath.

My two tables are like so:

Category-

CategoryID

Name

SubCategory-

SubCategoryID

SubCategoryName

CategoryID

I have a foreign key from category to subcategory a one to many.

Here is where I got in the code, which display all sub categories foreach category.

```<code>public void displayLinqCategory()
{
    MyDataContext dbm = new MyDataContext();

    var q = from category in dbm.Categories
            join subCat in dbm.SubCategories
            on category.CategoryID equals subCat.CategoryID
            select new { category.Name, subCat.SubCategoryName };

    resultSpan.InnerHtml += "<table>";
    foreach (var c in q)
    {
        resultSpan.InnerHtml += "<tr><td>" + c.Name + "</td></tr>";
        foreach (var s in q)
        {
            resultSpan.InnerHtml += "<tr><td>   " + s.SubCategoryName + "</td></td>";
        }

    }
    resultSpan.InnerHtml += "</table>";
}
</code>```

答:
If you add an into clause it will group the related categories into a collection you can easily iterate over.

Here's how:

```<code>using (var dbm = new MyDataContext())
{
    var query = dbm.Categories
                join s in dbm.SubCategories on c.CategoryID equals s.CategoryID
                //group the related subcategories into a collection
                into subCollection
                select new { Category = c, SubCategories = subCollection };

    foreach (var result in query)
    {
        //use result.Category here...

        //now go through the subcategories for this category
        foreach (var sub in result.Subcategories)
        {
            //use sub here...
        }
    }
}
</code>```

Title: help with a two table linq query

Body:
I want to display categories and subcategories like so:

Category 1

  Subcategory 1

  Subcategory 2

  Subcategory 3

Category 2

  Subcategory 5

  Subcategory 6

  Subcategory 7

In other words, foreach category, display the subcategories that belong to each one underneath.

My two tables are like so:

Category-

CategoryID

Name

SubCategory-

SubCategoryID

SubCategoryName

CategoryID

I have a foreign key from category to subcategory a one to many.

Here is where I got in the code, which display all sub categories foreach category.

public void displayLinqCategory()
{
    MyDataContext dbm = new MyDataContext();

    var q = from category in dbm.Categories
            join subCat in dbm.SubCategories
            on category.CategoryID equals subCat.CategoryID
            select new { category.Name, subCat.SubCategoryName };

    resultSpan.InnerHtml += "
";
    foreach (var c in q)
    {
        resultSpan.InnerHtml += "
" + c.Name + "
";
        foreach (var s in q)
        {
            resultSpan.InnerHtml += "
   " + s.SubCategoryName + "		";
        }

    }
    resultSpan.InnerHtml += "
";
}

Body:
If you add an into clause it will group the related categories into a collection you can easily iterate over.

Here's how:

using (var dbm = new MyDataContext())
{
    var query = dbm.Categories
                join s in dbm.SubCategories on c.CategoryID equals s.CategoryID
                //group the related subcategories into a collection
                into subCollection
                select new { Category = c, SubCategories = subCollection };

    foreach (var result in query)
    {
        //use result.Category here...

        //now go through the subcategories for this category
        foreach (var sub in result.Subcategories)
        {
            //use sub here...
        }
    }
}


问:
How to get name of objects in global namespace in javascript
I am experiencing a javascript bug in internet explorer and I suspect its due to a name of a div matching with a global object.

My application loads many javascript libraries.

I want to find what global objects are loaded at runtime

答: You can simply inspect the window object in Chrome/Firefox devtools: just type window in the devtools console and expand the object to view its members.


问:
Excel to DATATABLE using isn't working after hosting
```<code>var pck = new OfficeOpenXml.ExcelPackage();

pck.Load(File.OpenRead("~\\EXCELS\\Book2.xlsx"));
</code>```

How to map excel after hosting ...

I tried this code it is not working for me.

I tried system path it works but after hosting doesn't work
it shows

Could not find a part of the path
  'C:\Windows\SysWOW64\inetsrv\~\EXCELS\Book2.xlsx'.

Can anyone help me please..

答:
You have to get the path relative to the website using Server.MapPath.

```<code>pck.Load(File.OpenRead(Server.MapPath(@"~\EXCELS\Book2.xlsx")));
</code>```

Body:
var pck = new OfficeOpenXml.ExcelPackage();

pck.Load(File.OpenRead("~\\EXCELS\\Book2.xlsx"));

How to map excel after hosting ...

I tried this code it is not working for me.

I tried system path it works but after hosting doesn't work
it shows

Could not find a part of the path
  'C:\Windows\SysWOW64\inetsrv\~\EXCELS\Book2.xlsx'.

Can anyone help me please..

Body:
You have to get the path relative to the website using Server.MapPath.

pck.Load(File.OpenRead(Server.MapPath(@"~\EXCELS\Book2.xlsx")));


问:
XCode/Swift 3: How to shift storyboard elements down/up without messing up existing constraints?
XCode/Swift 3

I've placed several elements (e.g. labels, text Fields) on my story board, and I've properly set all constraints.

Now I've decided that all content needs to shift down about five pixels. I can press the COMMAND + A keys to select all and then press the down arrow five times on my keyboard to shift everything. However, that messes up all of my existing constraints!

How can I shift everything down five pixels and preserve my constraints?

I'm very new to iOS programming, so thanks for your patience for what must be a very easy question for some of you!

答:
If you shift elements down it will cause the constraints to update accordingly. You should update all constraints, an easy way to do it is by selection the following option:

Select "Update constraints" and make sure you select "Apply to all views in container".


问:
TypeError: Cannot read property 'then' of undefined while making async call
I have been trying to work on application doing server side rendering. But I have been stuck where I am getting error 'Cannot read property 'then' of undefined'. As soon as my request goes to server for rendering the page, I need to load initial state from database and put it in store.But when I try to fetch data from server side I get the above error. Please find my server side code for rendering initial page

```<code>if (renderProps) {

  const components = renderProps.components;

  var componentObj = renderProps.components[2].WrappedComponent;
  const fetchData = (componentObj && componentObj.fetchDatas) || (() => Promise.resolve());
  const { location, params, history } = renderProps;
  const store = createStore(reducers, initialState, applyMiddleware(thunk));
  // calling this function which is place inside another component
  // I get error at below line stating cannot read property .then of undefined
   fetchData({ store, location, params, history })
  .then(() => {
    const markup= renderToString(
      <Provider store={store}>
        <RouterContext {...renderProps} />
      </Provider>
    )

    const state = store.getState();
    return res.render('index', { markup,initialState:
    JSON.stringify(store.getState()) });
    // if the current route matched we have renderProps
   }).catch((err)=> {
    console.log("error",err);
   })
  }
</code>```

Please find my code where I defined the function which is getting called

```<code>class IndexPage extends React.Component {
  componentDidMount () {
    this.props.getCoffeeOrders();
  }
  // call the action creator
  static fetchDatas({store}) {
     store.dispatch(getCoffeeOrders);
  }
  render() {
    // render code goes here
}
</code>```

}

Also Please find my action creator which makes a async call in action creator to fetch the data from server

```<code>import axios from 'axios';
export const FETCH_COFFEE_ORDERS = 'FETCH_COFFEE_ORDERS';
export  function getCoffeeOrders() {
//below line is getting printed on console
console.log("getting coffee orders inside");
return ((dispatch,getState) => {
    // below line is not getting printed
    // I think control does not come here
    console.log("mKe a call");
     return axios.get('http://localhost:8080/api/fetchcoffeeData').then((response)=> {
        console.log("got response", response);
        dispatch({
            type: FETCH_COFFEE_ORDERS,
            data
        });

    })
    .catch((err) => {
        console.log("got error while fetching data",err);
    });
});
}
</code>```

Control does not comes to the line which I printed in getCoffeeOrders inside another function.
Any help would be appreciated. Thanks in advance

答:
You don't return the promise in fetchDatas static function it should be something like this:

```<code>static fetchDatas({store}) {
   return store.dispatch(getCoffeeOrders);
}
</code>```

But I'm still not sure if redux dispatch returns anything take a look at this github issue

Body:
I have been trying to work on application doing server side rendering. But I have been stuck where I am getting error 'Cannot read property 'then' of undefined'. As soon as my request goes to server for rendering the page, I need to load initial state from database and put it in store.But when I try to fetch data from server side I get the above error. Please find my server side code for rendering initial page

if (renderProps) {

  const components = renderProps.components;

  var componentObj = renderProps.components[2].WrappedComponent;
  const fetchData = (componentObj && componentObj.fetchDatas) || (() => Promise.resolve());
  const { location, params, history } = renderProps;
  const store = createStore(reducers, initialState, applyMiddleware(thunk));
  // calling this function which is place inside another component
  // I get error at below line stating cannot read property .then of undefined
   fetchData({ store, location, params, history })
  .then(() => {
    const markup= renderToString(
      <Provider store={store}>
        <RouterContext {...renderProps} />
      </Provider>
    )

    const state = store.getState();
    return res.render('index', { markup,initialState:
    JSON.stringify(store.getState()) });
    // if the current route matched we have renderProps
   }).catch((err)=> {
    console.log("error",err);
   })
  }

Please find my code where I defined the function which is getting called

class IndexPage extends React.Component {
  componentDidMount () {
    this.props.getCoffeeOrders();
  }
  // call the action creator
  static fetchDatas({store}) {
     store.dispatch(getCoffeeOrders);
  }
  render() {
    // render code goes here
}

}

Also Please find my action creator which makes a async call in action creator to fetch the data from server

import axios from 'axios';
export const FETCH_COFFEE_ORDERS = 'FETCH_COFFEE_ORDERS';
export  function getCoffeeOrders() {
//below line is getting printed on console
console.log("getting coffee orders inside");
return ((dispatch,getState) => {
    // below line is not getting printed
    // I think control does not come here
    console.log("mKe a call");
     return axios.get('http://localhost:8080/api/fetchcoffeeData').then((response)=> {
        console.log("got response", response);
        dispatch({
            type: FETCH_COFFEE_ORDERS,
            data
        });

    })
    .catch((err) => {
        console.log("got error while fetching data",err);
    });
});
}

Control does not comes to the line which I printed in getCoffeeOrders inside another function.
Any help would be appreciated. Thanks in advance

Body:
You don't return the promise in fetchDatas static function it should be something like this:

static fetchDatas({store}) {
   return store.dispatch(getCoffeeOrders);
}

But I'm still not sure if redux dispatch returns anything take a look at this github issue


问:
AngularJS display data of index that has matching value
I am working on a dashboard and am trying to display a certain piece of data. In my scope I have a project which consists of a couple fields and an array of users. The users consist of the following fields:

user_id

user_name

user_email

role

I want to display the user_name of the role which matches a certain value.  Is there a way to do this within my html file or is it recommended to do this in my controller?

My table code looks as follows:

```<code><tbody md-body>
        <tr md-row md-select="project" md-select-id="name" md-auto-select
            ng-repeat="project in projects.data | orderBy : myOrder">
            <td md-cell ng-click="getProject()">{{project.title}}</td>
            <td md-cell><i class="material-icons" style="color: green">radio_button_checked</i></td>
            <td md-cell>{{project.phase}}</td>
            <td md-cell>{{project.budget_indication}}</td>
            <td md-cell>{{project.users}}</td> <!-- Display user with specific role -->
            <td md-cell>{{project.start_date | date:dd/MM/yyyy}}</td>
        </tr>
</tbody>
</code>```

Thanks in advance!

答:
If the project.data contains objects which has the role property (project.role) then you could use angular filter to filter against that property like this

```<code>Search by role: <input type="text" ng-model="roleSearch">

<tbody md-body>
        <tr md-row md-select="project" md-select-id="name" md-auto-select
            ng-repeat="project in projects.data | filter:{ role: roleSearch }| orderBy : myOrder">
            <td md-cell ng-click="getProject()">{{project.title}}</td>
            <td md-cell><i class="material-icons" style="color: green">radio_button_checked</i></td>
            <td md-cell>{{project.phase}}</td>
            <td md-cell>{{project.budget_indication}}</td>
            <td md-cell>{{project.users}}</td> <!-- Display user with specific role -->
            <td md-cell>{{project.start_date | date:dd/MM/yyyy}}</td>
        </tr>
</tbody>
</code>```

Read more about filters here.

More examples in this SO question

Update

To set the default filter value, you could set the roleSearch in the controller:

```<code>$scope.roleSearch = 'Admin';
</code>```

To filter by the users.role add this filter

```<code>filter:{ users.role: roleSearch }
</code>```

Body:
I am working on a dashboard and am trying to display a certain piece of data. In my scope I have a project which consists of a couple fields and an array of users. The users consist of the following fields:

user_id

user_name

user_email

role

I want to display the user_name of the role which matches a certain value.  Is there a way to do this within my html file or is it recommended to do this in my controller?

My table code looks as follows:

            {{project.title}}
            radio_button_checked
            {{project.phase}}
            {{project.budget_indication}}
            {{project.users}}
            {{project.start_date | date:dd/MM/yyyy}}

Thanks in advance!

Body:
If the project.data contains objects which has the role property (project.role) then you could use angular filter to filter against that property like this

Search by role: <input type="text" ng-model="roleSearch">

<tbody md-body>
        <tr md-row md-select="project" md-select-id="name" md-auto-select
            ng-repeat="project in projects.data | filter:{ role: roleSearch }| orderBy : myOrder">
            <td md-cell ng-click="getProject()">{{project.title}}</td>
            <td md-cell><i class="material-icons" style="color: green">radio_button_checked</i></td>
            <td md-cell>{{project.phase}}</td>
            <td md-cell>{{project.budget_indication}}</td>
            <td md-cell>{{project.users}}</td> <!-- Display user with specific role -->
            <td md-cell>{{project.start_date | date:dd/MM/yyyy}}</td>
        </tr>
</tbody>

Read more about filters here.

More examples in this SO question

Update

To set the default filter value, you could set the roleSearch in the controller:

$scope.roleSearch = 'Admin';

To filter by the users.role add this filter

filter:{ users.role: roleSearch }


问:
Mongoose $ne in Azure DocuemntDB
I know that DocumentDB in Azure does not support everything that is supported for MongoDB (despite Ms general statement that it does). What I am trying to do is create an application that can switch between using MongoDB and DocumentDB. What I have found is that DocumentDB essentially ignores the $ne operator when passed in by Mongoose.

Thus when run against DocumentDB, the following line of code as the filter operator in a Mongoose .find query returns everything, regardless as to whether the record already contains the given rule._id or not.

```<code>WebsiteObj.SelectWebsite = function(rule, websiteUri, callback){
    Website.find(
        {websiteUri: websiteUri, 'rules': { '$ne': rule._id }},
        ['_id', 'websiteUri', 'ipAddress', 'createdAt'], function(err, websites){
        if(err) {
            callback(err);
                return;
            }
            callback(null, rule, websites);
    });
};
</code>```

Is there a way to make this work without having to resort to DocumentDB specific querying?

答:
I have tested $ne operator using Mongoose (^4.9.2) with DocuemntDB, it worked for me.

Here is my full code example,

```<code>var mongoose = require('mongoose');
mongoose.connect('mongodb://my-user-name:my-password@my-host:10250/test/?ssl=true');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!

  var kittySchema = mongoose.Schema({
    name: String
  });

  var Kitten = mongoose.model('Kitten', kittySchema);

  var fluffy = new Kitten({ name: 'fluffy' });

  fluffy.save(function (err, fluffy) {
    if (err) return console.error(err);

    Kitten.find({name: { '$ne': 'fluffy' }}, function (err, kittens) {
      if (err) return console.error(err);
      console.log(kittens);
    })

  });

});
</code>```

I get the empty array when I run the code.

Title: Mongoose $ne in Azure DocuemntDB

Body:
I know that DocumentDB in Azure does not support everything that is supported for MongoDB (despite Ms general statement that it does). What I am trying to do is create an application that can switch between using MongoDB and DocumentDB. What I have found is that DocumentDB essentially ignores the $ne operator when passed in by Mongoose.

Thus when run against DocumentDB, the following line of code as the filter operator in a Mongoose .find query returns everything, regardless as to whether the record already contains the given rule._id or not.

WebsiteObj.SelectWebsite = function(rule, websiteUri, callback){
    Website.find(
        {websiteUri: websiteUri, 'rules': { '$ne': rule._id }},
        ['_id', 'websiteUri', 'ipAddress', 'createdAt'], function(err, websites){
        if(err) {
            callback(err);
                return;
            }
            callback(null, rule, websites);
    });
};

Is there a way to make this work without having to resort to DocumentDB specific querying?

Body:
I have tested $ne operator using Mongoose (^4.9.2) with DocuemntDB, it worked for me.

Here is my full code example,

var mongoose = require('mongoose');
mongoose.connect('mongodb://my-user-name:my-password@my-host:10250/test/?ssl=true');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!

  var kittySchema = mongoose.Schema({
    name: String
  });

  var Kitten = mongoose.model('Kitten', kittySchema);

  var fluffy = new Kitten({ name: 'fluffy' });

  fluffy.save(function (err, fluffy) {
    if (err) return console.error(err);

    Kitten.find({name: { '$ne': 'fluffy' }}, function (err, kittens) {
      if (err) return console.error(err);
      console.log(kittens);
    })

  });

});

I get the empty array when I run the code.


问:
Updating foreign keys in spring jpa hateoas
I am using the same code that is described on my other question: Accessing data jpa with rest getting started + entity bike that has foreign key on person entity

The problem is that i cannot update the value person_id in the bike entity. I tried using this command:

```<code>curl -i -X PUT -H "Content-Type:application/json" -d "{ \"name\" : \"Frodos Bike name is changed\", \"person\" : \"http://localhost:8080/people/2\" }" http://localhost:8080/bikes/1
</code>```

But it doesn't work. The name value changes, but the person_id stays the same.

Keep in mind that i do have a person which has ID = 2, and it is accesible at the url: http://localhost:8080/people/2

What is the correct way of updating this field?

答:
PUT would work with curl -i -X PUT -H "Content-Type:application/json" -d '{"_links": {"person": {"href" : "/people/2"}}} http://localhost:8080/bikes/1/person

or also with PATCH with curl -i -X PATCH -H "Content-Type:application/json" -d "{ \"name\" : \"Frodos Bike name is changed\", \"person\" : \"/people/2\" }" http://localhost:8080/bikes/1

Body:
I am using the same code that is described on my other question: Accessing data jpa with rest getting started + entity bike that has foreign key on person entity

The problem is that i cannot update the value person_id in the bike entity. I tried using this command:

curl -i -X PUT -H "Content-Type:application/json" -d "{ \"name\" : \"Frodos Bike name is changed\", \"person\" : \"http://localhost:8080/people/2\" }" http://localhost:8080/bikes/1

But it doesn't work. The name value changes, but the person_id stays the same.

Keep in mind that i do have a person which has ID = 2, and it is accesible at the url: http://localhost:8080/people/2

What is the correct way of updating this field?


问:
Returning anonymous type in C#
I have a query that returns an anonymous type and the query is in a method. How do you write this:</p>

```<code>public "TheAnonymousType" TheMethod(SomeParameter)
{
  using (MyDC TheDC = new MyDC())
  {
     var TheQueryFromDB = (....
                           select new { SomeVariable = ....,
                                        AnotherVariable = ....}
                           ).ToList();

      return "TheAnonymousType";
    }
}
</code>```

答:
In C# 7 we can use tuples to accomplish this:

```<code>public List<(int SomeVariable, string AnotherVariable)> TheMethod(SomeParameter)
{
  using (MyDC TheDC = new MyDC())
  {
     var TheQueryFromDB = (....
                       select new { SomeVariable = ....,
                                    AnotherVariable = ....}
                       ).ToList();

      return TheQueryFromDB
                .Select(s => (
                     SomeVariable = s.SomeVariable,
                     AnotherVariable = s.AnotherVariable))
                 .ToList();
  }
}
</code>```

You might need to install System.ValueTuple nuget package though.

Title: Returning anonymous type in C#

Body:
I have a query that returns an anonymous type and the query is in a method. How do you write this:

public "TheAnonymousType" TheMethod(SomeParameter)
{
  using (MyDC TheDC = new MyDC())
  {
     var TheQueryFromDB = (....
                           select new { SomeVariable = ....,
                                        AnotherVariable = ....}
                           ).ToList();

      return "TheAnonymousType";
    }
}

Body:
In C# 7 we can use tuples to accomplish this:

public List<(int SomeVariable, string AnotherVariable)> TheMethod(SomeParameter)
{
  using (MyDC TheDC = new MyDC())
  {
     var TheQueryFromDB = (....
                       select new { SomeVariable = ....,
                                    AnotherVariable = ....}
                       ).ToList();

      return TheQueryFromDB
                .Select(s => (
                     SomeVariable = s.SomeVariable,
                     AnotherVariable = s.AnotherVariable))
                 .ToList();
  }
}

You might need to install System.ValueTuple nuget package though.


问:
EntityFramework in .NET - when adding child entity to existing parent, parent is being validated/added
I am using EntityFramework with .NET and I have, among others, entities Invoice (parent) and receipt (child). They are modeled as shown below:

```<code>public class Invoice
{
  public int InvoiceID { get; set; }

  [Required(ErrorMessage = "Field Date is mandatory for the invoice.")]
  public DateTime Date { get; set; }
  ...
  public virtual ICollection<Receipt> Receipts { get; set; }
}

public class Receipt
{
  public int ReceiptID { get; set; }
...
  public int? InvoiceID { get; set; }
  public Invoice Invoice { get; set; }
}
</code>```

I have the invoice added in the database already. The problem is when I try to add a receipt for it. In order to do this, I use a FormView, with properties ItemType="Models.Receipt", ValidateRequestMode="Enabled", InsertMethod="AddReceipt":

```<code>public void AddReceipt(Models.Receipt receiptObj)
{
  receiptObj.InvoiceID = intInvoiceID; //from POST
  if (ModelState.IsValid)
    {
       var _db = new Models.InvoiceContext();
       _db.Receipts.Add(receiptObj);
       _db.Entry(receiptObj).State = System.Data.Entity.EntityState.Added;
      _db.SaveChanges();
    }
 }
</code>```

The ModelState.IsValid returns false. The error message is "Field Date is mandatory for the invoice." - But I am not trying to add an invoice! When I inspect the "ModelState" in Debug, in ModelState.Keys I see values "Invoice.InvoiceNumber" and "Invoice.InvoiceDate"...?

If I try to load the invoice

```<code>receiptObj.Invoice= GetInvoice(intInvoiceID);
</code>```

I still get the same validation error, even if when I inspect in Debug the invoice.Bill, I see that it is loaded properly- including the date field. (But fetching the invoice this way is not ok because I'll receive another error when I solve the validation problem because I use a different context when I call GetInvoice(intInvoiceID) and I can't attach the invoice object to two different contexts.)

I'm stuck with this for some time, so any help is greatly appreciated.

答:
I found the problem! I'm posting it in case someone else encounters it.

Inside the FormView which I use to insert/upate the receipt, I had a label which displayed the invoice number.

```<code><asp:Label ID="lblInvoiceNumber_edit" Text='<%# Bind("Invoice.InvoiceNumber") %>' runat="server"></asp:Label>
</code>```

Because of the Bind, each time I was trying to insert/update a receipt, the context was also trying to insert a new invoice - but since for this new invoice only the InvoiceNumber field was bound, all the other fields were null - this is why the validation for the mandatory field Date of the invoice failed.

Thank you all for your interest and suggestions.

Body:
I am using EntityFramework with .NET and I have, among others, entities Invoice (parent) and receipt (child). They are modeled as shown below:

public class Invoice
{
  public int InvoiceID { get; set; }

  [Required(ErrorMessage = "Field Date is mandatory for the invoice.")]
  public DateTime Date { get; set; }
  ...
  public virtual ICollection<Receipt> Receipts { get; set; }
}

public class Receipt
{
  public int ReceiptID { get; set; }
...
  public int? InvoiceID { get; set; }
  public Invoice Invoice { get; set; }
}

I have the invoice added in the database already. The problem is when I try to add a receipt for it. In order to do this, I use a FormView, with properties ItemType="Models.Receipt", ValidateRequestMode="Enabled", InsertMethod="AddReceipt":

public void AddReceipt(Models.Receipt receiptObj)
{
  receiptObj.InvoiceID = intInvoiceID; //from POST
  if (ModelState.IsValid)
    {
       var _db = new Models.InvoiceContext();
       _db.Receipts.Add(receiptObj);
       _db.Entry(receiptObj).State = System.Data.Entity.EntityState.Added;
      _db.SaveChanges();
    }
 }

The ModelState.IsValid returns false. The error message is "Field Date is mandatory for the invoice." - But I am not trying to add an invoice! When I inspect the "ModelState" in Debug, in ModelState.Keys I see values "Invoice.InvoiceNumber" and "Invoice.InvoiceDate"...?

If I try to load the invoice

receiptObj.Invoice= GetInvoice(intInvoiceID);

I still get the same validation error, even if when I inspect in Debug the invoice.Bill, I see that it is loaded properly- including the date field. (But fetching the invoice this way is not ok because I'll receive another error when I solve the validation problem because I use a different context when I call GetInvoice(intInvoiceID) and I can't attach the invoice object to two different contexts.)

I'm stuck with this for some time, so any help is greatly appreciated.

Body:
I found the problem! I'm posting it in case someone else encounters it.

Inside the FormView which I use to insert/upate the receipt, I had a label which displayed the invoice number.

<asp:Label ID="lblInvoiceNumber_edit" Text='<%# Bind("Invoice.InvoiceNumber") %>' runat="server"></asp:Label>

Because of the Bind, each time I was trying to insert/update a receipt, the context was also trying to insert a new invoice - but since for this new invoice only the InvoiceNumber field was bound, all the other fields were null - this is why the validation for the mandatory field Date of the invoice failed.

Thank you all for your interest and suggestions.


问:
How to pass bitset of any size to a function?
The following program compiles fine.

```<code>#include <iostream>
#include <bitset>

void foo(std::bitset<10> n)
{
    std::cout << n.size() << "\n";
}

int main()
{
    std::bitset<10> n;
    foo(n);
}
</code>```

```<code>$ g++ -std=c++11 -Wall -Wextra -pedantic foo.cpp
$ ./a.out
10
</code>```

How can I modify the foo() function such that it can accept bitset of any size?

答:
That's what templates supposed to do. So make foo a function template with non-type template parameter:

```<code>template<std::size_t N>
void foo(std::bitset<N> n)
{
    std::cout << n.size() << "\n";
}
</code>```

then

```<code>std::bitset<10> n10;
foo(n10);
std::bitset<20> n20;
foo(n20);
</code>```

Body:
The following program compiles fine.

#include <iostream>
#include <bitset>

void foo(std::bitset<10> n)
{
    std::cout << n.size() << "\n";
}

int main()
{
    std::bitset<10> n;
    foo(n);
}

$ g++ -std=c++11 -Wall -Wextra -pedantic foo.cpp
$ ./a.out
10

How can I modify the foo() function such that it can accept bitset of any size?

Body:
That's what templates supposed to do. So make foo a function template with non-type template parameter:

template<std::size_t N>
void foo(std::bitset<N> n)
{
    std::cout << n.size() << "\n";
}

then

std::bitset<10> n10;
foo(n10);
std::bitset<20> n20;
foo(n20);