问:
Python Pandas - Iterating and adding data to blank column
I am trying to iterate through a dataframe, classify each row and add the output to the end of the row in a new column.

It seems to be adding the same classification to every row

```<code>dfMach = pd.read_csv("C:/Users/nicholas/Desktop/machineSum.csv", encoding='latin-1')
dfNew = dfMach
dfNew["Classification"] = ""

for index, row in dfMach.iterrows():
    aVar = dfMach['Summary'].iat[0]
    aClass = cl.classify(aVar)
    dfNew['Classification'] = aClass
</code>```

Where am I going wrong?

Thank you

答:
Use apply instead of looping explicitly i.e

```<code> dfMach['Classification'] = dfMach['Summary'].apply(cl.classify)
</code>```

A couple of simple mistake to be corrected in your code and a bit of improvement i.e

```<code>dfNew = dfMach.copy() # dfNew = dfMach This will not let you create a new copy so you have to use dfMach.copy()

dfNew["Classification"] = ""

for index, row in dfMach.iterrows():
    # As @jez suggested we need to use loc for assignemnt
    dfNew.loc[index, 'Classification'] = cl.classify(row['Summary'])
</code>```

Body:
I am trying to iterate through a dataframe, classify each row and add the output to the end of the row in a new column.

It seems to be adding the same classification to every row

dfMach = pd.read_csv("C:/Users/nicholas/Desktop/machineSum.csv", encoding='latin-1')
dfNew = dfMach
dfNew["Classification"] = ""

for index, row in dfMach.iterrows():
    aVar = dfMach['Summary'].iat[0]
    aClass = cl.classify(aVar)
    dfNew['Classification'] = aClass

Where am I going wrong?

Thank you

Body:
Use apply instead of looping explicitly i.e

 dfMach['Classification'] = dfMach['Summary'].apply(cl.classify)

A couple of simple mistake to be corrected in your code and a bit of improvement i.e

dfNew = dfMach.copy() # dfNew = dfMach This will not let you create a new copy so you have to use dfMach.copy()

dfNew["Classification"] = ""

for index, row in dfMach.iterrows():
    # As @jez suggested we need to use loc for assignemnt
    dfNew.loc[index, 'Classification'] = cl.classify(row['Summary'])


来源: stackexchange

问:
How can I able to display todays working hour in a different colour in vue js?
My script for the same to display is

```<code>const workHour = "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM".split(',').map((val) => {
  const obj = val.split(':');
  const time = val.replace(`${obj[0]}:`, '');
  return {
    day: obj[0],
    time,
  }
});
console.log(workHour);
</code>```

HTML CODE TO DISPLAY THE VALUES ARE

```<code>   <table class="table">
  <thead>
    <tr>
      <th v-for="(item,key) in data.workHr" :key="key">{{item.day}}</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td v-for="(item,key) in data.workHr" :key="key">{{item.time}}</td>
    </tr>
  </tbody>
</table>
</code>```

By this, I am able to display the date as well as working hours. I need to change colour of todays working hours and automatically update for tomorrow? Can anyone please help to solve the problem?

答:
Try the following codes

With if

```<code> <td v-for="(item,key) in workHr" :key="key">
    <span v-if="new Date().getDay()-1==key" class="today">{{item.time}}</span>
    <span v-else-if="new Date().getDay()==key" class="tomorrow">{{item.time}}</span>
    <span v-else >{{item.time}}</span>
 </td>
</code>```

With class object

```<code><span :class="{'tomorrow':new Date().getDay()==key,'today':new Date().getDay()-1==key}">{{item.time}}</span>
</code>```

If condition demo:https://jsfiddle.net/50wL7mdz/76096/

Class object demo:https://jsfiddle.net/50wL7mdz/77860/

ContentLicense: CC BY-SA 3.0

Body:
My script for the same to display is

const workHour = "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM".split(',').map((val) => {
  const obj = val.split(':');
  const time = val.replace(`${obj[0]}:`, '');
  return {
    day: obj[0],
    time,
  }
});
console.log(workHour);

HTML CODE TO DISPLAY THE VALUES ARE

      {{item.day}}

      {{item.time}}

By this, I am able to display the date as well as working hours. I need to change colour of todays working hours and automatically update for tomorrow? Can anyone please help to solve the problem?

Body:
Try the following codes

With if

 <td v-for="(item,key) in workHr" :key="key">
    <span v-if="new Date().getDay()-1==key" class="today">{{item.time}}</span>
    <span v-else-if="new Date().getDay()==key" class="tomorrow">{{item.time}}</span>
    <span v-else >{{item.time}}</span>
 </td>

With class object

<span :class="{'tomorrow':new Date().getDay()==key,'today':new Date().getDay()-1==key}">{{item.time}}</span>

If condition demo:https://jsfiddle.net/50wL7mdz/76096/

Class object demo:https://jsfiddle.net/50wL7mdz/77860/


问:
Can I prevent SharpDevelop design view from setting a property's value in InitializeComponent?
I am finding that Design View (DV) is nice, but trying to change the way it automagically injects code into InitializeComponent is very hard. And sometimes its automagical code breaks the program.

For example, DV automatically sees every single property of my custom UserControl, and then it assigns every single property to some value in InitializeComponent. But I don't want it to assign values to some of the properties because some of my setters will throw a runtime exception if not used correctly. I could correct InitializeComponent manually, but anytime I make a change to the design, SharpDevelop will just regenerate the function again.

And there's another case where I have the Default Constructor set the size based upon certain factors, but then InitializeComponent will immediately set it to another static value.

How can I tell DV to not automagically assign values to certain properties I define?

