问:
Swift - iOS - Dates and times in different format
I am working for an application written in swift and i want to manipulate dates and times

```<code>let timestamp = NSDateFormatter.localizedStringFromDate(
    NSDate(),
    dateStyle: .ShortStyle,
    timeStyle: .ShortStyle
)
</code>```

returns

```<code>2/12/15, 11:27 PM
</code>```

if I want date and time in a different format, for example the date in a European format like dd/mm/yy and the hours in the 24h format without AM and PM. Is there some function that i can use or i have to use N Strings to reorder the various elements?

答:
This is possibly an old thread but I was working on datetimes recently and was stuck with similar issue so I ended up creating a utility of mine which looks like this,

This utility would take a string date and would return an optional date object

```<code>        func toDate(dateFormat: DateFormatType) -> Date? {
        let formatter = DateFormatter()
        formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
        formatter.dateFormat = dateFormat.rawValue
        let temp = formatter.date(from: self)
        return formatter.date(from: self)
        }
</code>```

the DateFormatType enum looks like this

```<code>        enum DateFormatType : String {
        case type1 = "yyyy-MM-dd - HH:mm:ss"
        case type2 = "dd/MM/yyyy"
        case type3 = "yyyy/MM/dd"
    }
</code>```

One important thing I would like to mention here is the line

formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?

it's very important that you add this line because without this the DateFormatter would use it's default conversions to convert the date and you might end up seeing different dates if you are working with a remote team and get all sorts of issues with data depending on dates.

Hope this helps

Body:
I am working for an application written in swift and i want to manipulate dates and times

let timestamp = NSDateFormatter.localizedStringFromDate(
    NSDate(),
    dateStyle: .ShortStyle,
    timeStyle: .ShortStyle
)

returns

2/12/15, 11:27 PM

if I want date and time in a different format, for example the date in a European format like dd/mm/yy and the hours in the 24h format without AM and PM. Is there some function that i can use or i have to use N Strings to reorder the various elements?

Body:
This is possibly an old thread but I was working on datetimes recently and was stuck with similar issue so I ended up creating a utility of mine which looks like this,

This utility would take a string date and would return an optional date object

        func toDate(dateFormat: DateFormatType) -> Date? {
        let formatter = DateFormatter()
        formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
        formatter.dateFormat = dateFormat.rawValue
        let temp = formatter.date(from: self)
        return formatter.date(from: self)
        }

the DateFormatType enum looks like this

        enum DateFormatType : String {
        case type1 = "yyyy-MM-dd - HH:mm:ss"
        case type2 = "dd/MM/yyyy"
        case type3 = "yyyy/MM/dd"
    }

One important thing I would like to mention here is the line

formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?

it's very important that you add this line because without this the DateFormatter would use it's default conversions to convert the date and you might end up seeing different dates if you are working with a remote team and get all sorts of issues with data depending on dates.

Hope this helps


来源: stackexchange

问:
SQL Server Analysis Services and Team Foundation Server
I am attempting to setup Team Foundation server, however I am running into a problem regarding SQL Server Analysis Services.

The installer gives a warning saying that Analysis Services is not running.  Analysis Services was installed when we installed the version of SQL because we do have the Deployment Wizard etc, however there is not a service showing in the services window that is running.

I tried to run the deployment wizard but it wants me to specify what database to connect to, and I can't create a database because I cant connect to analysis services.

There appears to be something fundamental that I am missing here, if anyone could give me guidance I would much appreciate it.

答: The AD account you install and configure TFS 2010 with has to have administrative privileges in the AS cube.  You should be able to connect to it using SQL Server Management Studio.  It needs these privileges during configuration to create and setup the cube.</p>

ContentLicense: CC BY-SA 3.0


问:
Spring Authentication failure after database restore
EDIT: This issue turns out to have been user error, the passwords had been changed, so the hash was never going to match

I'm using a simple authentication in Spring 4.2.2's toolkit, using a DAO which reads a (Postgres) database table for user's name, password, and authorities

@EnableWebSecurity
@Configuration
class X extends WebSecurityConfigurerAdapter{

    ...
    @Autowired
    private SessionRegistry sessionRegistry;

    @Autowired
    private SessionAuthenticationStrategy sessionAuthenticationStrategy;

    @Override
    protected void configure(HttpSecurity http){
       http.sessionManagement().sessionAuthenticationStrategy(sessionAuthenticationStrategy).maximumSessions(1).sessionRegistry(sessionRegistry).expiredUrl("/login.jsp");

    //presumably unrelated additional code related to matchers, roles, https
    }

    @Bean
    public SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
    }

    @Bean
    public SessionAuthenticationStrategy sessionAuthenticationStrategy(){
        return new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
       return new StandardPasswordEncoder();
    }

   ...
}
```

<p>Recently I restored an old copy of the database, the old database comes from a Redhat 6 server, the new one is CentOS 7, though realistically since this is all database backed, it shouldn't matter. The authentication portion of our code hasn't changed at all, but since I restored the database despite entering the correct credentials I get</p>

```BadCredentialsException: Bad credentials at
org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:98) at
org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:165) at   org.springframework.security.authentication.ProvideManager.authenticate(ProviderManager.java:167) at
....
```

The rest of the stack trace is all more standard spring/catalina/java bits of the stack trace, nothing custom.

It's not expired, I've deleted cookies, it's not disabled....

This code hasn't changed in literal years neither have the backing database tables or Spring libraries. Debugging I can confirm that the correct user is retrieved by username as it goes towards authentication that the user object is correctly constructed with the password hash and authorities.  Since so much of this is done by the default behavior of Spring classes, I can't step through very much of the code as it happens so it's very difficult to identify where the actual bad credentials have occurred and what the heck might have changed.

Googling around, I find many users have problems, but almost of them deal with initial bad configuration.  This isn't such a problem, since this code used to work.

Are there any known gotchas related to Spring security that I might test?

Failing that, how can I triage this further?

答:
Some more things to try:

Verify that the database collation and character-set matches across both old and new environments

Do you have a way within your application (or could you write some simple code to) reset a password then try and login with the newly-reset password (or just write some quick code to generate a new one that you know is correct and then set it directly against the database)? If that works, have a look at the format of the new password against the others in the database.

Wire in your own custom DaoAuthenticationProvider that enables you to set a breakpoint (or just logs to the console/file) the generated vs. database password hash

Implement your own custom StandardPasswordEncoder (from here), but again add more logging/breakpoints

ContentLicense: CC BY-SA 4.0

Body:
EDIT: This issue turns out to have been user error, the passwords had been changed, so the hash was never going to match

I'm using a simple authentication in Spring 4.2.2's toolkit, using a DAO which reads a (Postgres) database table for user's name, password, and authorities

@EnableWebSecurity
@Configuration
class X extends WebSecurityConfigurerAdapter{

    ...
    @Autowired
    private SessionRegistry sessionRegistry;

    @Autowired
    private SessionAuthenticationStrategy sessionAuthenticationStrategy;

    @Override
    protected void configure(HttpSecurity http){
       http.sessionManagement().sessionAuthenticationStrategy(sessionAuthenticationStrategy).maximumSessions(1).sessionRegistry(sessionRegistry).expiredUrl("/login.jsp");

    //presumably unrelated additional code related to matchers, roles, https
    }

    @Bean
    public SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
    }

    @Bean
    public SessionAuthenticationStrategy sessionAuthenticationStrategy(){
        return new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
       return new StandardPasswordEncoder();
    }

   ...
}

Recently I restored an old copy of the database, the old database comes from a Redhat 6 server, the new one is CentOS 7, though realistically since this is all database backed, it shouldn't matter. The authentication portion of our code hasn't changed at all, but since I restored the database despite entering the correct credentials I get

BadCredentialsException: Bad credentials at
org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:98) at
org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:165) at   org.springframework.security.authentication.ProvideManager.authenticate(ProviderManager.java:167) at
....

The rest of the stack trace is all more standard spring/catalina/java bits of the stack trace, nothing custom.

It's not expired, I've deleted cookies, it's not disabled....

This code hasn't changed in literal years neither have the backing database tables or Spring libraries. Debugging I can confirm that the correct user is retrieved by username as it goes towards authentication that the user object is correctly constructed with the password hash and authorities.  Since so much of this is done by the default behavior of Spring classes, I can't step through very much of the code as it happens so it's very difficult to identify where the actual bad credentials have occurred and what the heck might have changed.

Googling around, I find many users have problems, but almost of them deal with initial bad configuration.  This isn't such a problem, since this code used to work.

Are there any known gotchas related to Spring security that I might test?

Failing that, how can I triage this further?


问:
How to test if method with @KafkaListener is being called
I'm really struggling to write a test to check if my Kafka Consumer is being correctly called when messages are sent to it's designated topic.

My consumer:

```<code>@Service
@Slf4j
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class ProcessingConsumer {

  private AppService appService;

  @KafkaListener(
      topics = "${topic}",
      containerFactory = "processingConsumerContainerFactory")
  public void listen(ConsumerRecord<Key, Value> message, Acknowledgment ack) {
    try {
      appService.processMessage(message);
      ack.acknowledge();
    } catch (Throwable t) {
      log.error("error while processing message!", t);
    }
  }
}
</code>```

My consumer config:

```<code>@EnableKafka
@Configuration
public class ProcessingCosumerConfig {

  @Value("${spring.kafka.schema-registry-url}")
  private String schemaRegistryUrl;

  private KafkaProperties props;

  public ProcessingCosumerConfig(KafkaProperties kafkaProperties) {
    this.props = kafkaProperties;
  }

  public Map<String, Object> deserializerConfigs() {
    Map<String, Object> props = new HashMap<>();
    props.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, true);
    props.put(KafkaAvroDeserializerConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl);