答:
Unless I misunderstood your scenario, it seems like you're barking up the wrong tree by trying to modify or reconfigure SharpDevelop's behavior. Even if you manage to change it, you won't affect Visual Studio's behavior, and you won't help any of the other consumers of your custom control who don't happen to (and/or don't want to) configure their designer accordingly.

Instead, it seems that you should just mark the properties exposed by your custom control with the [DesignerSerializationVisibility] attribute. This indicates to the designer exactly how that property's value should be serialized into the InitializeComponent method.

You have a choice of three different values:

Visible indicates that the value for the property should be persisted in initialization code

Hidden indicates that the value for the property should not be persisted in initialization code

Content indicates that initialization code should be generated for each public (not hidden) property of the object assigned to the property

The default value is Visible, which causes a property's value to be serialized whenever possible.

ContentLicense: CC BY-SA 2.5


问:
writeFile does not create file
Error code looks like:

```<code>{ Error: ENOENT: no such file or directory, open 'sad' errno: -2, code: 'ENOENT', syscall: 'open', path: 'sad' }
</code>```

where 'sad' is the name of file I would like to write to and it doesn't exist.

Code looks like this:

```<code>fs.writeFile(filename, JSON_string, { flag: 'w' }, function(err){
        if(err){
            return console.error(err);
        }
        return JSON_string;
    });
</code>```

There are other similar questions, but they are all wrong in their path, starting or not starting with /, I just want to write a file on root from where I run this node.js application (it is also initialized with npm in this directory..).

Running with

```<code>sudo node server4.js
</code>```

Doesnt work either.
Changing flags to w+ or wx or whatever, doesn't help.
Code works if file exists.

Node v9+.

I need to use writeFile() function.

答:
This is working for me, please check if this works in your system:

```<code>var fs = require('fs')

fs.writeFile('./myfile.txt', 'Content to write', { flag: 'w' }, function(err) {
    if (err)
        return console.error(err);
    fs.readFile('./myfile.txt', 'utf-8', function (err, data) {
        if (err)
            return console.error(err);
        console.log(data);
    });
});
</code>```

(besides writing it also reads to confirm)

Title: writeFile does not create file

Body:
Error code looks like:

{ Error: ENOENT: no such file or directory, open 'sad' errno: -2, code: 'ENOENT', syscall: 'open', path: 'sad' }

where 'sad' is the name of file I would like to write to and it doesn't exist.

Code looks like this:

fs.writeFile(filename, JSON_string, { flag: 'w' }, function(err){
        if(err){
            return console.error(err);
        }
        return JSON_string;
    });

There are other similar questions, but they are all wrong in their path, starting or not starting with /, I just want to write a file on root from where I run this node.js application (it is also initialized with npm in this directory..).

Running with

sudo node server4.js

Doesnt work either.
Changing flags to w+ or wx or whatever, doesn't help.
Code works if file exists.

Node v9+.

I need to use writeFile() function.

Body:
This is working for me, please check if this works in your system:

var fs = require('fs')

fs.writeFile('./myfile.txt', 'Content to write', { flag: 'w' }, function(err) {
    if (err)
        return console.error(err);
    fs.readFile('./myfile.txt', 'utf-8', function (err, data) {
        if (err)
            return console.error(err);
        console.log(data);
    });
});

(besides writing it also reads to confirm)

ContentLicense: CC BY-SA 4.0


问:
Spring Data Neo4j 5 and dynamic @Properties - InvalidDataAccessApiUsageException
This is my SDN 5 relationship entity:

```<code>@RelationshipEntity(type = "HAS_VALUE_ON")
public class RelationshipValue {

    @Id
    @GeneratedValue
    private Long id;

    @StartNode
    private Decision decision;

    @EndNode
    private Valuable valuable;

    @Index(unique = false)
    private Object value;

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}
</code>```

Everything is working fine, but when I try to change the logic onto new dynamic @Properties :

```<code>@RelationshipEntity(type = "HAS_VALUE_ON")
public class RelationshipValue {

    public static final String VALUE_PROPERTY_NAME = "value";

    @Id
    @GeneratedValue
    private Long id;

    @StartNode
    private Decision decision;

    @EndNode
    private Valuable valuable;

    @Properties(allowCast = true)
    private Map<String, Object> valueProperties = new HashMap<>();

    public Object getValue() {
        return valueProperties.get(VALUE_PROPERTY_NAME);
    }

    public void setValue(Object value) {
        valueProperties.put(VALUE_PROPERTY_NAME, value);
    }

}
</code>```

my tests fails with the following error:

```<code>org.springframework.dao.InvalidDataAccessApiUsageException: Could not map key=valueProperties.value, value=[Ljava.lang.Object;@52bef30b (type = class [Ljava.lang.Object;) because it is not a supported type.; nested exception is org.neo4j.ogm.exception.core.MappingException: Could not map key=valueProperties.value, value=[Ljava.lang.Object;@52bef30b (type = class [Ljava.lang.Object;) because it is not a supported type.
    at org.springframework.data.neo4j.transaction.SessionFactoryUtils.convertOgmAccessException(SessionFactoryUtils.java:126)
    at org.springframework.data.neo4j.repository.support.SessionBeanDefinitionRegistrarPostProcessor.translateExceptionIfPossible(SessionBeanDefinitionRegistrarPostProcessor.java:71)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:217)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy144.save(Unknown Source)
    at com.example.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl.createOrUpdate(RelationshipValueDaoImpl.java:47)
    at com.example.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl.synchronizeWithValues(RelationshipValueDaoImpl.java:107)
    at com.example.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl.create(RelationshipValueDaoImpl.java:42)
    at com.example.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl$$FastClassBySpringCGLIB$$5a98b507.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:112)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
    at com.example.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl$$EnhancerBySpringCGLIB$$a2f79bd4.create(<generated>)
    at com.example.domain.dao.decision.characteristic.value.ValueDaoImpl.create(ValueDaoImpl.java:86)
    at com.example.domain.dao.decision.characteristic.value.ValueDaoImpl.create(ValueDaoImpl.java:51)
    at com.example.domain.dao.decision.characteristic.value.ValueDaoImpl$$FastClassBySpringCGLIB$$db4e63af.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:112)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
    at com.example.domain.dao.decision.characteristic.value.ValueDaoImpl$$EnhancerBySpringCGLIB$$532710cc.create(<generated>)
    at com.example.domain.DecisionCharacteristicIT.testDuplicateCharacteristicValues(DecisionCharacteristicIT.java:573)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.neo4j.ogm.exception.core.MappingException: Could not map key=valueProperties.value, value=[Ljava.lang.Object;@52bef30b (type = class [Ljava.lang.Object;) because it is not a supported type.
    at org.neo4j.ogm.typeconversion.MapCompositeConverter.addMapToProperties(MapCompositeConverter.java:104)
    at org.neo4j.ogm.typeconversion.MapCompositeConverter.toGraphProperties(MapCompositeConverter.java:88)
    at org.neo4j.ogm.typeconversion.MapCompositeConverter.toGraphProperties(MapCompositeConverter.java:37)
    at org.neo4j.ogm.metadata.FieldInfo.readComposite(FieldInfo.java:445)
    at org.neo4j.ogm.context.EntityGraphMapper.updateRelationshipEntity(EntityGraphMapper.java:623)
    at org.neo4j.ogm.context.EntityGraphMapper.map(EntityGraphMapper.java:116)
    at org.neo4j.ogm.session.delegates.SaveDelegate.save(SaveDelegate.java:80)
    at org.neo4j.ogm.session.Neo4jSession.save(Neo4jSession.java:456)
    at sun.reflect.GeneratedMethodAccessor76.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.invoke(SharedSessionCreator.java:131)
    at com.sun.proxy.$Proxy96.save(Unknown Source)
    at org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save(SimpleNeo4jRepository.java:131)
    at sun.reflect.GeneratedMethodAccessor75.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:377)
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:610)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:573)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:554)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    ... 67 more
</code>```

Is there any way to emulate the same correct behaviour(as in the first code snippet) with the dynamic @Properties ?

答:
It is probably because arrays are not supported as Map values.

Switching from array to List as an argument to the setValue method should solve the problem.

Body:
This is my SDN 5 relationship entity:

@RelationshipEntity(type = "HAS_VALUE_ON")
public class RelationshipValue {

    @Id
    @GeneratedValue
    private Long id;

    @StartNode
    private Decision decision;

    @EndNode
    private Valuable valuable;

    @Index(unique = false)
    private Object value;

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}

Everything is working fine, but when I try to change the logic onto new dynamic @Properties :

@RelationshipEntity(type = "HAS_VALUE_ON")
public class RelationshipValue {

    public static final String VALUE_PROPERTY_NAME = "value";

    @Id
    @GeneratedValue
    private Long id;

    @StartNode
    private Decision decision;

    @EndNode
    private Valuable valuable;

    @Properties(allowCast = true)
    private Map<String, Object> valueProperties = new HashMap<>();

    public Object getValue() {
        return valueProperties.get(VALUE_PROPERTY_NAME);
    }

    public void setValue(Object value) {
        valueProperties.put(VALUE_PROPERTY_NAME, value);
    }

}

my tests fails with the following error:

org.springframework.dao.InvalidDataAccessApiUsageException: Could not map key=valueProperties.value, value=[Ljava.lang.Object;@52bef30b (type = class [Ljava.lang.Object;) because it is not a supported type.; nested exception is org.neo4j.ogm.exception.core.MappingException: Could not map key=valueProperties.value, value=[Ljava.lang.Object;@52bef30b (type = class [Ljava.lang.Object;) because it is not a supported type.
    at org.springframework.data.neo4j.transaction.SessionFactoryUtils.convertOgmAccessException(SessionFactoryUtils.java:126)
    at org.springframework.data.neo4j.repository.support.SessionBeanDefinitionRegistrarPostProcessor.translateExceptionIfPossible(SessionBeanDefinitionRegistrarPostProcessor.java:71)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:217)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy144.save(Unknown Source)
    at com.example.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl.createOrUpdate(RelationshipValueDaoImpl.java:47)
    at com.example.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl.synchronizeWithValues(RelationshipValueDaoImpl.java:107)
    at com.example.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl.create(RelationshipValueDaoImpl.java:42)
    at com.example.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl$$FastClassBySpringCGLIB$$5a98b507.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:112)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
    at com.example.domain.dao.decision.characteristic.value.RelationshipValueDaoImpl$$EnhancerBySpringCGLIB$$a2f79bd4.create(<generated>)
    at com.example.domain.dao.decision.characteristic.value.ValueDaoImpl.create(ValueDaoImpl.java:86)
    at com.example.domain.dao.decision.characteristic.value.ValueDaoImpl.create(ValueDaoImpl.java:51)
    at com.example.domain.dao.decision.characteristic.value.ValueDaoImpl$$FastClassBySpringCGLIB$$db4e63af.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:112)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
    at com.example.domain.dao.decision.characteristic.value.ValueDaoImpl$$EnhancerBySpringCGLIB$$532710cc.create(<generated>)
    at com.example.domain.DecisionCharacteristicIT.testDuplicateCharacteristicValues(DecisionCharacteristicIT.java:573)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.neo4j.ogm.exception.core.MappingException: Could not map key=valueProperties.value, value=[Ljava.lang.Object;@52bef30b (type = class [Ljava.lang.Object;) because it is not a supported type.
    at org.neo4j.ogm.typeconversion.MapCompositeConverter.addMapToProperties(MapCompositeConverter.java:104)
    at org.neo4j.ogm.typeconversion.MapCompositeConverter.toGraphProperties(MapCompositeConverter.java:88)
    at org.neo4j.ogm.typeconversion.MapCompositeConverter.toGraphProperties(MapCompositeConverter.java:37)
    at org.neo4j.ogm.metadata.FieldInfo.readComposite(FieldInfo.java:445)
    at org.neo4j.ogm.context.EntityGraphMapper.updateRelationshipEntity(EntityGraphMapper.java:623)
    at org.neo4j.ogm.context.EntityGraphMapper.map(EntityGraphMapper.java:116)
    at org.neo4j.ogm.session.delegates.SaveDelegate.save(SaveDelegate.java:80)
    at org.neo4j.ogm.session.Neo4jSession.save(Neo4jSession.java:456)
    at sun.reflect.GeneratedMethodAccessor76.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.invoke(SharedSessionCreator.java:131)
    at com.sun.proxy.$Proxy96.save(Unknown Source)
    at org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.save(SimpleNeo4jRepository.java:131)
    at sun.reflect.GeneratedMethodAccessor75.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:377)
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:610)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:573)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:554)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    ... 67 more