    return props;
  }

  private KafkaAvroDeserializer getKafkaAvroDeserializer(Boolean isKey) {
    KafkaAvroDeserializer kafkaAvroDeserializer = new KafkaAvroDeserializer();
    kafkaAvroDeserializer.configure(deserializerConfigs(), isKey);
    return kafkaAvroDeserializer;
  }

  private DefaultKafkaConsumerFactory consumerFactory() {
    return new DefaultKafkaConsumerFactory<>(
        props.buildConsumerProperties(),
        getKafkaAvroDeserializer(true),
        getKafkaAvroDeserializer(false));
  }

  @Bean(name = "processingConsumerContainerFactory")
  public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Key, Value>>
      kafkaListenerContainerFactory() {

    ConcurrentKafkaListenerContainerFactory<Key, Value>
        factory = new ConcurrentKafkaListenerContainerFactory<>();

    factory.setConsumerFactory(consumerFactory());
    factory.getContainerProperties().setAckOnError(false);
    factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
    factory.setErrorHandler(new SeekToCurrentErrorHandler());
    return factory;
  }
}
</code>```

Finally, my (wannabe) test:

```<code>@DirtiesContext
public class ProcessingConsumerTest extends BaseIntegrationTest{

  @Autowired private ProcessingProducerFixture processingProducer;
  @Autowired private ProcessingConsumer processingConsumer;
  @org.springframework.beans.factory.annotation.Value("${topic}")
  String topic;

  @Test
  public void consumer_shouldConsumeMessages_whenMessagesAreSent() throws Exception{
    Thread.sleep(1000);
    ProducerRecord<Key, Value> message = new ProducerRecord<>(topic, new Key("b"), new Value("a", "b", "c", "d"));
    processingProducer.send(message);
  }
}
</code>```

And that's about it for all I have so far.
I've tried checking if this approach gets to the consumer manually using debug and also even just putting simple prints there but the execution simply doesn't seems to get there. Also, if it could be somehow called correctly by my tests, I have no idea what to do to actually assert it in the actual test.

答: Inject a mock AppService into the listener and verify its processMessage() was called.</p>

Body:
I'm really struggling to write a test to check if my Kafka Consumer is being correctly called when messages are sent to it's designated topic.

My consumer:

@Service
@Slf4j
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class ProcessingConsumer {

  private AppService appService;

  @KafkaListener(
      topics = "${topic}",
      containerFactory = "processingConsumerContainerFactory")
  public void listen(ConsumerRecord<Key, Value> message, Acknowledgment ack) {
    try {
      appService.processMessage(message);
      ack.acknowledge();
    } catch (Throwable t) {
      log.error("error while processing message!", t);
    }
  }
}

My consumer config:

@EnableKafka
@Configuration
public class ProcessingCosumerConfig {

  @Value("${spring.kafka.schema-registry-url}")
  private String schemaRegistryUrl;

  private KafkaProperties props;

  public ProcessingCosumerConfig(KafkaProperties kafkaProperties) {
    this.props = kafkaProperties;
  }

  public Map<String, Object> deserializerConfigs() {
    Map<String, Object> props = new HashMap<>();
    props.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, true);
    props.put(KafkaAvroDeserializerConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl);

    return props;
  }

  private KafkaAvroDeserializer getKafkaAvroDeserializer(Boolean isKey) {
    KafkaAvroDeserializer kafkaAvroDeserializer = new KafkaAvroDeserializer();
    kafkaAvroDeserializer.configure(deserializerConfigs(), isKey);
    return kafkaAvroDeserializer;
  }

  private DefaultKafkaConsumerFactory consumerFactory() {
    return new DefaultKafkaConsumerFactory<>(
        props.buildConsumerProperties(),
        getKafkaAvroDeserializer(true),
        getKafkaAvroDeserializer(false));
  }

  @Bean(name = "processingConsumerContainerFactory")
  public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Key, Value>>
      kafkaListenerContainerFactory() {

    ConcurrentKafkaListenerContainerFactory<Key, Value>
        factory = new ConcurrentKafkaListenerContainerFactory<>();

    factory.setConsumerFactory(consumerFactory());
    factory.getContainerProperties().setAckOnError(false);
    factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
    factory.setErrorHandler(new SeekToCurrentErrorHandler());
    return factory;
  }
}

Finally, my (wannabe) test:

@DirtiesContext
public class ProcessingConsumerTest extends BaseIntegrationTest{

  @Autowired private ProcessingProducerFixture processingProducer;
  @Autowired private ProcessingConsumer processingConsumer;
  @org.springframework.beans.factory.annotation.Value("${topic}")
  String topic;

  @Test
  public void consumer_shouldConsumeMessages_whenMessagesAreSent() throws Exception{
    Thread.sleep(1000);
    ProducerRecord<Key, Value> message = new ProducerRecord<>(topic, new Key("b"), new Value("a", "b", "c", "d"));
    processingProducer.send(message);
  }
}

And that's about it for all I have so far.
I've tried checking if this approach gets to the consumer manually using debug and also even just putting simple prints there but the execution simply doesn't seems to get there. Also, if it could be somehow called correctly by my tests, I have no idea what to do to actually assert it in the actual test.


问:
How do I delete a versioned bucket in AWS S3 using the CLI?
I have tried both s3cmd:

```<code>$ s3cmd -r -f -v del s3://my-versioned-bucket/
</code>```

And the AWS CLI:

```<code>$ aws s3 rm s3://my-versioned-bucket/ --recursive
</code>```

But both of these commands simply add DELETE markers to S3. The command for removing a bucket also doesn't work (from the AWS CLI):

```<code>$ aws s3 rb s3://my-versioned-bucket/ --force
Cleaning up. Please wait...
Completed 1 part(s) with ... file(s) remaining
remove_bucket failed: s3://my-versioned-bucket/ A client error (BucketNotEmpty) occurred when calling the DeleteBucket operation: The bucket you tried to delete is not empty. You must delete all versions in the bucket.
</code>```

Ok... how? There's no information in their documentation for this. S3Cmd says it's a 'fully-featured' S3 command-line tool, but it makes no reference to versions other than its own. Is there any way to do this without using the web interface, which will take forever and requires me to keep my laptop on?

答:
This bash script found here:   https://gist.github.com/weavenet/f40b09847ac17dd99d16

worked as is for me.

I saved script as: delete_all_versions.sh and then simply ran:

./delete_all_versions.sh my_foobar_bucket

and that worked without a flaw.

Did not need python or boto or anything.

Body:
I have tried both s3cmd:

$ s3cmd -r -f -v del s3://my-versioned-bucket/

And the AWS CLI:

$ aws s3 rm s3://my-versioned-bucket/ --recursive

But both of these commands simply add DELETE markers to S3. The command for removing a bucket also doesn't work (from the AWS CLI):

$ aws s3 rb s3://my-versioned-bucket/ --force
Cleaning up. Please wait...
Completed 1 part(s) with ... file(s) remaining
remove_bucket failed: s3://my-versioned-bucket/ A client error (BucketNotEmpty) occurred when calling the DeleteBucket operation: The bucket you tried to delete is not empty. You must delete all versions in the bucket.

Ok... how? There's no information in their documentation for this. S3Cmd says it's a 'fully-featured' S3 command-line tool, but it makes no reference to versions other than its own. Is there any way to do this without using the web interface, which will take forever and requires me to keep my laptop on?


问:
Why ggplot2 geom_boxplot gives wrong order results for no reason?
I have been using ggplot2 with geom_boxplot to plot multiple boxplots in one graph. The data looks something like thst below.

```<code>Month   Rainfall

1         45
1         12
1         14
2         65
2         45
2         78
3         10
3         35
3         92
.         .
.         .
.         .
</code>```

So by using boxplot I want to see the boxplot for the values of Rainfall for each group (1,2,3...). The result I am getting is weird and order seems messed up. Any help?

```<code>ggplot(data=edit3)+geom_boxplot(aes(x=Month, y=Rainfall))
</code>```

Note: edit3 is the dataframe with the values of Rainfall and Month.

```<code>dput(head(edit3[,c("Month","Rainfall")],9))
</code>```

```<code>structure(list(Month = c("1", "1", "1", "1", "1", "1", "1", "1",
"2"), Rainfall = c(NA, 135.6, 34.2, 39.4, 134.6, 234.6, 69.6,
92.8, NA)), row.names = c(NA, -9L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

答:
Because your months are like factors, you just need to reorder the factors. Here I used the forcats package for this.

```<code>library(dplyr)
library(forcats)

edit31_1 <- edit3 %>%
  dplyr::mutate(Month = forcats::fct_inorder(Month))

ggplot2::ggplot(edit31_1) +
  geom_boxplot(aes(x = Month, y = Rainfall))
</code>```

Fictitious data used:

```<code>library(ggplot2)

set.seed(1)
edit3 <- data.frame(Month = as.factor(rep(paste(seq(1, 12, 1)), 3)),
                    Rainfall = rnorm(n = 36, mean = 60, sd = 30))

ggplot2::ggplot(edit3) +
  geom_boxplot(aes(x = Month, y = Rainfall))
</code>```

Body:
I have been using ggplot2 with geom_boxplot to plot multiple boxplots in one graph. The data looks something like thst below.

Month   Rainfall

1         45
1         12
1         14
2         65
2         45
2         78
3         10
3         35
3         92
.         .
.         .
.         .

So by using boxplot I want to see the boxplot for the values of Rainfall for each group (1,2,3...). The result I am getting is weird and order seems messed up. Any help?

ggplot(data=edit3)+geom_boxplot(aes(x=Month, y=Rainfall))

Note: edit3 is the dataframe with the values of Rainfall and Month.

dput(head(edit3[,c("Month","Rainfall")],9))

structure(list(Month = c("1", "1", "1", "1", "1", "1", "1", "1",
"2"), Rainfall = c(NA, 135.6, 34.2, 39.4, 134.6, 234.6, 69.6,
92.8, NA)), row.names = c(NA, -9L), class = c("tbl_df", "tbl",
"data.frame"))

Body:
Because your months are like factors, you just need to reorder the factors. Here I used the forcats package for this.

library(dplyr)
library(forcats)

edit31_1 <- edit3 %>%
  dplyr::mutate(Month = forcats::fct_inorder(Month))

ggplot2::ggplot(edit31_1) +
  geom_boxplot(aes(x = Month, y = Rainfall))

Fictitious data used:

library(ggplot2)

set.seed(1)
edit3 <- data.frame(Month = as.factor(rep(paste(seq(1, 12, 1)), 3)),
                    Rainfall = rnorm(n = 36, mean = 60, sd = 30))

ggplot2::ggplot(edit3) +
  geom_boxplot(aes(x = Month, y = Rainfall))


问:
constructing valid CTL or LTL expression (in NuSMV)
I'm trying to create a valid CTL or LTL expression for model checking in NuSMV.

I have a variable in a game, with actors running around trying to catch each other.
Variable is, State_Of_Game : {Win,Lose,Playing}

and I want to express that from every starting state the game can be both won or lost.

So, how would I implement this in CTL or LTL?

I was thinking something like AG (S_O_G = Win | S_O_G = Lose) but don't know how to implement that it is seen from every starting state.

答: Try with this : AF(State_of_Game=Win| State_of_Game=Lose)</p>


问:
__subclassess__() function does not exist
I want to get a list of classes in my class. According to this answer How to find all the subclasses of a class given its name? I should be able to use cls.__subclasses__, but this function does not exist.

I tried the answer to question How to find all the subclasses of a class given its name?

class X:
  class my_subclass:
    pass

x=X()
x.__subclassess__()

# This reports AttributeError 'X' has no attribute '__subclasses__'
```

I would expect to get a dictionary object or the like. But I just get an error message AttributeError 'X' has no attribute '__subclasses__'.

答:
The name of the method is

```<code>__subclasses__
</code>```

You wrote:

```<code>__subclassess__
</code>```

See the extra 's'?

Body:
I want to get a list of classes in my class. According to this answer How to find all the subclasses of a class given its name? I should be able to use cls.__subclasses__, but this function does not exist.

I tried the answer to question How to find all the subclasses of a class given its name?

class X:
  class my_subclass:
    pass

x=X()
x.__subclassess__()

# This reports AttributeError 'X' has no attribute '__subclasses__'

I would expect to get a dictionary object or the like. But I just get an error message AttributeError 'X' has no attribute '__subclasses__'.

Body:
The name of the method is

__subclasses__

You wrote:

__subclassess__

See the extra 's'?


问:
Locking issue with LimitedConcurrencyLevelTaskScheduler and aync/await
I'm struggling to understand what's happening in this simple program.

In the example below I have a task factory that uses the  LimitedConcurrencyLevelTaskScheduler from ParallelExtensionsExtras with maxDegreeOfParallelism set to 2.

I then start 2 tasks that each call an async method (e.g. an async Http request), then gets the awaiter and the result of the completed task.

The problem seem to be that Task.Delay(2000) never completes. If I set maxDegreeOfParallelism to 3 (or greater) it completes. But with maxDegreeOfParallelism = 2 (or less) my guess is that there is no thread available to complete the task. Why is that?

It seems to be related to async/await since if I remove it and simply do Task.Delay(2000).GetAwaiter().GetResult() in DoWork it works perfectly. Does async/await somehow use the parent task's task scheduler, or how is it connected?

```<code>using System;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Schedulers;

namespace LimitedConcurrency
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new TaskSchedulerTest();
            test.Run();
        }
    }

    class TaskSchedulerTest
    {
        public void Run()
        {
            var scheduler = new LimitedConcurrencyLevelTaskScheduler(2);
            var taskFactory = new TaskFactory(scheduler);

            var tasks = Enumerable.Range(1, 2).Select(id => taskFactory.StartNew(() => DoWork(id)));
            Task.WaitAll(tasks.ToArray());
        }

        private void DoWork(int id)
        {
            Console.WriteLine($"Starting Work {id}");
            HttpClientGetAsync().GetAwaiter().GetResult();
            Console.WriteLine($"Finished Work {id}");
        }

        async Task HttpClientGetAsync()
        {
            await Task.Delay(2000);
        }
    }
}
</code>```

Thanks in advance for any help

答:
I think you are encountering a sync deadlock. You are waiting for a thread to complete that is waiting for your thread to complete. Never going to happen. If you make your DoWork method async so you can await the HttpClientGetAsync() call, and you'll avoid the deadlock.

```<code>using MassTransit.Util;
using System;
using System.Linq;
using System.Threading.Tasks;
//using System.Threading.Tasks.Schedulers;

namespace LimitedConcurrency
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new TaskSchedulerTest();
            test.Run();
        }
    }

    class TaskSchedulerTest
    {
        public void Run()
        {
            var scheduler = new LimitedConcurrencyLevelTaskScheduler(2);
            var taskFactory = new TaskFactory(scheduler);

            var tasks = Enumerable.Range(1, 2).Select(id => taskFactory.StartNew(() => DoWork(id)));
            Task.WaitAll(tasks.ToArray());
        }

        private async Task DoWork(int id)
        {
            Console.WriteLine($"Starting Work {id}");
            await HttpClientGetAsync();
            Console.WriteLine($"Finished Work {id}");
        }

        async Task HttpClientGetAsync()
        {
            await Task.Delay(2000);
        }
    }
}
</code>```

https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d

TLDR never call .result, which I'm sure .GetResult(); was doing

Body:
I'm struggling to understand what's happening in this simple program.

In the example below I have a task factory that uses the  LimitedConcurrencyLevelTaskScheduler from ParallelExtensionsExtras with maxDegreeOfParallelism set to 2.

I then start 2 tasks that each call an async method (e.g. an async Http request), then gets the awaiter and the result of the completed task.

The problem seem to be that Task.Delay(2000) never completes. If I set maxDegreeOfParallelism to 3 (or greater) it completes. But with maxDegreeOfParallelism = 2 (or less) my guess is that there is no thread available to complete the task. Why is that?

It seems to be related to async/await since if I remove it and simply do Task.Delay(2000).GetAwaiter().GetResult() in DoWork it works perfectly. Does async/await somehow use the parent task's task scheduler, or how is it connected?

using System;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Schedulers;

namespace LimitedConcurrency
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new TaskSchedulerTest();
            test.Run();
        }
    }

    class TaskSchedulerTest
    {
        public void Run()
        {
            var scheduler = new LimitedConcurrencyLevelTaskScheduler(2);
            var taskFactory = new TaskFactory(scheduler);

            var tasks = Enumerable.Range(1, 2).Select(id => taskFactory.StartNew(() => DoWork(id)));
            Task.WaitAll(tasks.ToArray());
        }

        private void DoWork(int id)
        {
            Console.WriteLine($"Starting Work {id}");
            HttpClientGetAsync().GetAwaiter().GetResult();
            Console.WriteLine($"Finished Work {id}");
        }

        async Task HttpClientGetAsync()
        {
            await Task.Delay(2000);
        }
    }
}

Thanks in advance for any help

Body:
I think you are encountering a sync deadlock. You are waiting for a thread to complete that is waiting for your thread to complete. Never going to happen. If you make your DoWork method async so you can await the HttpClientGetAsync() call, and you'll avoid the deadlock.

using MassTransit.Util;
using System;
using System.Linq;
using System.Threading.Tasks;
//using System.Threading.Tasks.Schedulers;

namespace LimitedConcurrency
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new TaskSchedulerTest();
            test.Run();
        }
    }

    class TaskSchedulerTest
    {
        public void Run()
        {
            var scheduler = new LimitedConcurrencyLevelTaskScheduler(2);
            var taskFactory = new TaskFactory(scheduler);

            var tasks = Enumerable.Range(1, 2).Select(id => taskFactory.StartNew(() => DoWork(id)));
            Task.WaitAll(tasks.ToArray());
        }

        private async Task DoWork(int id)
        {
            Console.WriteLine($"Starting Work {id}");
            await HttpClientGetAsync();
            Console.WriteLine($"Finished Work {id}");
        }

        async Task HttpClientGetAsync()
        {
            await Task.Delay(2000);
        }
    }
}

https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d

TLDR never call .result, which I'm sure .GetResult(); was doing


问:
Bootstrap column width adjustments
I am new to using Bootstrap. I tried adjusting a 3-coulmn row to fit, with the last column divided into another 3, but it overlaps and having difficulty in making it look right.

My cshtml for the 1st row:

```<code> <div class="row">
        <div class="col-md-4 col-sm-4">
            <strong>Last Name</strong> <span class="required">*</span>
            @Html.TextBoxFor(m => m.Patient_Lastname, new { @class = "text-primary", required = "required" })
        </div>
        <div class="col-md-4 col-sm-4">
            <strong>First Name</strong> <span class="required">*</span>
            @Html.TextBoxFor(m => m.Patient_Firstname, new { @class = "text-primary", required = "required" })
        </div>
       <div class="col-md-1 col-sm-1">
            <strong>birth</strong> <span class="required">*</span>
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1900, 119).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Year--", new { @class = "form-control", style = "width: 90px; height:30px;", required = "required" })
        </div>
        <div class="col-md-1 col-sm-1">
            <strong>Month</strong> <span class="required">*</span>
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Month--", new { @class = "form-control", style = "width: 90px; height:30px;", required = "required" })
        </div>
        <div class="col-md-2 col-sm-2">
            <strong>Day</strong> <span class="required">*</span>
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Day--", new { @class = "form-control", style = "width: 80px; height:30px;", required = "required" })
        </div>
    </div>