Is there any way to emulate the same correct behaviour(as in the first code snippet) with the dynamic @Properties ?


问:
Dependency inject IPrincipal into a DBContext in separate assembly in MVC
I'm trying to get details about the current user in my DBContext so that I can store a CreatedByUserId and ModifiedByUserId when a record is updated.

What I'm finding is that the IPrincipal instance injected is valid for the controllers, but is null when injected into my DB Context, which is in a separate assembly.

I'm doing the injection with Autofac as follows:

```<code>builder.Register(c => HttpContext.Current.User).As<IPrincipal>().InstancePerRequest();

builder.Register<AppDbContext>(c => new AppDbContext(GlobalHost.DependencyResolver.Resolve<IPrincipal>())).InstancePerLifetimeScope();
</code>```

My controller constructors look like this, and user will be valid here as expected:

```<code>public class ProductsController : Controller
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService, IPrincipal userPrincipal)
    {
        var user = userPrincipal;
        _productService = productService;
    }
</code>```

My DBContext constructor looks like this and user will be null here:

```<code>public partial class AppDbContext : System.Data.Entity.DbContext, IAppDbContext
{
    public AppDbContext(IPrincipal principal)
        : this("Name=SqlConnection", principal)
    {
        var user = principal;
    }
</code>```

The controller code is called before the DB Context code, so it's not a timing issue, so I'm guessing the issue here is that the DB Context code is running on a different thread to the controller with different identity maybe?

If I use this code to get the identity in my DB context I can successfully get the user:

```<code>var user = System.Threading.Thread.CurrentPrincipal;
</code>```

But it seems like I might run into issues getting the user in two different ways in the same app, and I'd need to figure out a way to make the DI return HTTPContext's user to the web project and the thread's principal to another assembly, all of which smacks of being the wrong solution?

Can anyone help me understand exactly why I'm seeing the behaviour above and advise on the best way to get the principal in the different assemblies of an mvc app?

答:
So, the issue here turns out to be that I'm using the wrong Dependency Resolver when setting up the DB Context in this line:

```<code>builder.Register<AppDbContext>(c => new AppDbContext(GlobalHost.DependencyResolver.Resolve<IPrincipal>())).InstancePerLifetimeScope();
</code>```

GlobalHost.DependencyResolver is giving me the SignalR resolver rather than MVC's resolver.  Removing the GlobalHost bit then gives me the System.Web.MVC.DependencyResolver instead and then I can use that to get the IPrincipal as follows:

```<code>builder.Register<AppDbContext>(c => new AppDbContext(DependencyResolver.Current.GetService<IPrincipal>())).InstancePerRequest();
</code>```

Body:
I'm trying to get details about the current user in my DBContext so that I can store a CreatedByUserId and ModifiedByUserId when a record is updated.

What I'm finding is that the IPrincipal instance injected is valid for the controllers, but is null when injected into my DB Context, which is in a separate assembly.

I'm doing the injection with Autofac as follows:

builder.Register(c => HttpContext.Current.User).As<IPrincipal>().InstancePerRequest();

builder.Register<AppDbContext>(c => new AppDbContext(GlobalHost.DependencyResolver.Resolve<IPrincipal>())).InstancePerLifetimeScope();

My controller constructors look like this, and user will be valid here as expected:

public class ProductsController : Controller
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService, IPrincipal userPrincipal)
    {
        var user = userPrincipal;
        _productService = productService;
    }

My DBContext constructor looks like this and user will be null here:

public partial class AppDbContext : System.Data.Entity.DbContext, IAppDbContext
{
    public AppDbContext(IPrincipal principal)
        : this("Name=SqlConnection", principal)
    {
        var user = principal;
    }

The controller code is called before the DB Context code, so it's not a timing issue, so I'm guessing the issue here is that the DB Context code is running on a different thread to the controller with different identity maybe?

If I use this code to get the identity in my DB context I can successfully get the user:

var user = System.Threading.Thread.CurrentPrincipal;

But it seems like I might run into issues getting the user in two different ways in the same app, and I'd need to figure out a way to make the DI return HTTPContext's user to the web project and the thread's principal to another assembly, all of which smacks of being the wrong solution?

Can anyone help me understand exactly why I'm seeing the behaviour above and advise on the best way to get the principal in the different assemblies of an mvc app?

Body:
So, the issue here turns out to be that I'm using the wrong Dependency Resolver when setting up the DB Context in this line:

builder.Register<AppDbContext>(c => new AppDbContext(GlobalHost.DependencyResolver.Resolve<IPrincipal>())).InstancePerLifetimeScope();

GlobalHost.DependencyResolver is giving me the SignalR resolver rather than MVC's resolver.  Removing the GlobalHost bit then gives me the System.Web.MVC.DependencyResolver instead and then I can use that to get the IPrincipal as follows:

builder.Register<AppDbContext>(c => new AppDbContext(DependencyResolver.Current.GetService<IPrincipal>())).InstancePerRequest();


问:
How to make a Python list based on another list
I have a master list and then a whole bunch (100s) of sublists cherry-picked from the master list. However, over time items in the master list will be removed. I want to also remove those items from each of the sublists. I imagine having a list that is only pointers to the master list. As the pointer goes stale then the list gets smaller. The sublists are normally in objects not easily accessible at the point where the master list is edited. Is this possible?</p>

```<code>master = ["first","last","middle","top","bottom","left","right","inside"]

sides = []
sides.append(master[2])
sides.append(master[3])
sides.append(master[4])

centre = []
centre.append(master[0])
centre.append(master[2])
centre.append(master[7])

print(master)
['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
print(sides)
['middle', 'top', 'bottom']
print(centre)
['first', 'middle', 'inside']

master.remove("middle")

print(master)
['first', 'last', 'top', 'bottom', 'left', 'right', 'inside']
print(sides) # Ideal outcome
['top', 'bottom']
print(centre) # Ideal outcome
['first', 'inside']
</code>```

答:
You could use a custom class that subclasses list. This way you can tailor the behavior of .remove:

```<code>class Lists(list):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # logic here, for now using the whole passed list
        self.sides = self[:]
        self.center = self[:]

    def remove(self, obj):
        #  TODO catch ValueError that is raised if obj isn't in all of the lists
        super().remove(obj)
        self.sides.remove(obj)
        self.center.remove(obj)

   # probably overriding other methods from list, such as append, so
   # an instance can be used directly to interact with the "master" list

my_lists = Lists(["first", "last", "middle", "top", "bottom", "left", "right", "inside"])

print(my_lists)
my_lists.remove('last')
print(my_lists)
print(my_lists.sides)
print(my_lists.center)

# ['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
# ['first', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
# ['first', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
# ['first', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
</code>```

You could also better encapsulate .master if needed (as the in-code comment suggests).

However, you may want to rethink the problem and the approach you have chosen to solve it. There might be a better way than keeping sublists of the original list, and you should also keep in mind that .remove will raise an exception if you try to delete a non-existing element from the list.

Body:
I have a master list and then a whole bunch (100s) of sublists cherry-picked from the master list. However, over time items in the master list will be removed. I want to also remove those items from each of the sublists. I imagine having a list that is only pointers to the master list. As the pointer goes stale then the list gets smaller. The sublists are normally in objects not easily accessible at the point where the master list is edited. Is this possible?

master = ["first","last","middle","top","bottom","left","right","inside"]

sides = []
sides.append(master[2])
sides.append(master[3])
sides.append(master[4])

centre = []
centre.append(master[0])
centre.append(master[2])
centre.append(master[7])

print(master)
['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
print(sides)
['middle', 'top', 'bottom']
print(centre)
['first', 'middle', 'inside']

master.remove("middle")

print(master)
['first', 'last', 'top', 'bottom', 'left', 'right', 'inside']
print(sides) # Ideal outcome
['top', 'bottom']
print(centre) # Ideal outcome
['first', 'inside']

Body:
You could use a custom class that subclasses list. This way you can tailor the behavior of .remove:

class Lists(list):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # logic here, for now using the whole passed list
        self.sides = self[:]
        self.center = self[:]

    def remove(self, obj):
        #  TODO catch ValueError that is raised if obj isn't in all of the lists
        super().remove(obj)
        self.sides.remove(obj)
        self.center.remove(obj)

   # probably overriding other methods from list, such as append, so
   # an instance can be used directly to interact with the "master" list

my_lists = Lists(["first", "last", "middle", "top", "bottom", "left", "right", "inside"])

print(my_lists)
my_lists.remove('last')
print(my_lists)
print(my_lists.sides)
print(my_lists.center)

# ['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
# ['first', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
# ['first', 'middle', 'top', 'bottom', 'left', 'right', 'inside']
# ['first', 'middle', 'top', 'bottom', 'left', 'right', 'inside']

You could also better encapsulate .master if needed (as the in-code comment suggests).

However, you may want to rethink the problem and the approach you have chosen to solve it. There might be a better way than keeping sublists of the original list, and you should also keep in mind that .remove will raise an exception if you try to delete a non-existing element from the list.


Title: MYSQL select query based on another tables multiple values

Body:
I have two tables one for units and one for Amenities

Table units
+---------+---------------------+---------------------+-----------+----------+
| unit_id |     date added      |     date modified   | unit name |   user   |
+---------+---------------------+---------------------+-----------+----------+
|       1 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 |  Villa 1  | Smith    |
|       2 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 |  Villa 2  | Smith    |
|       3 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 |  Villa 3  | Jones    |
|       4 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 | Apartment | Smith    |
+---------+---------------------+---------------------+-----------+----------+

Table Amenities
+---------+-----------+-------------------+
|      id |  Unit_id  |   Amenity         |
+---------+-----------+-------------------+
|       1 |         1 |   Air conditions  |
|       2 |         1 |   Internet        |
|       3 |         1 |   Water heaters   |
|       4 |         1 |   TV              |
|       5 |         2 |   TV              |
|       6 |         2 |   pool            |
|       7 |         2 |   Internet        |
|       8 |         3 |   Internet        |
|       9 |         4 |   Internet        |
+---------+-----------+-------------------+

i want to select units where it has both TV and Internet

I try

select units.* from units left join Amenities  on units.unit_id=Amenities.Unit_id

where Amenities.Amenity='TV' and  Amenities.Amenity='Internet'

but not work

Body:
SELECT ua.*
FROM units AS ua
INNER JOIN units AS ub ON ua.unit_id = ub.unit_id
INNER JOIN Amenities AS aa
    ON ua.unit_id = aa.Unit_id
    AND aa.Amenity = 'TV'
INNER JOIN Amenities AS ab
    ON ub.unit_id = ab.Unit_id
    AND ab.Amenity = 'Internet';

Here's the output generated with your data:

+---------+---------------------+---------------------+-----------+-------+
| unit_id | date added          | date modified       | unit name | user  |
+---------+---------------------+---------------------+-----------+-------+
|       1 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 | Villa 1   | Smith |
|       2 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 | Villa 2   | Smith |
+---------+---------------------+---------------------+-----------+-------+


问:
JLabel not greyed out when disabled, when HTML text displayed
How do I get a JLabel displaying a HTML string to appear greyed out (which is the behaviour of JLabels that don't display HTML text)? Is there another way than actually changing the colour myself by modifying the foreground property?

```<code>JLabel label1 = new JLabel("Normal text");
JLabel label2 = new JLabel("<html>HTML <b>text</b>");
// Both labels are now black in colour

label1.setEnabled(false);
label2.setEnabled(false);
// label1 is greyed out, label2 is still black in colour
</code>```

Thank you very much for all of your responses. From what I gather, it seems that Java doesn't support automatic greying out of JLabels when they use HTML text. Suraj's solution has come closest to the fix considering the limitations.

I have however, tried a different out-of-the box approach, where I have put the HTML text JLabels inside of an inner JPanel and did this:

```<code>mInnerPanel.setEnabled(shouldShow); //shouldShow is a boolean value
</code>```

Which hasn't worked. Any suggestions for this way?

EDIT: Added implemented solution.

答:
I would suggest the following, which is combination of two solutions provided here:</p>

```<code>public class HtmlLabel extends JLabel{
    public void setEnabled(boolean enabled){
        if(getClientProperty(BasicHTML.propertyKey) != null ){
            Color foreground = (enabled) ? SystemColor.textText : SystemColor.textInactiveText;
            setForeground(foreground);
        }
        super.setEnabled(enabled);
    }
}
</code>```

Body:
How do I get a JLabel displaying a HTML string to appear greyed out (which is the behaviour of JLabels that don't display HTML text)? Is there another way than actually changing the colour myself by modifying the foreground property?

JLabel label1 = new JLabel("Normal text");
JLabel label2 = new JLabel("HTML text");
// Both labels are now black in colour

label1.setEnabled(false);
label2.setEnabled(false);
// label1 is greyed out, label2 is still black in colour

Thank you very much for all of your responses. From what I gather, it seems that Java doesn't support automatic greying out of JLabels when they use HTML text. Suraj's solution has come closest to the fix considering the limitations.

I have however, tried a different out-of-the box approach, where I have put the HTML text JLabels inside of an inner JPanel and did this:

mInnerPanel.setEnabled(shouldShow); //shouldShow is a boolean value

Which hasn't worked. Any suggestions for this way?

EDIT: Added implemented solution.

Body:
I would suggest the following, which is combination of two solutions provided here:

public class HtmlLabel extends JLabel{
    public void setEnabled(boolean enabled){
        if(getClientProperty(BasicHTML.propertyKey) != null ){
            Color foreground = (enabled) ? SystemColor.textText : SystemColor.textInactiveText;
            setForeground(foreground);
        }
        super.setEnabled(enabled);
    }
}


问:
Pimcore Error(Symfony): No route found for "GET /"

Dont know what to do.. Can someone help me?

答:
You have no default Route. This is outlined in the Symfony docs. Take your time and you will work this out.

https://symfony.com/doc/current/routing.html

Your question lacks the required information to be able to fully understand the problem. When starting out change one thing at a time and take your time.

Good luck.


问:
Draw Floor Plan on canvas using javascript
I want to draw following 2d plan on canvas using javascript.

I have width of each wall with its facing direction. I want to draw each wall in room in clockwise direction. In each room I have to first draw wall having direction similar to Main door direction(In this case it is North West[NW])

Can anybody please help me with some code snippets? I can able to draw walls using lines. But I need algorithm for this.

Following code I have tried till now

```<code>function drawPlan(cnv) {
    var plan = JSON.parse((localStorage.getItem("plan-name")));

    if (!plan)
        return true;

    var start = { x: planCanvas.width/2 - 100, y: planCanvas.height/2 - 100 };

    var canvasRef = document.getElementById('planner-canvas-reference-holder');

    var ctx = canvasRef.getContext('2d');

    //ctx.scale(100, 100);
    var actualWidth;
    var color = "red";

var plotLine = function(s, e, textX, textY) {
    ctx.beginPath();

    ctx.moveTo(s.x, s.y);
    ctx.lineTo(e.x, e.y);
    ctx.lineWidth = 1;

    ctx.font = "20px Times New Roman"
    ctx.textBaseline = "top";
    ctx.fillText(actualWidth, textX, textY, 20);
    ctx.strokeStyle = color;
    ctx.stroke();
    ctx.closePath();
};

var dir = "";
var mainDoorDirection = "N";
var previousDirection = "";
var currentDirection = "";
ep = { x: planCanvas.width/2 - 400, y: planCanvas.height/2 - 200 };

for (var j in plan) {
    var room = plan[j];
    previousDirection = "";
    currentDirection = "";
    dir = "";
    start = ep;
    start.x = start.x + 300;
    start.y = start.y + 100;

    for (var i in room) {

        var wall = room[i];
        var width = parseFloat(wall.width);
        actualWidth = width.toFixed(2);
        width = feetToPixel(width);
        width = width / 100;
        width = Math.floor(width);
        color = wall.color;
        currentDirection = wall.direction;

        var angle = wall.angle;
        var cd = "";

        if ((angle >= 0 && angle <= 22.5) || (angle >= 337.5 && angle < 360))
            cd = "N";

        if ((angle >= 292.5 && angle <= 337.5))
            cd = "NW";

        if ((angle >= 202.5 && angle <= 247.5))
            cd = "SW";

        if ((angle >= 112.5 && angle <= 157.5))
            cd = "SE";

        if ((angle >= 22.5 && angle <= 67.5))
            cd = "NE";
        if ((angle >= 247.5 && angle <= 292.5))
            cd = "W";

        if ((angle >= 157.5 && angle <= 202.5))
            cd = "S";

        if ((angle >= 67.5 && angle <= 112.5))
            cd = "E";

        if (currentDirection !== cd) {
            currentDirection = cd;
        }
        //console.log(i + "== " + cd + " ==== CUrrent == "+currentDirection+ " ==== Prev == "+previousDirection);
        if (dir) {

            if (currentDirection == 'NE' && (previousDirection == 'N' || previousDirection == 'NW')) {
                dir = 'top-bottom';
            }

            if (currentDirection == 'NW' && (previousDirection == 'NE')) {
                dir = 'left-right';
            }

            if (currentDirection == 'E' && (previousDirection == 'NW' || previousDirection == 'N' )) {
                dir = 'top-bottom';
            }
            if (currentDirection == 'S' && (previousDirection == 'W' || previousDirection == 'NE')) {
                dir = 'right-left';
            }
            if (currentDirection == 'W' && (previousDirection == 'S')) {
                dir = 'bottom-top';
            }

            if (currentDirection == 'SW' && (previousDirection == 'S')) {
                dir = 'bottom-top';
            }

            if (currentDirection == 'SE' && (previousDirection == 'W')) {
                dir = 'right-left';
            }

            if (currentDirection == 'SE' && (previousDirection == 'E' || previousDirection == 'NE')) {
                dir = 'right-left';
            }

            if (currentDirection == 'W' && (previousDirection == 'SW' || previousDirection == 'S' || previousDirection == 'SE')) {
                dir = 'bottom-top';
            }
        } else {
            if (mainDoorDirection == 'N')
                dir = "left-right";
        }

        var end = {};

        if (dir == "left-right") {
            end.x = start.x + width;
            end.x = end.x - 10;
            end.y = start.y;

            var textX = start.x + Math.abs((end.x - start.x) / 2) - 5;
            var textY = start.y - 20;
            plotLine(start, end, textX, textY);
            start = end;
            //dir = "top-bottom"
        } else if (dir == 'top-bottom') {
            end.x = start.x;
            end.y = start.y + width;
            end.y = end.y - 10;
            var textX = start.x + 5;
            var textY = start.y + Math.abs((end.y - start.y) / 2) - 5;
            plotLine(start, end, textX, textY);
            start = end;
            //dir = 'right-left';
        } else if (dir == 'right-left') {
            end.x = start.x - width;
            end.x = end.x + 10;
            end.y = start.y;
            var textX = start.x - Math.abs((end.x - start.x) / 2) - 5;
            var textY = start.y + 5;
            plotLine(start, end, textX, textY);
            start = end;
            //dir = 'bottom-top';
        } else if (dir == 'bottom-top') {
            end.x = start.x;
            end.y = start.y - width;
            end.y = end.y + 10;
            var textX = start.x - 22;
            var textY = start.y - Math.abs((end.y - start.y) / 2) - 5;
            plotLine(start, end, textX, textY);
            start = end;
            //dir = 'left-right';
        }
        wall.startPoint = start;
        wall.endPoint = end;
        ep = end;
        previousDirection = currentDirection;
    }
  }
}
</code>```

My json file structures is as follows

```<code>{
  "rcptn": {
    "w1": {"width":12, "direction": "N", "angle": 343, "color": "red"},
    "w2": {"width":10, "direction": "E", "angle": 75, "color": "red"},
    "w3": {"width":12, "direction": "SE", "angle": 153, "color": "red"},
    "w4": {"width":10, "direction": "W", "angle": 251, "color": "red"}
  },
  "Living Room": {
    "w1": { "width": "22", "direction": "NW", "angle": 324, "color": "green"},
    "w2": { "width": "40", "direction": "NE", "angle": 63, "color": "green"},
    "w3": { "width": "4", "direction": "NW", "angle": 324, "color": "green"},
    "w4": { "width": "5", "direction": "E", "angle": 72, "color": "green"},
    "w5": { "width": "14", "direction": "SE", "angle": 152, "color": "green"},
    "w6": { "width": "10", "direction": "W", "angle": 248, "color": "green"},
    "w7": { "width": "2", "direction": "S", "angle": 182, "color": "green"},
    "w8": { "width": "4", "direction": "W", "angle": 249, "color": "green"},
    "w9": { "width": "8", "direction": "SE", "angle": 147, "color": "green"},
    "w10": { "width": "29", "direction": "SW", "angle": 249, "color": "green"}
  },
  "Study Room": {
    "w1": { "width": "12", "direction": "NW", "angle": 328, "color": "blue"},
    "w2": { "width": "20", "direction": "E", "angle": 68, "color": "blue"},
    "w3": { "width": "12", "direction": "SE", "angle": 156, "color": "blue"},
    "w4": { "width": "20", "direction": "W", "angle": 278, "color": "blue"}
  },
  "Kitchen 1": {
    "w1": { "width": "12", "direction": "NW", "angle": 333, "color": "orange"},
    "w2": { "width": "10", "direction": "NE", "angle": 60, "color": "orange"},
    "w3": { "width": "12", "direction": "S", "angle": 158, "color": "orange"},
    "w4": { "width": "10", "direction": "SW", "angle": 246, "color": "orange"}
  }
}
</code>```

答:
I cannot see your coordinate sets, but it is easy to draw and stroke a polygon on canvas.

Make a list of coordinates for each room and loop over them, using beginPath(),closePath() and stroke() to draw them on the canvas.

var canvas = document.body.appendChild(document.createElement("canvas"));
var size = canvas.width = canvas.height = 1000;
var scale = 20;
var ctx = canvas.getContext("2d");
var coordinateSets = [
  //Big room
  [{
      x: 0,
      y: 0
    },
    {
      x: 22,
      y: 0
    },
    {
      x: 22,
      y: 0
    },
    {
      x: 22,
      y: 40
    },
    {
      x: 26,
      y: 40
    },
    {
      x: 26,
      y: 45
    },
    {
      x: 10,
      y: 45
    },
    {
      x: 10,
      y: 33
    },
    {
      x: 8,
      y: 33
    },
    {
      x: 8,
      y: 29
    },
    {
      x: 0,
      y: 29
    },
  ],
  //Little room 1
  [{
      x: 22,
      y: 0
    },
    {
      x: 34,
      y: 0
    },
    {
      x: 34,
      y: 10
    },
    {
      x: 22,
      y: 10
    },
  ],
  //Little room 2
  [{
      x: 22,
      y: 10
    },
    {
      x: 34,
      y: 10
    },
    {
      x: 34,
      y: 30
    },
    {
      x: 22,
      y: 30
    },
  ],
  //Little room 3
  [{
      x: 22,
      y: 30
    },
    {
      x: 34,
      y: 30
    },
    {
      x: 34,
      y: 40
    },
    {
      x: 22,
      y: 40
    },
  ],
];
coordinateSets.forEach(function(coordinates) {
  ctx.beginPath();
  ctx.moveTo(coordinates[0].x * scale, coordinates[0].y * scale);
  coordinates.forEach(function(coordinate) {
    ctx.lineTo(coordinate.x * scale, coordinate.y * scale);
  });
  ctx.closePath();
  ctx.stroke();
});```

Body:
I want to draw following 2d plan on canvas using javascript.

I have width of each wall with its facing direction. I want to draw each wall in room in clockwise direction. In each room I have to first draw wall having direction similar to Main door direction(In this case it is North West[NW])

Can anybody please help me with some code snippets? I can able to draw walls using lines. But I need algorithm for this.

Following code I have tried till now

function drawPlan(cnv) {
    var plan = JSON.parse((localStorage.getItem("plan-name")));

    if (!plan)
        return true;

    var start = { x: planCanvas.width/2 - 100, y: planCanvas.height/2 - 100 };

    var canvasRef = document.getElementById('planner-canvas-reference-holder');

    var ctx = canvasRef.getContext('2d');

    //ctx.scale(100, 100);
    var actualWidth;
    var color = "red";

var plotLine = function(s, e, textX, textY) {
    ctx.beginPath();

    ctx.moveTo(s.x, s.y);
    ctx.lineTo(e.x, e.y);
    ctx.lineWidth = 1;

    ctx.font = "20px Times New Roman"
    ctx.textBaseline = "top";
    ctx.fillText(actualWidth, textX, textY, 20);
    ctx.strokeStyle = color;
    ctx.stroke();
    ctx.closePath();
};

var dir = "";
var mainDoorDirection = "N";
var previousDirection = "";
var currentDirection = "";
ep = { x: planCanvas.width/2 - 400, y: planCanvas.height/2 - 200 };

for (var j in plan) {
    var room = plan[j];
    previousDirection = "";
    currentDirection = "";
    dir = "";
    start = ep;
    start.x = start.x + 300;
    start.y = start.y + 100;

    for (var i in room) {

        var wall = room[i];
        var width = parseFloat(wall.width);
        actualWidth = width.toFixed(2);
        width = feetToPixel(width);
        width = width / 100;
        width = Math.floor(width);
        color = wall.color;
        currentDirection = wall.direction;

        var angle = wall.angle;
        var cd = "";

        if ((angle >= 0 && angle <= 22.5) || (angle >= 337.5 && angle < 360))
            cd = "N";

        if ((angle >= 292.5 && angle <= 337.5))
            cd = "NW";

        if ((angle >= 202.5 && angle <= 247.5))
            cd = "SW";

        if ((angle >= 112.5 && angle <= 157.5))
            cd = "SE";

        if ((angle >= 22.5 && angle <= 67.5))
            cd = "NE";
        if ((angle >= 247.5 && angle <= 292.5))
            cd = "W";

        if ((angle >= 157.5 && angle <= 202.5))
            cd = "S";

        if ((angle >= 67.5 && angle <= 112.5))
            cd = "E";

        if (currentDirection !== cd) {
            currentDirection = cd;
        }
        //console.log(i + "== " + cd + " ==== CUrrent == "+currentDirection+ " ==== Prev == "+previousDirection);
        if (dir) {

            if (currentDirection == 'NE' && (previousDirection == 'N' || previousDirection == 'NW')) {
                dir = 'top-bottom';
            }

            if (currentDirection == 'NW' && (previousDirection == 'NE')) {
                dir = 'left-right';
            }

            if (currentDirection == 'E' && (previousDirection == 'NW' || previousDirection == 'N' )) {
                dir = 'top-bottom';
            }
            if (currentDirection == 'S' && (previousDirection == 'W' || previousDirection == 'NE')) {
                dir = 'right-left';
            }
            if (currentDirection == 'W' && (previousDirection == 'S')) {
                dir = 'bottom-top';
            }

            if (currentDirection == 'SW' && (previousDirection == 'S')) {
                dir = 'bottom-top';
            }

            if (currentDirection == 'SE' && (previousDirection == 'W')) {
                dir = 'right-left';
            }

            if (currentDirection == 'SE' && (previousDirection == 'E' || previousDirection == 'NE')) {
                dir = 'right-left';
            }

            if (currentDirection == 'W' && (previousDirection == 'SW' || previousDirection == 'S' || previousDirection == 'SE')) {
                dir = 'bottom-top';
            }
        } else {
            if (mainDoorDirection == 'N')
                dir = "left-right";
        }

        var end = {};

        if (dir == "left-right") {
            end.x = start.x + width;
            end.x = end.x - 10;
            end.y = start.y;

            var textX = start.x + Math.abs((end.x - start.x) / 2) - 5;
            var textY = start.y - 20;
            plotLine(start, end, textX, textY);
            start = end;
            //dir = "top-bottom"
        } else if (dir == 'top-bottom') {
            end.x = start.x;
            end.y = start.y + width;
            end.y = end.y - 10;
            var textX = start.x + 5;
            var textY = start.y + Math.abs((end.y - start.y) / 2) - 5;
            plotLine(start, end, textX, textY);
            start = end;
            //dir = 'right-left';
        } else if (dir == 'right-left') {
            end.x = start.x - width;
            end.x = end.x + 10;
            end.y = start.y;
            var textX = start.x - Math.abs((end.x - start.x) / 2) - 5;
            var textY = start.y + 5;
            plotLine(start, end, textX, textY);
            start = end;
            //dir = 'bottom-top';
        } else if (dir == 'bottom-top') {
            end.x = start.x;
            end.y = start.y - width;
            end.y = end.y + 10;
            var textX = start.x - 22;
            var textY = start.y - Math.abs((end.y - start.y) / 2) - 5;
            plotLine(start, end, textX, textY);
            start = end;
            //dir = 'left-right';
        }
        wall.startPoint = start;
        wall.endPoint = end;
        ep = end;
        previousDirection = currentDirection;
    }
  }
}

My json file structures is as follows

{
  "rcptn": {
    "w1": {"width":12, "direction": "N", "angle": 343, "color": "red"},
    "w2": {"width":10, "direction": "E", "angle": 75, "color": "red"},
    "w3": {"width":12, "direction": "SE", "angle": 153, "color": "red"},
    "w4": {"width":10, "direction": "W", "angle": 251, "color": "red"}
  },
  "Living Room": {
    "w1": { "width": "22", "direction": "NW", "angle": 324, "color": "green"},
    "w2": { "width": "40", "direction": "NE", "angle": 63, "color": "green"},
    "w3": { "width": "4", "direction": "NW", "angle": 324, "color": "green"},
    "w4": { "width": "5", "direction": "E", "angle": 72, "color": "green"},
    "w5": { "width": "14", "direction": "SE", "angle": 152, "color": "green"},
    "w6": { "width": "10", "direction": "W", "angle": 248, "color": "green"},
    "w7": { "width": "2", "direction": "S", "angle": 182, "color": "green"},
    "w8": { "width": "4", "direction": "W", "angle": 249, "color": "green"},
    "w9": { "width": "8", "direction": "SE", "angle": 147, "color": "green"},
    "w10": { "width": "29", "direction": "SW", "angle": 249, "color": "green"}
  },
  "Study Room": {
    "w1": { "width": "12", "direction": "NW", "angle": 328, "color": "blue"},
    "w2": { "width": "20", "direction": "E", "angle": 68, "color": "blue"},
    "w3": { "width": "12", "direction": "SE", "angle": 156, "color": "blue"},
    "w4": { "width": "20", "direction": "W", "angle": 278, "color": "blue"}
  },
  "Kitchen 1": {
    "w1": { "width": "12", "direction": "NW", "angle": 333, "color": "orange"},
    "w2": { "width": "10", "direction": "NE", "angle": 60, "color": "orange"},
    "w3": { "width": "12", "direction": "S", "angle": 158, "color": "orange"},
    "w4": { "width": "10", "direction": "SW", "angle": 246, "color": "orange"}
  }
}


问:
Count vector elements in range when condition is met
I have a vector of numbers:

```<code>x <- c(0, 0, 0, 30, 60, 0, 0, 0, 0, 0, 10, 0, 0, 15, 45, 0, 0)
</code>```

For each element i in x, I would like to do the following

If x[i] > 0, return 0

If all 4 elements before x[i] are 0, return NA

If the 4 elements before x[i] are not 0, count how many elements are between the last not-0 element and x[i]

I expect this output:

```<code>#> x
#[1]  0  0  0 30 60  0  0  0  0  0 10  0  0 15 45  0  0
#> x_out
#[1] NA NA NA  0  0  1  2  3  4 NA  0  1  2  0  0  1  2
</code>```

Notice that the solution should also work when there are less than 4 elements available at the beginning of the vector (i.e. condition 2 and 3 should use as many elements as are available). Does anybody have a solution for this? A vectorised approach is preferred because the vectors are long and the dataset is fairly big.

答:
Here is a simple Rcpp solution. Create a new C++ file in RStudio and paste the code into it and source the file. Obviously, you'll need to have installed Rtools if you use Windows.

```<code>#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerVector funRcpp(const IntegerVector x) {
  const double n = x.length();
  int counter = 4;
  IntegerVector y(n);

  for (double i = 0; i < n; ++i) {
    if (x(i) > 0) {
      y(i) = 0;
      counter = 0;
    }
    else {
      if (counter > 3) {
        y(i) = NA_INTEGER;
      } else {
        counter++;
        y(i) = counter;
      }
    }
  }

  return y;
}

/*** R
x <- c(0, 0, 0, 30, 60, 0, 0, 0, 0, 0, 10, 0, 0, 15, 45, 0, 0)
funRcpp(x)
*/
</code>```

This returns the desired result:

```<code>> funRcpp(x)
 [1] NA NA NA  0  0  1  2  3  4 NA  0  1  2  0  0  1  2
</code>```

Body:
I have a vector of numbers:

x <- c(0, 0, 0, 30, 60, 0, 0, 0, 0, 0, 10, 0, 0, 15, 45, 0, 0)

For each element i in x, I would like to do the following

If x[i] > 0, return 0

If all 4 elements before x[i] are 0, return NA

If the 4 elements before x[i] are not 0, count how many elements are between the last not-0 element and x[i]

I expect this output:

#> x
#[1]  0  0  0 30 60  0  0  0  0  0 10  0  0 15 45  0  0
#> x_out
#[1] NA NA NA  0  0  1  2  3  4 NA  0  1  2  0  0  1  2

Notice that the solution should also work when there are less than 4 elements available at the beginning of the vector (i.e. condition 2 and 3 should use as many elements as are available). Does anybody have a solution for this? A vectorised approach is preferred because the vectors are long and the dataset is fairly big.

Body:
Here is a simple Rcpp solution. Create a new C++ file in RStudio and paste the code into it and source the file. Obviously, you'll need to have installed Rtools if you use Windows.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerVector funRcpp(const IntegerVector x) {
  const double n = x.length();
  int counter = 4;
  IntegerVector y(n);

  for (double i = 0; i < n; ++i) {
    if (x(i) > 0) {
      y(i) = 0;
      counter = 0;
    }
    else {
      if (counter > 3) {
        y(i) = NA_INTEGER;
      } else {
        counter++;
        y(i) = counter;
      }
    }
  }

  return y;
}

/*** R
x <- c(0, 0, 0, 30, 60, 0, 0, 0, 0, 0, 10, 0, 0, 15, 45, 0, 0)
funRcpp(x)
*/

This returns the desired result:

> funRcpp(x)
 [1] NA NA NA  0  0  1  2  3  4 NA  0  1  2  0  0  1  2


问:
Error prompting to increase project limit while creating new project in Firebase
While trying to add a new project in Firebase, it's showing the warning as:

```<code>You've reached the project limit for your account.
You can add Firebase to an existing project or request an increased limit.

                                                   Request an increase // button
</code>```

Later I checked in Google Developer Console and deleted all existing projects in there. Still this issue persists and I am not able to create a new project in Firebase. Any help is appreciated.

答:
While this is likely answered on the Firebase maximum projects and apps question, the most important parts are from Frank van Puffelen's (a Firebase engineer) comments on the Cannot create new project in Firebase console question:

The projects are pending deletion. It takes a week before they actually are permanently deleted.

There's no limit on the number of projects in general, but there is a limit on the number of projects on an unpaid plan. The exact limit for that varies, from what I understand.

Furthermore, the Cloud Platform Console Help section explains why these limits are in place:

Why are there limits to how many projects I can create?

Quotas protect the Google Cloud Community from unforeseen spikes in usage. However, as your usage of Google Cloud Platform increases, you can request an increase in your quota.

Body:
While trying to add a new project in Firebase, it's showing the warning as:

You've reached the project limit for your account.
You can add Firebase to an existing project or request an increased limit.

                                                   Request an increase // button

Later I checked in Google Developer Console and deleted all existing projects in there. Still this issue persists and I am not able to create a new project in Firebase. Any help is appreciated.


问:
Changing Activity content while starting via Intent
I've a listView with 10 items on it and an activity which contains a textView. I want to start the activity on listView ItemClick but with different textView in it. I am able to start the activity via intent but stuck how to change the value in textView . Is there any way to do this?</p>

```<code>      lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id){

                    switch (position){
                        case 0:
                            Intent myIntent = new Intent(ListActivity.this, Districts.class);
                            ListActivity.this.startActivity(myIntent);
//I want textView to display 'abc'

                        case 1:
                            Intent myIntent = new Intent(ListActivity.this, Districts.class);
                            ListActivity.this.startActivity(myIntent);
//I want textView to display 'xyz'

                    }
                }
            });