</code>```

The 2nd and 3rd row are straight forward with col-md-4

Could you help me fix this ?

TIA
Ron.

答:
There is no fixed layout you have to follow so that your screen will look nice automatically! It's your job to try and experiment what's the best to fit your need.

Obviously there is no way for col-sm-1 to fit a dropdown perfectly so you have to think of different layouts for different breakpoints. And bootstrap has many nice CSS classes you can use out of the box already for that purpose.

Extra Small Devices

For extra small devices, you might still be able to put year, month and day dropdown in a single row.

HTML Structure

<form>

Last Name Label & Input

First Name Label & Input

Year Label & Input

Month Label & Input

Day Label & Input

</form>
```
<p>I used <code>.form-row</code> here instead of <code>.row</code> because it gives you tighter gutters between columns.
<code>.form-group</code> is used to give each input group a nice <code>margin-bottom</code>.
Use of <code>.col</code> is to give you auto width.</p>
<h3>How it looks like</h3>
<p><img src="https://i.stack.imgur.com/pKbOn.png" alt="enter image description here" /></p>
<p>Now you have a layout that works for extra small devices. You kind of start building up from this layout for each different devices with different screen sizes and <strong>add</strong> necessary CSS classes.</p>
<h2>Small Devices</h2>
<p>For small devices, you might want to put last name and first name input as 2 columns in a row.</p>
<h3>HTML Structure</h3>
<pre class="lang-html prettyprint-override"><code><form>
    <div class="form-row">
        <div class="form-group col-sm-6">Last Name Label & Input</div>
        <div class="form-group col-sm-6">First Name Label & Input</div>
        <div class="form-group col-sm-12">
            <div class="form-row">
                <div class="form-group col">Year Label & Input</div>
                <div class="form-group col">Month Label & Input</div>
                <div class="form-group col">Day Label & Input</div>
            </div>
        </div>
    </div>
</form>
</code>```

See those .col-sm-* classes are added?

How it looks like

...

...

...

Extra Large Devices

HTML Structure

<form>

Last Name Label & Input

First Name Label & Input

Year Label & Input

Month Label & Input

Day Label & Input

</form>
```

How it looks like

Title: Bootstrap column width adjustments

Body:
I am new to using Bootstrap. I tried adjusting a 3-coulmn row to fit, with the last column divided into another 3, but it overlaps and having difficulty in making it look right.

My cshtml for the 1st row:

            Last Name *
            @Html.TextBoxFor(m => m.Patient_Lastname, new { @class = "text-primary", required = "required" })

            First Name *
            @Html.TextBoxFor(m => m.Patient_Firstname, new { @class = "text-primary", required = "required" })

            birth *
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1900, 119).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Year--", new { @class = "form-control", style = "width: 90px; height:30px;", required = "required" })

            Month *
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Month--", new { @class = "form-control", style = "width: 90px; height:30px;", required = "required" })

            Day *
            @Html.DropDownListFor(m => m.YearOfBirth, Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }),
           "--Day--", new { @class = "form-control", style = "width: 80px; height:30px;", required = "required" })

The 2nd and 3rd row are straight forward with col-md-4

Could you help me fix this ?

TIA
Ron.

Body:
There is no fixed layout you have to follow so that your screen will look nice automatically! It's your job to try and experiment what's the best to fit your need.

Obviously there is no way for col-sm-1 to fit a dropdown perfectly so you have to think of different layouts for different breakpoints. And bootstrap has many nice CSS classes you can use out of the box already for that purpose.

Extra Small Devices

For extra small devices, you might still be able to put year, month and day dropdown in a single row.

HTML Structure

<form>
    <div class="form-row">
        <div class="form-group">Last Name Label & Input</div>
        <div class="form-group">First Name Label & Input</div>
        <div class="form-group">
            <div class="form-row">
                <div class="form-group col">Year Label & Input</div>
                <div class="form-group col">Month Label & Input</div>
                <div class="form-group col">Day Label & Input</div>
            </div>
        </div>
    </div>
</form>

I used .form-row here instead of .row because it gives you tighter gutters between columns.
.form-group is used to give each input group a nice margin-bottom.
Use of .col is to give you auto width.

How it looks like

Now you have a layout that works for extra small devices. You kind of start building up from this layout for each different devices with different screen sizes and add necessary CSS classes.

Small Devices

For small devices, you might want to put last name and first name input as 2 columns in a row.

HTML Structure

<form>
    <div class="form-row">
        <div class="form-group col-sm-6">Last Name Label & Input</div>
        <div class="form-group col-sm-6">First Name Label & Input</div>
        <div class="form-group col-sm-12">
            <div class="form-row">
                <div class="form-group col">Year Label & Input</div>
                <div class="form-group col">Month Label & Input</div>
                <div class="form-group col">Day Label & Input</div>
            </div>
        </div>
    </div>
</form>

See those .col-sm-* classes are added?

How it looks like

...

...

...

Extra Large Devices

HTML Structure

<form>
    <div class="form-row">
        <div class="form-group col-sm-6 col-xl-4">Last Name Label & Input</div>
        <div class="form-group col-sm-6 col-xl-4">First Name Label & Input</div>
        <div class="form-group col-sm-12 col-xl-4">
            <div class="form-row">
                <div class="form-group col">Year Label & Input</div>
                <div class="form-group col">Month Label & Input</div>
                <div class="form-group col">Day Label & Input</div>
            </div>
        </div>
    </div>
</form>

How it looks like


问:
How do you center content in a flexbox
I have images and text, and they are currently are located on the left side of the flexbox.

The issue I'm having is that anything above 1000px in browser size leaves a big open space on the right side. So what I want to do is if the browser width is 1000px or larger center the content so I can get rid of the white space.

I'm having trouble centering these items in my media break. I need help centering for these conditions.

section {
    display: flex;
    flex-flow: wrap;
    align-items: flex-start;

    width: 80%;
    margin: 1em auto;

    border: solid .125em #00aaff;
    background-color: white;
    opacity: 0.9;
}

section > figure {
    flex: 1 1 25%;
    text-align: center;
    align-self: center;
    padding: 1em 0em;

}

section > article {
    flex: 1 1 75%;
    align-self: center;
    line-height: 1.6;
    padding: 1em 0em;
}

figure img {
    width: 75%;
}

@media screen and (min-width:1000px) {
     /*Center the content in the middle of the flexbox*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
        <figure id="image1">
            <img src="images/512x512.png" alt="Dynamo">
        </figure>

        <article>
                <p>Houston Dynamo</p>
                <p>Sport Science/Sport Performance Intern</p>
                <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
        </article>

        <figure>
            <img src="images/UW-Logo.png" alt="Wisconsion">
        </figure>

         <article>
                <p>University of Madison Wisconsin-Madison</p>
                <p>Strength and Conditioning Coach, Graduate Assistant</p>
                <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
        </article></code>```

答:
Use margin: 0 auto to center the section.

section {
  display: flex;
  flex-direction: row;
  width: 100%;
  border: solid .125em #00aaff;
}

@media screen and (min-width: 1000px) {
  section {
    width: 50%;
    margin: 0 auto;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <figure id="image1">
    <img src="//placehold.it/100x100" alt="Dynamo">
  </figure>

  <article>
    <p>Houston Dynamo</p>
    <p>Sport Science/Sport Performance Intern</p>
    <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
  </article>

</section>
<section>
  <figure>
    <img src="//placehold.it/100x100" alt="Wisconsion">
  </figure>

  <article>
    <p>University of Madison Wisconsin-Madison</p>
    <p>Strength and Conditioning Coach, Graduate Assistant</p>
    <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
  </article>
</section></code>```

Title: How do you center content in a flexbox

Body:
I have images and text, and they are currently are located on the left side of the flexbox.

The issue I'm having is that anything above 1000px in browser size leaves a big open space on the right side. So what I want to do is if the browser width is 1000px or larger center the content so I can get rid of the white space.

I'm having trouble centering these items in my media break. I need help centering for these conditions.

section {
    display: flex;
    flex-flow: wrap;
    align-items: flex-start;

    width: 80%;
    margin: 1em auto;

    border: solid .125em #00aaff;
    background-color: white;
    opacity: 0.9;
}

section > figure {
    flex: 1 1 25%;
    text-align: center;
    align-self: center;
    padding: 1em 0em;

}

section > article {
    flex: 1 1 75%;
    align-self: center;
    line-height: 1.6;
    padding: 1em 0em;
}

figure img {
    width: 75%;
}

@media screen and (min-width:1000px) {
     /*Center the content in the middle of the flexbox*/
}

Houston Dynamo

Sport Science/Sport Performance Intern

<time datetime="2018-01-01"></time>January 2019 - Present

University of Madison Wisconsin-Madison

Strength and Conditioning Coach, Graduate Assistant

<time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time>

Body:
Use margin: 0 auto to center the section.

section {
  display: flex;
  flex-direction: row;
  width: 100%;
  border: solid .125em #00aaff;
}

@media screen and (min-width: 1000px) {
  section {
    width: 50%;
    margin: 0 auto;
  }
}

<section>
  <figure id="image1">
    <img src="//placehold.it/100x100" alt="Dynamo">
  </figure>

  <article>
    <p>Houston Dynamo</p>
    <p>Sport Science/Sport Performance Intern</p>
    <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
  </article>

</section>
<section>
  <figure>
    <img src="//placehold.it/100x100" alt="Wisconsion">
  </figure>

  <article>
    <p>University of Madison Wisconsin-Madison</p>
    <p>Strength and Conditioning Coach, Graduate Assistant</p>
    <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
  </article>
</section>


问:
How to make a embed message to be edited later
I'm trying to develop some code that shows the bot when it went online, and let the embed message color change to something else every 2 seconds. (2000ms) But I don't know how, I get an error that says channel.send.edit is not a function or something along those lines.

What I did was...
Create a timeout.
Edit the message, but it'll show a different message / output for the uptime section.
Delete and send a message.

```<code>var myInfo = new discord.RichEmbed()
.setAuthor(`${bot.user.username} is now ONLINE`,`${bot.user.avatarURL}`)
.setDescription(`The bot is now up, please check the following below to see when the bot was online.`)
.addField(`Ready At`,`${bot.readyAt}`,true)
.addField(`Timestamp`,`${bot.readyTimestamp}`,true)
.addField(`Uptime`,`${bot.uptime}`,true)
.setColor(0x008704)
.setFooter('Bot is now online.')
.setThumbnail(`${bot.user.avatarURL}`)

var myInfo2 = new discord.RichEmbed()
.setAuthor(`${bot.user.username} is now ONLINE`,`${bot.user.avatarURL}`)
.setDescription(`The bot is now up, please check the following below to see when the bot was online.`)
.addField(`Ready At`,`${bot.readyAt}`,true)
.addField(`Timestamp`,`${bot.readyTimestamp}`,true)
.addField(`Uptime`,`${bot.uptime}`,true)
.setColor(0x00c13a)
.setFooter('Bot is now online.')
.setThumbnail(`${bot.user.avatarURL}`)

bot.channels.get("523649838693482507").send(myInfo).edit(myInfo2);
</code>```

I expect the bot when it gets online, it'll send the embed message, then 2 seconds later the bot edits the color, and so on.

The output is a bot giving an error, or just not working at all.

答:
You can use the result of message.channel.send(...) by attaching a then() method to the returned promise like so...

message.channel.send(myInfo)
  .then(m => m.edit(myInfo2)) // Note that this will edit the message immediately.
  .catch(console.error);
```

<p>You'll notice I added a <code>catch()</code> method to catch the rejected promises in an event where an error is returned.</p>

<p>Alternatively, you can declare a variable as the fulfilled promise. However, the <code>await</code> keyword can only be in async functions. Here's an example...</p>

<pre class="lang-js prettyprint-override"><code>client.on('message', async message => {
  try {
    const m = await message.channel.send('Hello.');
    await m.edit('Hi again.');
  } catch(err) {
    console.error(err);
  }
});
</code>```

In this case, we can use a try...catch statement instead of individual catch() methods.

For more about promises, see this MDN documentation.

For more about the TextChannel.send() method, see the Discord.js documentation.

Body:
I'm trying to develop some code that shows the bot when it went online, and let the embed message color change to something else every 2 seconds. (2000ms) But I don't know how, I get an error that says channel.send.edit is not a function or something along those lines.

What I did was...
Create a timeout.
Edit the message, but it'll show a different message / output for the uptime section.
Delete and send a message.

var myInfo = new discord.RichEmbed()
.setAuthor(`${bot.user.username} is now ONLINE`,`${bot.user.avatarURL}`)
.setDescription(`The bot is now up, please check the following below to see when the bot was online.`)
.addField(`Ready At`,`${bot.readyAt}`,true)
.addField(`Timestamp`,`${bot.readyTimestamp}`,true)
.addField(`Uptime`,`${bot.uptime}`,true)
.setColor(0x008704)
.setFooter('Bot is now online.')
.setThumbnail(`${bot.user.avatarURL}`)

var myInfo2 = new discord.RichEmbed()
.setAuthor(`${bot.user.username} is now ONLINE`,`${bot.user.avatarURL}`)
.setDescription(`The bot is now up, please check the following below to see when the bot was online.`)
.addField(`Ready At`,`${bot.readyAt}`,true)
.addField(`Timestamp`,`${bot.readyTimestamp}`,true)
.addField(`Uptime`,`${bot.uptime}`,true)
.setColor(0x00c13a)
.setFooter('Bot is now online.')
.setThumbnail(`${bot.user.avatarURL}`)

bot.channels.get("523649838693482507").send(myInfo).edit(myInfo2);

I expect the bot when it gets online, it'll send the embed message, then 2 seconds later the bot edits the color, and so on.

The output is a bot giving an error, or just not working at all.

Body:
You can use the result of message.channel.send(...) by attaching a then() method to the returned promise like so...

message.channel.send(myInfo)
  .then(m => m.edit(myInfo2)) // Note that this will edit the message immediately.
  .catch(console.error);

You'll notice I added a catch() method to catch the rejected promises in an event where an error is returned.

Alternatively, you can declare a variable as the fulfilled promise. However, the await keyword can only be in async functions. Here's an example...

client.on('message', async message => {
  try {
    const m = await message.channel.send('Hello.');
    await m.edit('Hi again.');
  } catch(err) {
    console.error(err);
  }
});

In this case, we can use a try...catch statement instead of individual catch() methods.

For more about promises, see this MDN documentation.

For more about the TextChannel.send() method, see the Discord.js documentation.


问:
Making textinputlayout uneditable and setting click event on it
I want to make textinputlayout uneditable by user and when user click on it i want to perform an action.
I added android:focusable="false" inside edittext of textinputlayout to make it uneditable but now when i click on it it is not getting callback inside onclicklistener of textinputlayout.

```<code>   <android.support.design.widget.TextInputLayout
        android:id="@+id/tipVideoFilePath"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/uploadVideo"
        android:layout_toLeftOf="@+id/uploadVideo">

    <EditText
        android:id="@+id/etVideoFilePath"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/dp5"
        android:singleLine="true"
        android:focusable="false"
        android:hint="@string/videoPath"
        android:textColor="@color/black"/>
</android.support.design.widget.TextInputLayout>
</code>```

答:
I had the same issue for TextInputLayout and TextInputEditText. I wanted to open a dialog.
Changing the TextInputEditText's "clickable" property to true worked for me

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/country_chooser_layout"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:layout_marginBottom="8dp">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/country_chooser"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:drawableEnd="@drawable/ic_expand_arrow"
        android:focusable="false"
        android:hint="Country"
        android:inputType="textCapWords" />
</com.google.android.material.textfield.TextInputLayout>
```
<p>Kotlin :</p>
<pre class="lang-kotlin prettyprint-override"><code>val countryChooser = view.findViewById<TextInputEditText>(R.id.country_chooser)
countryChooser.setOnClickListener { v -> showCountryDialog(v) }
</code>```

Body:
I want to make textinputlayout uneditable by user and when user click on it i want to perform an action.
I added android:focusable="false" inside edittext of textinputlayout to make it uneditable but now when i click on it it is not getting callback inside onclicklistener of textinputlayout.

   <android.support.design.widget.TextInputLayout
        android:id="@+id/tipVideoFilePath"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/uploadVideo"
        android:layout_toLeftOf="@+id/uploadVideo">

    <EditText
        android:id="@+id/etVideoFilePath"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/dp5"
        android:singleLine="true"
        android:focusable="false"
        android:hint="@string/videoPath"
        android:textColor="@color/black"/>
</android.support.design.widget.TextInputLayout>

Body:
I had the same issue for TextInputLayout and TextInputEditText. I wanted to open a dialog.
Changing the TextInputEditText's "clickable" property to true worked for me

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/country_chooser_layout"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:layout_marginBottom="8dp">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/country_chooser"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:drawableEnd="@drawable/ic_expand_arrow"
        android:focusable="false"
        android:hint="Country"
        android:inputType="textCapWords" />
</com.google.android.material.textfield.TextInputLayout>

Kotlin :

val countryChooser = view.findViewById<TextInputEditText>(R.id.country_chooser)
countryChooser.setOnClickListener { v -> showCountryDialog(v) }


问:
NextJS - react-springy-parallax doesn't work
I'm trying to use react-springy-parallax in my NextJS project, but whenever I want to use it, I get the following error message:

Fetch API cannot load webpack://%5Bname%5D_%5Bchunkhash%5D/./node_modules/react-dom/cjs/react-dom.development.js?. URL scheme must be "http" or "https" for CORS request.

Is this is a limitation to react-springy-parallax on NextJS?

Here is the example code I put in my index.js component:

```<code><Parallax ref='parallax' pages={3}>
  <Parallax.Layer offset={0} speed={0.5}>
    <span>Layers can contain anything</span>
  </Parallax.Layer>
</Parallax>
</code>```

It seems the problem has something to do with a CORS issue and I don't know exactly how to approach a solution to this problem.

答:
I've read that this has nothing to do with NextJS in particular. After React 16.8.0 and up, I read that I have to use the useRef function.

Solution:

```<code>import React, { useRef } from 'react'
[...]
const parallax = useRef( 'parallax' )
[...]
<Parallax ref={ parallax } pages={3}>

    <Parallax.Layer offset={0} speed={0.5} onClick={ () => parallax.current.scrollTo(1) }>

        <span>Layers can contain anything</span>

    </Parallax.Layer>

</Parallax>
</code>```

Body:
I'm trying to use react-springy-parallax in my NextJS project, but whenever I want to use it, I get the following error message:

Fetch API cannot load webpack://%5Bname%5D_%5Bchunkhash%5D/./node_modules/react-dom/cjs/react-dom.development.js?. URL scheme must be "http" or "https" for CORS request.

Is this is a limitation to react-springy-parallax on NextJS?

Here is the example code I put in my index.js component:

<Parallax ref='parallax' pages={3}>
  <Parallax.Layer offset={0} speed={0.5}>
    Layers can contain anything
  </Parallax.Layer>
</Parallax>

It seems the problem has something to do with a CORS issue and I don't know exactly how to approach a solution to this problem.

Body:
I've read that this has nothing to do with NextJS in particular. After React 16.8.0 and up, I read that I have to use the useRef function.

Solution:

import React, { useRef } from 'react'
[...]
const parallax = useRef( 'parallax' )
[...]
<Parallax ref={ parallax } pages={3}>

    <Parallax.Layer offset={0} speed={0.5} onClick={ () => parallax.current.scrollTo(1) }>

        <span>Layers can contain anything</span>

    </Parallax.Layer>

</Parallax>


问:
MongoDB Performance Issue at AWS
I have a few questions about MongoDB performance. Thanks in advance for any help.

DB Architecture

The DB has been installed according to instructions at:
https://docs.aws.amazon.com/quickstart/latest/mongodb/step2.html

It has one bastion and three replicas.

The DB is used in a Ruby on Rails 5 app with MongoDB 4.09

Questions

I would like to know if the 'hosts' parameter should include all the replicas or only the primary?

mongoid.yml config

```<code>"mongoid": {
                "production": {
                    "clients": {
                        "default": {
                            "options": {
                                "user": "USER",
                                "password": "PASS****",
                                "auth_source": "admin",
                                "read": {
                                    "mode": "primary_preferred"
                                },
                                "max_pool_size": 200,
                                "min_pool_size": 10,
                                "ssl_verify": false
                            },
                            "database": "pro_db",
                            "hosts": [
                                "PRIMARY_REPLICANODE.3.0.53:27017",
                                "SECONDARY_NODE0.3.62.61:27017",
                                "SECONDARY_NODE1.3.80.80:27017"
                            ]
                        }
                    }
                }
            },
</code>```