</code>```

答:
Pass data to intent </p>

```<code>Intent myIntent = new Intent(ListActivity.this, Districts.class);
myIntent.putExtra("key","value");
ListActivity.this.startActivity(myIntent);
</code>```

<p>and get it in next activity </p>

```<code>Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("key");
    textView.setText(value);
}
</code>```

Body:
I've a listView with 10 items on it and an activity which contains a textView. I want to start the activity on listView ItemClick but with different textView in it. I am able to start the activity via intent but stuck how to change the value in textView . Is there any way to do this?

      lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id){

                    switch (position){
                        case 0:
                            Intent myIntent = new Intent(ListActivity.this, Districts.class);
                            ListActivity.this.startActivity(myIntent);
//I want textView to display 'abc'

                        case 1:
                            Intent myIntent = new Intent(ListActivity.this, Districts.class);
                            ListActivity.this.startActivity(myIntent);
//I want textView to display 'xyz'

                    }
                }
            });

Body:
Pass data to intent

Intent myIntent = new Intent(ListActivity.this, Districts.class);
myIntent.putExtra("key","value");
ListActivity.this.startActivity(myIntent);

and get it in next activity

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("key");
    textView.setText(value);
}


问:
Does yield return work across service boundary?
I have a WCF service with this contract and implementation:

```<code>[OperationContract]
IEnumerable<string> GetData(int value);