What is a good value for max_pool_size? Each Mongo DB node has around 16 GiB of RAM and 2 Virtual CPUS. Are there any other relevant parameters that should be modified from the default?

There is a performance issue on concurrent API requests with different parameters. API requests with the same parameter have an average response of 11 milliseconds, but as soon as a parameter changes and is concurrent the average is 8904 milliseconds. And some timeout. I would like to know what might cause the issue?

API Requests With Same parameter 11 ms

API Requests With Different parameters 8904 ms

答:
All MongoDB hosts should be listed in application configuration. Which server is the primary one changes over time, for example during maintenance. If the application references only one server and this server is restarting, the application will have no way of locating any of the other servers (one of which would likely be the current primary) and may experience an outage.

The driver performs discovery of nodes in the cluster and, if it is able to contact nodes in the seed list (this is the list of servers in the configuration), will then be able to find out about all of the other nodes in the cluster and follow primary changes. But if you happen to restart the application and at that time it is referencing only one server and that server is down, the application will not be able to find the other servers.

Max pool size is the maximum number of open connections that each client will keep around. A 16 GB RAM node should have no issue with 200 open connections. If max pool size is set too low, the application may experience errors as it will be unable to obtain a connection to perform operations.

Note that the max of 200 roughly states that you are expecting to perform about 200 operations concurrently, which - for a typical Rails application - seems unlikely. But, there is nothing wrong with leaving the max at 200.

The specific performance question is not really answerable given the details you provided. Narrow down whether the time is spent in the application or in the database; if it's spent in the database, what the queries are and how they are different. If the time is spent in the application you generally would have to profile the application yourself as there are many possibilities where the time may be going.

Title: MongoDB Performance Issue at AWS

Body:
I have a few questions about MongoDB performance. Thanks in advance for any help.

DB Architecture

The DB has been installed according to instructions at:
https://docs.aws.amazon.com/quickstart/latest/mongodb/step2.html

It has one bastion and three replicas.

The DB is used in a Ruby on Rails 5 app with MongoDB 4.09

Questions

I would like to know if the 'hosts' parameter should include all the replicas or only the primary?

mongoid.yml config

"mongoid": {
                "production": {
                    "clients": {
                        "default": {
                            "options": {
                                "user": "USER",
                                "password": "PASS****",
                                "auth_source": "admin",
                                "read": {
                                    "mode": "primary_preferred"
                                },
                                "max_pool_size": 200,
                                "min_pool_size": 10,
                                "ssl_verify": false
                            },
                            "database": "pro_db",
                            "hosts": [
                                "PRIMARY_REPLICANODE.3.0.53:27017",
                                "SECONDARY_NODE0.3.62.61:27017",
                                "SECONDARY_NODE1.3.80.80:27017"
                            ]
                        }
                    }
                }
            },

What is a good value for max_pool_size? Each Mongo DB node has around 16 GiB of RAM and 2 Virtual CPUS. Are there any other relevant parameters that should be modified from the default?

There is a performance issue on concurrent API requests with different parameters. API requests with the same parameter have an average response of 11 milliseconds, but as soon as a parameter changes and is concurrent the average is 8904 milliseconds. And some timeout. I would like to know what might cause the issue?

API Requests With Same parameter 11 ms

API Requests With Different parameters 8904 ms


问:
Firefox debugger breakpoint not working
When I click on a line to set a break point, the break point line gets highlighted, then the break point highlight disappears. </p>

<p>Other than that, Firefox developer debug has been working fine. </p>

答:
I ran into this problem, or a variant of it as well. For me, it was because webpack was defaulting to setting devtool to "eval". This broke stopping at breakpoints in Firefox for me. Changing that setting to "source-map" resolved the issue, though I suspect most other non-eval options would work fine as well.

I noticed this because I looked in the generated JS file and noticed everything was put into eval() calls.

Title: Firefox debugger breakpoint not working

Body:
When I click on a line to set a break point, the break point line gets highlighted, then the break point highlight disappears.

Other than that, Firefox developer debug has been working fine.


问:
How to store a variable in an array in a different file
What I've done/tried so far:

I've created a file called links.js which contains a single array.

I've got my main file (index.js) which you run and it scrapes URLs;

I need to save the URL in links.js in the format I created so I can run the second part of my program which requires links.js in a specific format and uses the URLs gathered from my index.js

I've tried fs and creating streams etc but I'm still learning nodejs so I don't really understand it and can't find an issue on stack similar enough to figure out what to do..

Overview of format required for the links.js file expanding the url array each time with another url from index.js:
This is the links.js array format I need it in as an example

```<code>url = ['url1.com','url2.com','url3.com'];

module.exports{url:url};
</code>```

How would I code my index.js so it stores my variable in the format above in links.js (a different file from the one I'm in)?

my index.js currently stores the url in test2[1]

I'm able to verify that's what I want to store by doing console.log(test2[1]);

Sorry if that's hard to understand I'm not sure how to explain it much better but if you're confused about something let me know and I'll try and reword it!

Thanks for any help :)

Expectations/Desired Outcomes:

I expect test2[1] to return http://example.com on index.js

I expext index.js to then save test2[1] and put it in links.js but keeping the format of links.js as explained and shown above.

I expect it to not be overwritten as index uses pupeteer and loops through to get website URLs and each would need to be saved all in the single links.js folder just expanding the arrays size.

答:
You can save it as a json file.

```<code>const fs = require('fs')
const file = "./urls.json"

const urls = require(file )

//Here you update urls array
urls.push("url4.com")

fs.writeFileSync(file, JSON.stringify(urls))
</code>```

urls.json

```<code>["url1.com","url2.com","url3.com", "url4.com"]
</code>```

Body:
What I've done/tried so far:

I've created a file called links.js which contains a single array.

I've got my main file (index.js) which you run and it scrapes URLs;

I need to save the URL in links.js in the format I created so I can run the second part of my program which requires links.js in a specific format and uses the URLs gathered from my index.js

I've tried fs and creating streams etc but I'm still learning nodejs so I don't really understand it and can't find an issue on stack similar enough to figure out what to do..

Overview of format required for the links.js file expanding the url array each time with another url from index.js:
This is the links.js array format I need it in as an example

url = ['url1.com','url2.com','url3.com'];

module.exports{url:url};

How would I code my index.js so it stores my variable in the format above in links.js (a different file from the one I'm in)?

my index.js currently stores the url in test2[1]

I'm able to verify that's what I want to store by doing console.log(test2[1]);

Sorry if that's hard to understand I'm not sure how to explain it much better but if you're confused about something let me know and I'll try and reword it!

Thanks for any help :)

Expectations/Desired Outcomes:

I expect test2[1] to return http://example.com on index.js

I expext index.js to then save test2[1] and put it in links.js but keeping the format of links.js as explained and shown above.

I expect it to not be overwritten as index uses pupeteer and loops through to get website URLs and each would need to be saved all in the single links.js folder just expanding the arrays size.

Body:
You can save it as a json file.

const fs = require('fs')
const file = "./urls.json"

const urls = require(file )

//Here you update urls array
urls.push("url4.com")

fs.writeFileSync(file, JSON.stringify(urls))

urls.json

["url1.com","url2.com","url3.com", "url4.com"]


问:
How to store an array as a value of a key in another array in PHP?
I am trying to store an array as a value of a key in another array.
I can't use functions like array_push() or a for loop because the second array is being created as a parameter of a function.

I've googled for hours and can't find any answers! I'm new to PHP so I have no idea if this is even possible.

The first array is something like:

    $choices[] = array('1'=>'Blue','2'=>'Red)
```

<p>EDIT: <em>this is the code I meant to add</em></p>

<pre class="lang-php prettyprint-override"><code>    $choices[] = array('1'=>'Blue','2'=>'Red');
</code>```

The lack of ' and ; were a typo. The array is being created in a much more complex way. In my attempt to abstract and simplify it to post it here I missed the ' and ; . Kudos to @diéfani-favareto-piovezan for spotting that.

Now I want to insert this array as a value of a key in another array that is being created in another part of the code:

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' =>  ,
                                  )

                          )
```

<p>I want array <code>$choices</code> to be the value of key <code>'c'</code>.</p>

<p>I tried this </p>

<pre class="lang-php prettyprint-override"><code>     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  ),

                          )
</code>```

but it gives me an error

EDIT: I meant to say that I tried this

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  )

                          )
```

<p><em>Once again, when trying to abstract and simplify (the actual array created in the RandomFunction has about 250 lines) I added the extra comma by mistake. Kudos to @brevis, @Nick and @tim for spotting this and bringing it to my attention.</em></p>

<pre class="lang-php prettyprint-override"><code>    Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' in /filename.php line 120
</code>```

The error mentions another line down the code, but I know that it is not the cause because if I remove

                                   'c' => $choices,
```

<p>there is no error.</p>

<p>EDIT: <em>I meant to say "before I added the <code>'c'</code> line" (and not "if I remove it" ), there were no errors. I also could have added that the creation of <code>$choices</code> comes before the <code>randomFunction</code> array, so that's another reason why I knew there were no errors there.</em></p>

<p><em>CONCLUSION:
As I mentioned, the error was an extra <code>),</code> after the <code>'c'</code> line, which I failed to reproduce here when trying to simplify the code. I think that when I added the <code>'c'</code> line in my actual code I must have added an extra <code>),</code> by mistake. I was only able to find that because @nick said that the <code>randomFunction</code> code (the one after "I tried this") should be working. That was the answer I needed to confirm that the error was not on that line. Thanks to to @dont-panic's comment, I looked more carefully into the error message I was getting and found the extra <code>)'</code>. At the end of the day, eveybody helped me. So thank you all!</em></p>

<p><em>To anyone who has come across this, the working code is</em>:</p>

<pre class="lang-php prettyprint-override"><code>    $choices[] = array('1'=>'Blue','2'=>'Red');

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  )

                          );
</code>```

*

答:
ok, I found the error:

I was adding an extra ), at the end of the second array.

The working code is

```<code>$choices[] = array('1'=>'Blue','2'=>'Red');

 return randomFunction('random text', array(
                               'a' => 'apple',
                               'b' => 'banana',
                               'c' => $choices,
                              )

                      );
</code>```

Body:
I am trying to store an array as a value of a key in another array.
I can't use functions like array_push() or a for loop because the second array is being created as a parameter of a function.

I've googled for hours and can't find any answers! I'm new to PHP so I have no idea if this is even possible.

The first array is something like:

    $choices[] = array('1'=>'Blue','2'=>'Red)

EDIT: this is the code I meant to add

    $choices[] = array('1'=>'Blue','2'=>'Red');

The lack of ' and ; were a typo. The array is being created in a much more complex way. In my attempt to abstract and simplify it to post it here I missed the ' and ; . Kudos to @diéfani-favareto-piovezan for spotting that.

Now I want to insert this array as a value of a key in another array that is being created in another part of the code:

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' =>  ,
                                  )

                          )

I want array $choices to be the value of key 'c'.

I tried this

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  ),

                          )

but it gives me an error

EDIT: I meant to say that I tried this

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  )

                          )

Once again, when trying to abstract and simplify (the actual array created in the RandomFunction has about 250 lines) I added the extra comma by mistake. Kudos to @brevis, @Nick and @tim for spotting this and bringing it to my attention.

    Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' in /filename.php line 120

The error mentions another line down the code, but I know that it is not the cause because if I remove

                                   'c' => $choices,

there is no error.

EDIT: I meant to say "before I added the 'c' line" (and not "if I remove it" ), there were no errors. I also could have added that the creation of $choices comes before the randomFunction array, so that's another reason why I knew there were no errors there.

CONCLUSION:
As I mentioned, the error was an extra ), after the 'c' line, which I failed to reproduce here when trying to simplify the code. I think that when I added the 'c' line in my actual code I must have added an extra ), by mistake. I was only able to find that because @nick said that the randomFunction code (the one after "I tried this") should be working. That was the answer I needed to confirm that the error was not on that line. Thanks to to @dont-panic's comment, I looked more carefully into the error message I was getting and found the extra )'. At the end of the day, eveybody helped me. So thank you all!

To anyone who has come across this, the working code is:

    $choices[] = array('1'=>'Blue','2'=>'Red');

     return randomFunction('random text', array(
                                   'a' => 'apple',
                                   'b' => 'banana',
                                   'c' => $choices,
                                  )

                          );

*

Body:
ok, I found the error:

I was adding an extra ), at the end of the second array.

The working code is

$choices[] = array('1'=>'Blue','2'=>'Red');

 return randomFunction('random text', array(
                               'a' => 'apple',
                               'b' => 'banana',
                               'c' => $choices,
                              )

                      );


问:
How to remove the square brackets around a JSON in PHP
How can I have the php script return json without the square brackets? I am also getting the INT values back with double quotes for some reason. Is it possible to remove those as well?

What I am getting now:

```<code>[{"id":"1","name":"Jack","username":"Jack1","age":"23"}]
</code>```

What I would like:

```<code>{"id": 1,"name":"Jack","username":"Jack1","age":23}
</code>```

The following is the php script that returns the JSON:

```<code><?php

$con = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT username, name FROM DriverInfo WHERE (username = '$username') and password = '$password' ";

// Check if there are results
if ($result = mysqli_query($con, $sql)) {
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    while ($row = $result->fetch_object()) {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);
</code>```

答: The json you want is in a single element php array, so try doing echo json_encode($resultArray[0]). Also if you're expecting an int back and you know where, just use parseInt() in your javascript when handling the response

Body:
How can I have the php script return json without the square brackets? I am also getting the INT values back with double quotes for some reason. Is it possible to remove those as well?

What I am getting now:

[{"id":"1","name":"Jack","username":"Jack1","age":"23"}]

What I would like:

{"id": 1,"name":"Jack","username":"Jack1","age":23}

The following is the php script that returns the JSON:

<?php

$con = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT username, name FROM DriverInfo WHERE (username = '$username') and password = '$password' ";

// Check if there are results
if ($result = mysqli_query($con, $sql)) {
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    while ($row = $result->fetch_object()) {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);


问:
Why does PyCharm propose to change method to static?
The new pycharm release (3.1.3 community edition) proposes to convert the methods that don't work with the current object's state to static.

What is the practical reason for that? Some kind of micro-performance(-or-memory)-optimization?

答:
It might be a bit messy, but sometimes you just don't need to access self, but you would prefer to keep the method in the class and not make it static. Or you just want to avoid adding a bunch of unsightly decorators. Here are some potential workarounds for that situation.

If your method only has side effects and you don't care about what it returns:

```<code>def bar(self):
    doing_something_without_self()
    return self
</code>```

If you do need the return value:

```<code>def bar(self):
    result = doing_something_without_self()
    if self:
        return result
</code>```

Now your method is using self, and the warning goes away!

Body:
It might be a bit messy, but sometimes you just don't need to access self, but you would prefer to keep the method in the class and not make it static. Or you just want to avoid adding a bunch of unsightly decorators. Here are some potential workarounds for that situation.

If your method only has side effects and you don't care about what it returns:

def bar(self):
    doing_something_without_self()
    return self

If you do need the return value:

def bar(self):
    result = doing_something_without_self()
    if self:
        return result

Now your method is using self, and the warning goes away!


答:
You are building an array of the resulting rows from your mysql query. The square brackets are there because that is the notation for an array in JSON. It looks like you only want to return the first row, so you don't need that while statement:

```<code>$row = $result->fetch_object();
if ($row) {
    echo json_encode($row);
} else {
    echo '{}';
}
</code>```

Also you'll want to be aware of this: How can I prevent SQL injection in PHP?

Title: How to remove the square brackets around a JSON in PHP

Body:
You are building an array of the resulting rows from your mysql query. The square brackets are there because that is the notation for an array in JSON. It looks like you only want to return the first row, so you don't need that while statement:

$row = $result->fetch_object();
if ($row) {
    echo json_encode($row);
} else {
    echo '{}';
}

Also you'll want to be aware of this: How can I prevent SQL injection in PHP?


问:
Javascript error when html passed in JSON packet
I am going mad trying to resolve this issue. I have implemented a Coldfusion Ajax-like File Upload that uploads a file using a hidden frame and then grabs the contents returned by the frame. It is based on this article: http://www.bennadel.com/blog/1244-ColdFusion-jQuery-And-AJAX-File-Upload-Demo.htm

So, everything is working great, EXCEPT when I send back HTML in the data. So, if you look in the code below, I have provided the action page that streams data back to the hidden frame. The first line works, the second line with html does not.

```<code>    <!--- Create the return HTML. Remember, we are going to be treating the BODY of the returned document as if it were a JSON string. --->
    <cfsavecontent variable="strHTML">

        <cfset var sResponse = {} />
        <!--- THIS WORKS --->
        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = "Hello World", RETURNID=""} />
        <!--- THIS DOES NOT WORK --->
        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = #HtmlEditFormat('<div>Hello World</div>')#", RETURNID=""} />

        <cfoutput>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html>
            <head></head>
            <body>#SerializeJSON( sResponse )#</body>
            </html>
        </cfoutput>
    </cfsavecontent>

<!--- Create binary response data. --->
<cfset binResponse = ToBinary( ToBase64( strHTML ) ) />

<!--- Tell the client how much data to expect. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<!--- Stream the "plain text" back to the client .--->
<cfcontent type="text/html" variable="#binResponse#" />
</code>```

The javascript for doing all of this is below. The line that it errors on when HTML is passed back is:

// Assuming that our return data is in JSON format, evaluate the body html to get our return data.
var objData = eval( "(" + jBody.html() + ")" );

```<code>//ShareForm Photo Upload Form Process (simulated Ajax)
$(document).ready(function() {
    // Attach an event to the submit method. Instead of submitting the actual form to the primary page, we are going to be submitting the form to a hidden iFrame that we dynamically create.
    $( "#frmShareForm" ).submit(
        function( objEvent ){
            var jThis = $( this );
            var photoUploadAction = $("#photoUploadAction").val();

            // Create a unique name for our iFrame. We can do this by using the tick count from the date.
            var strName = ("uploader" + (new Date()).getTime());

            // Create an iFrame with the given name that does not point to any page - we can use the address "about:blank" to get this to happen.
            var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" );

            // We now have an iFrame that is not attached to the document. Before we attach it, let's make sure it will not be seen.
            jFrame.css( "display", "none" );

            // Since we submitting the form to the iFrame, we will want to be able to get back data from the form submission.
            // To do this, we will have to set up an event listener for the LOAD event of the iFrame.
            jFrame.load(
                function( objEvent ){
                    // Get a reference to the body tag of the loaded iFrame. We are doing to assume that this element will contain our return data in JSON format.
                    var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];

                    // Get a jQuery object of the body so that we can have better access to it.
                    var jBody = $( objUploadBody );

                    // Assuming that our return data is in JSON format, evaluate the body html to get our return data.
                    var objData = eval( "(" + jBody.html() + ")" );
                    alert(objData);

                    // A JSON-format struct is returned that will be used to do callback functionality
                    SharePhotoAjaxResponseHandler(objData);

                    // Remove the iFrame from the document. Because FireFox has some issues with "Infinite thinking", let's put a small delay on the frame removal.
                    setTimeout
                    (
                        function()
                        {
                            jFrame.remove();
                        }, 100
                    );
                }
            );

            // Attach to body.
            $( "body:first" ).append( jFrame );

            // Now that our iFrame it totally in place, hook up the frame to post to the iFrame.
            jThis
                .attr( "action",  photoUploadAction)
                .attr( "method", "post" )
                .attr( "enctype", "multipart/form-data" )
                .attr( "encoding", "multipart/form-data" )
                .attr( "target", strName );
    });
});
</code>```

The javascript error I get is usually something like:
"unterminated regular expression literal"

I have also tried removing the SerialiseJson on the CFM page, and the eval in the javascript, which both result in other js errors. I have also tried removing the surrounding html as well as change .html() to .text(), remove the eval() and combinations of all of them. No luck.

Please can someone tell me what the problem is. I know I can't be far off as it works without html.

Thanks

UPDATE: I ran the JSON output that Coldfusion generates through the JSON validator and it failed, due to (from what I can see) the double quotation marks:

```<code>{""RETURNID"":"""",""DATA"":""<div>Hello World<\/div>"",""SUCCESS"":true,""ERRORS"":[]}
</code>```

Now I really don't know why Coldfusion is doing double quotations?? Anyone have any ideas?

答:
You are shoving JSON into the  of an HTML document.

The browser will interpret it as HTML, and perform error correction over it (doing things like convert & to & and discarding elements that aren't allowed in places you have put them.

You then pull it out using jQuery's html() method, which will get the HTML source and not the text you want.

The solution is therefore:

Encode any entities in the JSON. You need an HTML representation of the JSON string, not the raw string. I've no idea how to do this in CF but there must be an equivalent to encode_entities / htmlspecialchars / etc

Get the text() not the html()

(BTW: That is everything you need to do, not a list of alternatives)

Body:
I am going mad trying to resolve this issue. I have implemented a Coldfusion Ajax-like File Upload that uploads a file using a hidden frame and then grabs the contents returned by the frame. It is based on this article: http://www.bennadel.com/blog/1244-ColdFusion-jQuery-And-AJAX-File-Upload-Demo.htm

So, everything is working great, EXCEPT when I send back HTML in the data. So, if you look in the code below, I have provided the action page that streams data back to the hidden frame. The first line works, the second line with html does not.

    <cfsavecontent variable="strHTML">

        <cfset var sResponse = {} />

        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = "Hello World", RETURNID=""} />

        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = #HtmlEditFormat('
Hello World
')#", RETURNID=""} />

        <cfoutput>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

            #SerializeJSON( sResponse )#

        </cfoutput>
    </cfsavecontent>

<cfset binResponse = ToBinary( ToBase64( strHTML ) ) />

<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<cfcontent type="text/html" variable="#binResponse#" />

The javascript for doing all of this is below. The line that it errors on when HTML is passed back is:

// Assuming that our return data is in JSON format, evaluate the body html to get our return data.
var objData = eval( "(" + jBody.html() + ")" );

//ShareForm Photo Upload Form Process (simulated Ajax)
$(document).ready(function() {
    // Attach an event to the submit method. Instead of submitting the actual form to the primary page, we are going to be submitting the form to a hidden iFrame that we dynamically create.
    $( "#frmShareForm" ).submit(
        function( objEvent ){
            var jThis = $( this );
            var photoUploadAction = $("#photoUploadAction").val();

            // Create a unique name for our iFrame. We can do this by using the tick count from the date.
            var strName = ("uploader" + (new Date()).getTime());

            // Create an iFrame with the given name that does not point to any page - we can use the address "about:blank" to get this to happen.
            var jFrame = $( "" );

            // We now have an iFrame that is not attached to the document. Before we attach it, let's make sure it will not be seen.
            jFrame.css( "display", "none" );

            // Since we submitting the form to the iFrame, we will want to be able to get back data from the form submission.
            // To do this, we will have to set up an event listener for the LOAD event of the iFrame.
            jFrame.load(
                function( objEvent ){
                    // Get a reference to the body tag of the loaded iFrame. We are doing to assume that this element will contain our return data in JSON format.
                    var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];

                    // Get a jQuery object of the body so that we can have better access to it.
                    var jBody = $( objUploadBody );

                    // Assuming that our return data is in JSON format, evaluate the body html to get our return data.
                    var objData = eval( "(" + jBody.html() + ")" );
                    alert(objData);

                    // A JSON-format struct is returned that will be used to do callback functionality
                    SharePhotoAjaxResponseHandler(objData);

                    // Remove the iFrame from the document. Because FireFox has some issues with "Infinite thinking", let's put a small delay on the frame removal.
                    setTimeout
                    (
                        function()
                        {
                            jFrame.remove();
                        }, 100
                    );
                }
            );

            // Attach to body.
            $( "body:first" ).append( jFrame );

            // Now that our iFrame it totally in place, hook up the frame to post to the iFrame.
            jThis
                .attr( "action",  photoUploadAction)
                .attr( "method", "post" )
                .attr( "enctype", "multipart/form-data" )
                .attr( "encoding", "multipart/form-data" )
                .attr( "target", strName );
    });
});

The javascript error I get is usually something like:
"unterminated regular expression literal"

I have also tried removing the SerialiseJson on the CFM page, and the eval in the javascript, which both result in other js errors. I have also tried removing the surrounding html as well as change .html() to .text(), remove the eval() and combinations of all of them. No luck.

Please can someone tell me what the problem is. I know I can't be far off as it works without html.

Thanks

UPDATE: I ran the JSON output that Coldfusion generates through the JSON validator and it failed, due to (from what I can see) the double quotation marks:

{""RETURNID"":"""",""DATA"":""
Hello World<\/div>"",""SUCCESS"":true,""ERRORS"":[]}

Now I really don't know why Coldfusion is doing double quotations?? Anyone have any ideas?

Body:
You are shoving JSON into the <body> of an HTML document.

The browser will interpret it as HTML, and perform error correction over it (doing things like convert & to &amp; and discarding elements that aren't allowed in places you have put them.

You then pull it out using jQuery's html() method, which will get the HTML source and not the text you want.

The solution is therefore:

Encode any entities in the JSON. You need an HTML representation of the JSON string, not the raw string. I've no idea how to do this in CF but there must be an equivalent to encode_entities / htmlspecialchars / etc

Get the text() not the html()

(BTW: That is everything you need to do, not a list of alternatives)


问:
Python multiprocessing, cannot iterate with pool.map
I have a 32 core machine with 256gb ram and am new to parallel computing.
I have to run this line:

```<code>Flag=data.flag [:,:,x]
</code>```

which is a very large matrix. "x" refers to the sub-matrix that I want to store to file. But "changes" 64 times and each iteration takes +- 8min, hence the need to parallelize it

I've looked at a few examples:
https://www.machinelearningplus.com/python/parallel-processing-python/
and
https://docs.python.org/3.7/library/multiprocessing.html#multiprocessing-programming

Function for code:

```<code>def multi_flagger(antenna_no):
    recv=data.corr_products[antenna_no][0]         # Gets the antenna name and polarization value
    flagger=data.flags[:, :, antenna_no]         # Flags the data based on the antenna value
    mat_flag = np.matrix(flagger)                # Morphs the 2d array into a matrix
    np.save('Flagged_data_'+str(recv)+'_.npy', mat_flag)  # Saves the data to a file

pool.map(multi_flagger, for i in range(2))
pool.close()
</code>```

I get this error:

```<code>File "<ipython-input-58-e1a6f9779b9a>", line 1
   pool.map(multi_flagger, for i in range(2))
                             ^ SyntaxError: invalid syntax`
</code>```

What I would like is 64 .npy files written to disk

答:
The method Pool.map(func, iterable) expects an iterable, which can be a tuple or a list. You cannot pass a for loop as what you have tried (for i in range(2)), but you can instead pass a list of numbers from a range:

```<code>pool.map(multi_flagger, list(range(2)))  # [0, 1]
</code>```

I'm not sure about the rest of your code, but when using a Pool, you set the number of worker processes when you create the Pool instance (as explained in the Using a pool of workers example) and then call map to pass in the function to execute and the function inputs:

```<code>def multi_flagger(antenna_no):
    recv=data.corr_products[antenna_no][0]
    flagger=data.flags[:, :, antenna_no]
    mat_flag = np.matrix(flagger)
    np.save('Flagged_data_'+str(recv)+'_.npy', mat_flag)

with Pool(processes=3) as pool:               # set the number of worker processes
    pool.map(multi_flagger, list(range(2)))   # pass a list of antenna_no
    pool.close()
</code>```

Body:
I have a 32 core machine with 256gb ram and am new to parallel computing.
I have to run this line:

Flag=data.flag [:,:,x]

which is a very large matrix. "x" refers to the sub-matrix that I want to store to file. But "changes" 64 times and each iteration takes +- 8min, hence the need to parallelize it

I've looked at a few examples:
https://www.machinelearningplus.com/python/parallel-processing-python/
and
https://docs.python.org/3.7/library/multiprocessing.html#multiprocessing-programming

Function for code:

def multi_flagger(antenna_no):
    recv=data.corr_products[antenna_no][0]         # Gets the antenna name and polarization value
    flagger=data.flags[:, :, antenna_no]         # Flags the data based on the antenna value
    mat_flag = np.matrix(flagger)                # Morphs the 2d array into a matrix
    np.save('Flagged_data_'+str(recv)+'_.npy', mat_flag)  # Saves the data to a file

pool.map(multi_flagger, for i in range(2))
pool.close()

I get this error:

File "<ipython-input-58-e1a6f9779b9a>", line 1
   pool.map(multi_flagger, for i in range(2))
                             ^ SyntaxError: invalid syntax`

What I would like is 64 .npy files written to disk

Body:
The method Pool.map(func, iterable) expects an iterable, which can be a tuple or a list. You cannot pass a for loop as what you have tried (for i in range(2)), but you can instead pass a list of numbers from a range:

pool.map(multi_flagger, list(range(2)))  # [0, 1]

I'm not sure about the rest of your code, but when using a Pool, you set the number of worker processes when you create the Pool instance (as explained in the Using a pool of workers example) and then call map to pass in the function to execute and the function inputs:

def multi_flagger(antenna_no):
    recv=data.corr_products[antenna_no][0]
    flagger=data.flags[:, :, antenna_no]
    mat_flag = np.matrix(flagger)
    np.save('Flagged_data_'+str(recv)+'_.npy', mat_flag)

with Pool(processes=3) as pool:               # set the number of worker processes
    pool.map(multi_flagger, list(range(2)))   # pass a list of antenna_no
    pool.close()