public IEnumerable<string> GetData(int value)
{
           int i = 0;
            while (i++ < value)
            {
                Console.WriteLine($"returning {i}th item");
                yield return $" Item:{i}";
            }
        }
}
</code>```

When GetData is called by client the yield does not seem to work. All the items are returned in one go instead of one by one.

答:
Indeed. Because the data is serialized to go over the wire, so the serializer calls the method, materializes the result and writes it to a byte stream to send over the network.

If you'd put that class in the same assembly as your client and call it directly instead of over a service pipeline, it would work.

It does make a lot of sense to not work over serialized connections, one of them being that your other endpoint might not even be .NET at all and might not know that IEnumerable<T> is a special snowflake in terms of execution order.

Body:
I have a WCF service with this contract and implementation:

[OperationContract]
IEnumerable<string> GetData(int value);

public IEnumerable<string> GetData(int value)
{
           int i = 0;
            while (i++ < value)
            {
                Console.WriteLine($"returning {i}th item");
                yield return $" Item:{i}";
            }
        }
}

When GetData is called by client the yield does not seem to work. All the items are returned in one go instead of one by one.


问:
HBase NoServerForRegionException?
I am getting this exception when for a while i didn't communicated with HBase:

org.apache.hadoop.hbase.client.NoServerForRegionException: Timed out trying to locate root region because: Connection refused

is this something related with session expiry, if so, how can i extend session lifetime?

答:
I don't think this has anything to do with session lifetime.

Check your cluster to make sure that it is up and working correctly and all region servers are alive.  Then check the logs to make sure that they are not reporting some error state.

HBase is complex software -- without more detailed information it is very difficult to diagnose what is going on.  And often you can discover the problem by collecting the more detailed information.

Title: HBase NoServerForRegionException?


问:
Retrieving multiple sub queries output with different rows into a single response in postgresql
I'd like to receive the output of a few sub queries(each of them return a single column with different number of rows) into a single response.

I'm trying the following but it doesn't work with error as [21000] ERROR: more than one row returned by a subquery used as an expression.

```<code>SELECT
  (SELECT DISTINCT org_name
   FROM table_1
   WHERE column1= 1)                        AS terminal_1,
  (SELECT org_name
   FROM table_5
   WHERE column5= 1)                          AS cfs_1,
  (SELECT DISTINCT org_name
   FROM table_4 where column7= 136 )     AS terminals_2,
  (SELECT org_name
   FROM table_6
   WHERE column1=7)                           AS cfs_2;
</code>```

I'd like to do in the way such that in future I can add a few more sub-queries, each of which will also return a single column with a different number of rows. Is there a good practice to achieve the same? Thank you.

EDIT 1: The output response could be in any logical form. i.e. tabular or JSON.

答:
What about making us of PostgreSQL's excellent arrays?

```<code>with terminal_1 as (
  SELECT array_agg (DISTINCT org_name) as term1_name
  FROM table_1
  WHERE column1= 1
),
cfs_1 as (
  SELECT array_agg (org_name) as cfs1_name
  FROM table_5
  WHERE column5= 1
),
terminals_2 as (
  SELECT array_agg (DISTINCT org_name) as term2_name
  FROM table_4 where column7= 136
),
cfs_2 as (
  SELECT array_agg (org_name) as cfs2_name
  FROM table_6
  WHERE column1=7
)
select
  term1_name, cfs1_name, term2_name, cfs2_name
from
  terminal_1
  cross join cfs_1
  cross join terminals_2
  cross join cfs_2
</code>```

While this doesn't perform the cosmetics of what you want, I believe it does deliver the content the way you intended.

Body:
I'd like to receive the output of a few sub queries(each of them return a single column with different number of rows) into a single response.

I'm trying the following but it doesn't work with error as [21000] ERROR: more than one row returned by a subquery used as an expression.

SELECT
  (SELECT DISTINCT org_name
   FROM table_1
   WHERE column1= 1)                        AS terminal_1,
  (SELECT org_name
   FROM table_5
   WHERE column5= 1)                          AS cfs_1,
  (SELECT DISTINCT org_name
   FROM table_4 where column7= 136 )     AS terminals_2,
  (SELECT org_name
   FROM table_6
   WHERE column1=7)                           AS cfs_2;

I'd like to do in the way such that in future I can add a few more sub-queries, each of which will also return a single column with a different number of rows. Is there a good practice to achieve the same? Thank you.

EDIT 1: The output response could be in any logical form. i.e. tabular or JSON.

Body:
What about making us of PostgreSQL's excellent arrays?

with terminal_1 as (
  SELECT array_agg (DISTINCT org_name) as term1_name
  FROM table_1
  WHERE column1= 1
),
cfs_1 as (
  SELECT array_agg (org_name) as cfs1_name
  FROM table_5
  WHERE column5= 1
),
terminals_2 as (
  SELECT array_agg (DISTINCT org_name) as term2_name
  FROM table_4 where column7= 136
),
cfs_2 as (
  SELECT array_agg (org_name) as cfs2_name
  FROM table_6
  WHERE column1=7
)
select
  term1_name, cfs1_name, term2_name, cfs2_name
from
  terminal_1
  cross join cfs_1
  cross join terminals_2
  cross join cfs_2

While this doesn't perform the cosmetics of what you want, I believe it does deliver the content the way you intended.


问:
Determine major Java version across all Java releases
When determining the major Java version on Java 8 and before it was common to use the system property java.specification.version, drop 1., and parse the second digit:

on Java 8 this would yield "1.8" ~> "8" ~> 8

on Java 9 the same calls leads to NumberFormatException because the system property is "9"

What is a future-proof way to determine the major Java version? The goal is to get an int that can be if-ed or switch-ed over to decide which code path to take (e.g. in a library to activate a feature).

答:
Alternatively and probably to comply with the 1.5 and above versions only, a simpler way still could be to make use of :</p>

```<code>private static int getMajorVersion() {
    String systemVersionProperty = System.getProperty("java.specification.version");
    return systemVersionProperty.contains(".") ? Integer.parseInt(systemVersionProperty.substring(2)) :
            Integer.parseInt(systemVersionProperty);
}
</code>```

Body:
Alternatively and probably to comply with the 1.5 and above versions only, a simpler way still could be to make use of :

private static int getMajorVersion() {
    String systemVersionProperty = System.getProperty("java.specification.version");
    return systemVersionProperty.contains(".") ? Integer.parseInt(systemVersionProperty.substring(2)) :
            Integer.parseInt(systemVersionProperty);
}