问:
How does sizeof work for int types?
I have a small program which compares </p>

<p>(1) sizeof,
(2) numeric_limits::digits,
(3) and the results of a loop </p>

<p>in an effort to make sure they all report the same thing regarding the size of the "int types" on any C++ implementation.  However because I don't know about the internals of sizeof, I have to wonder if it is just reporting numeric_limits::digits.  Thanks </p>

答:
There aren't many internals to sizeof; it is a built-in operator which reports the size of its operand (either an expression or a type) in bytes.

Your code is rather complex - and using typeid leaves me wondering...

I have a bilingual program (written in the C subset of C++) that produces answers such as:

```<code> 1 = sizeof(char)
 1 = sizeof(unsigned char)
 2 = sizeof(short)
 2 = sizeof(unsigned short)
 4 = sizeof(int)
 4 = sizeof(unsigned int)
 8 = sizeof(long)
 8 = sizeof(unsigned long)
 4 = sizeof(float)
 8 = sizeof(double)
16 = sizeof(long double)
 8 = sizeof(size_t)
 8 = sizeof(ptrdiff_t)
 8 = sizeof(time_t)
 8 = sizeof(void *)
 8 = sizeof(char *)
 8 = sizeof(short *)
 8 = sizeof(int *)
 8 = sizeof(long *)
 8 = sizeof(float *)
 8 = sizeof(double *)
 8 = sizeof(int (*)(void))
 8 = sizeof(double (*)(void))
 8 = sizeof(char *(*)(void))
 1 = sizeof(struct { char a; })
 2 = sizeof(struct { short a; })
 4 = sizeof(struct { int a; })
 8 = sizeof(struct { long a; })
 4 = sizeof(struct { float a; })
 8 = sizeof(struct { double a; })
16 = sizeof(struct { char a; double b; })
16 = sizeof(struct { short a; double b; })
16 = sizeof(struct { long a; double b; })
 4 = sizeof(struct { char a; char b; short c; })
16 = sizeof(struct { char a; char b; long c; })
 4 = sizeof(struct { short a; short b; })
 6 = sizeof(struct { char a[3]; char b[3]; })
 8 = sizeof(struct { char a[3]; char b[3]; short c; })
16 = sizeof(struct { long double a; })
32 = sizeof(struct { char a; long double b; })
</code>```

(This was produced by G++ 4.6.0 on MacOS X 10.6.7 - a 64-bit compilation).  The code I used is:

```<code>#ifdef __cplusplus
#define __STDC_CONSTANT_MACROS
#endif /* __cplusplus */

#include <stdio.h>
#include <time.h>
#include <stddef.h>
#if __STDC_VERSION__ >= 199901L || HAVE_INTTYPES_H
#include <inttypes.h>
#endif /* __STDC_VERSION__ */

/* Using the simple C code in SPRINT() for structures leads to complaints from G++ */
/* Using the code in TPRINT() for pointers to functions leads to other complaints */
#define TPRINT(x)   do { typedef x y; printf("%2u = sizeof(" #x ")\n", (unsigned int)sizeof(y)); } while (0)
#define SPRINT(x)   printf("%2u = sizeof(" #x ")\n", (unsigned int)sizeof(x))

int main(void)
{
    /* Basic Types */
    SPRINT(char);
    SPRINT(unsigned char);
    SPRINT(short);
    SPRINT(unsigned short);
    SPRINT(int);
    SPRINT(unsigned int);
    SPRINT(long);
    SPRINT(unsigned long);

    SPRINT(float);
    SPRINT(double);
    SPRINT(long double);
    SPRINT(size_t);
    SPRINT(ptrdiff_t);
    SPRINT(time_t);

    /* Fancy integers */
#if __STDC_VERSION__ >= 199901L || HAVE_LONG_LONG
    SPRINT(long long);
    SPRINT(unsigned long long);
#endif /* __STDC_VERSION__ || HAVE_LONG_LONG */
#if __STDC_VERSION__ >= 199901L || HAVE_INTTYPES_H
    SPRINT(uintmax_t);
#ifdef INT8_MAX
    SPRINT(int8_t);
#endif
#ifdef INT16_MAX
    SPRINT(int16_t);
#endif
#ifdef INT32_MAX
    SPRINT(int32_t);
#endif
#ifdef INT64_MAX
    SPRINT(int64_t);
#endif
#ifdef INT128_MAX
    SPRINT(int128_t);
#endif
    SPRINT(int_least8_t);
    SPRINT(int_least16_t);
    SPRINT(int_least32_t);
    SPRINT(int_least64_t);
    SPRINT(int_fast8_t);
    SPRINT(int_fast16_t);
    SPRINT(int_fast32_t);
    SPRINT(int_fast64_t);
    SPRINT(uintptr_t);
#endif /* __STDC_VERSION__ || HAVE_INTTYPES_H */

    /* Pointers */
    SPRINT(void *);
    SPRINT(char *);
    SPRINT(short *);
    SPRINT(int *);
    SPRINT(long *);
    SPRINT(float *);
    SPRINT(double *);

    /* Pointers to functions */
    SPRINT(int (*)(void));
    SPRINT(double (*)(void));
    SPRINT(char *(*)(void));

    /* Structures */
    TPRINT(struct { char a; });
    TPRINT(struct { short a; });
    TPRINT(struct { int a; });
    TPRINT(struct { long a; });
    TPRINT(struct { float a; });
    TPRINT(struct { double a; });
    TPRINT(struct { char a; double b; });
    TPRINT(struct { short a; double b; });
    TPRINT(struct { long a; double b; });
    TPRINT(struct { char a; char b; short c; });
    TPRINT(struct { char a; char b; long c; });
    TPRINT(struct { short a; short b; });
    TPRINT(struct { char a[3]; char b[3]; });
    TPRINT(struct { char a[3]; char b[3]; short c; });
    TPRINT(struct { long double a; });
    TPRINT(struct { char a; long double b; });
#if __STDC_VERSION__ >= 199901L || HAVE_LONG_LONG
    TPRINT(struct { char a; long long b; });
#endif /* __STDC_VERSION__ */
#if __STDC_VERSION__ >= 199901L || HAVE_INTTYPES_H
    TPRINT(struct { char a; uintmax_t b; });
#endif /* __STDC_VERSION__ || HAVE_INTTYPES_H */

    return(0);
}
</code>```

I don't remember exactly why I had to do the messing with __STDC_CONSTANT_MACROS and SPRINT() vs TPRINT(), but that seemed to be what was needed (back in March 2010) to make the code bilingual.

Title: How does sizeof work for int types?

Body:
I have a small program which compares

(1) sizeof,
(2) numeric_limits::digits,
(3) and the results of a loop

in an effort to make sure they all report the same thing regarding the size of the "int types" on any C++ implementation.  However because I don't know about the internals of sizeof, I have to wonder if it is just reporting numeric_limits::digits.  Thanks

Body:
There aren't many internals to sizeof; it is a built-in operator which reports the size of its operand (either an expression or a type) in bytes.

Your code is rather complex - and using typeid leaves me wondering...

I have a bilingual program (written in the C subset of C++) that produces answers such as:

 1 = sizeof(char)
 1 = sizeof(unsigned char)
 2 = sizeof(short)
 2 = sizeof(unsigned short)
 4 = sizeof(int)
 4 = sizeof(unsigned int)
 8 = sizeof(long)
 8 = sizeof(unsigned long)
 4 = sizeof(float)
 8 = sizeof(double)
16 = sizeof(long double)
 8 = sizeof(size_t)
 8 = sizeof(ptrdiff_t)
 8 = sizeof(time_t)
 8 = sizeof(void *)
 8 = sizeof(char *)
 8 = sizeof(short *)
 8 = sizeof(int *)
 8 = sizeof(long *)
 8 = sizeof(float *)
 8 = sizeof(double *)
 8 = sizeof(int (*)(void))
 8 = sizeof(double (*)(void))
 8 = sizeof(char *(*)(void))
 1 = sizeof(struct { char a; })
 2 = sizeof(struct { short a; })
 4 = sizeof(struct { int a; })
 8 = sizeof(struct { long a; })
 4 = sizeof(struct { float a; })
 8 = sizeof(struct { double a; })
16 = sizeof(struct { char a; double b; })
16 = sizeof(struct { short a; double b; })
16 = sizeof(struct { long a; double b; })
 4 = sizeof(struct { char a; char b; short c; })
16 = sizeof(struct { char a; char b; long c; })
 4 = sizeof(struct { short a; short b; })
 6 = sizeof(struct { char a[3]; char b[3]; })
 8 = sizeof(struct { char a[3]; char b[3]; short c; })
16 = sizeof(struct { long double a; })
32 = sizeof(struct { char a; long double b; })

(This was produced by G++ 4.6.0 on MacOS X 10.6.7 - a 64-bit compilation).  The code I used is:

#ifdef __cplusplus
#define __STDC_CONSTANT_MACROS
#endif /* __cplusplus */

#include <stdio.h>
#include <time.h>
#include <stddef.h>
#if __STDC_VERSION__ >= 199901L || HAVE_INTTYPES_H
#include <inttypes.h>
#endif /* __STDC_VERSION__ */

/* Using the simple C code in SPRINT() for structures leads to complaints from G++ */
/* Using the code in TPRINT() for pointers to functions leads to other complaints */
#define TPRINT(x)   do { typedef x y; printf("%2u = sizeof(" #x ")\n", (unsigned int)sizeof(y)); } while (0)
#define SPRINT(x)   printf("%2u = sizeof(" #x ")\n", (unsigned int)sizeof(x))

int main(void)
{
    /* Basic Types */
    SPRINT(char);
    SPRINT(unsigned char);
    SPRINT(short);
    SPRINT(unsigned short);
    SPRINT(int);
    SPRINT(unsigned int);
    SPRINT(long);
    SPRINT(unsigned long);

    SPRINT(float);
    SPRINT(double);
    SPRINT(long double);
    SPRINT(size_t);
    SPRINT(ptrdiff_t);
    SPRINT(time_t);

    /* Fancy integers */
#if __STDC_VERSION__ >= 199901L || HAVE_LONG_LONG
    SPRINT(long long);
    SPRINT(unsigned long long);
#endif /* __STDC_VERSION__ || HAVE_LONG_LONG */
#if __STDC_VERSION__ >= 199901L || HAVE_INTTYPES_H
    SPRINT(uintmax_t);
#ifdef INT8_MAX
    SPRINT(int8_t);
#endif
#ifdef INT16_MAX
    SPRINT(int16_t);
#endif
#ifdef INT32_MAX
    SPRINT(int32_t);
#endif
#ifdef INT64_MAX
    SPRINT(int64_t);
#endif
#ifdef INT128_MAX
    SPRINT(int128_t);
#endif
    SPRINT(int_least8_t);
    SPRINT(int_least16_t);
    SPRINT(int_least32_t);
    SPRINT(int_least64_t);
    SPRINT(int_fast8_t);
    SPRINT(int_fast16_t);
    SPRINT(int_fast32_t);
    SPRINT(int_fast64_t);
    SPRINT(uintptr_t);
#endif /* __STDC_VERSION__ || HAVE_INTTYPES_H */

    /* Pointers */
    SPRINT(void *);
    SPRINT(char *);
    SPRINT(short *);
    SPRINT(int *);
    SPRINT(long *);
    SPRINT(float *);
    SPRINT(double *);

    /* Pointers to functions */
    SPRINT(int (*)(void));
    SPRINT(double (*)(void));
    SPRINT(char *(*)(void));

    /* Structures */
    TPRINT(struct { char a; });
    TPRINT(struct { short a; });
    TPRINT(struct { int a; });
    TPRINT(struct { long a; });
    TPRINT(struct { float a; });
    TPRINT(struct { double a; });
    TPRINT(struct { char a; double b; });
    TPRINT(struct { short a; double b; });
    TPRINT(struct { long a; double b; });
    TPRINT(struct { char a; char b; short c; });
    TPRINT(struct { char a; char b; long c; });
    TPRINT(struct { short a; short b; });
    TPRINT(struct { char a[3]; char b[3]; });
    TPRINT(struct { char a[3]; char b[3]; short c; });
    TPRINT(struct { long double a; });
    TPRINT(struct { char a; long double b; });
#if __STDC_VERSION__ >= 199901L || HAVE_LONG_LONG
    TPRINT(struct { char a; long long b; });
#endif /* __STDC_VERSION__ */
#if __STDC_VERSION__ >= 199901L || HAVE_INTTYPES_H
    TPRINT(struct { char a; uintmax_t b; });
#endif /* __STDC_VERSION__ || HAVE_INTTYPES_H */

    return(0);
}

I don't remember exactly why I had to do the messing with __STDC_CONSTANT_MACROS and SPRINT() vs TPRINT(), but that seemed to be what was needed (back in March 2010) to make the code bilingual.


来源: stackexchange

问:
Using Ml.net package error "System.ArgumentOutOfRangeException"
While using ML.net package the error "System.ArgumentOutOfRangeException: 'Schema mismatch for feature column 'Features': expected Vector, got Vector
Parameter name: inputSchema'" was thrown on the line "var model = trainingPipeline.Fit(trainData);". While understanding the error I cannot understand why it was thrown for the code

```<code> class Program
    {

        static void Main(string[] args)
        {

            MLContext mlcontext = new MLContext();
            IDataView trainData = mlcontext.Data.LoadFromTextFile<ModelInput>("StockTrain.csv", separatorChar: ',', hasHeader: false);
            var dataProcessPipeline = mlcontext.Transforms.Concatenate(outputColumnName: "Features", "age", "blPressure", "BiSkinthck", "NoPreg");

            var trainer = mlcontext.Regression.Trainers.LightGbm(labelColumnName: "bmi", featureColumnName: "Features");
            var trainingPipeline = dataProcessPipeline.Append(trainer);
            var model = trainingPipeline.Fit(trainData);

            IDataView testData = mlcontext.Data.LoadFromTextFile<ModelInput>("StockTest.csv", separatorChar: ',', hasHeader: false);
            IDataView predictions = model.Transform(testData);
            var metrics = mlcontext.Regression.Evaluate(predictions, "bmi");

                                                 //(0)     (2)  (3)       (5)         (7)
            var input = new ModelInput           //<4>,144,<58>,<28>,140,<29.5>,0.287,<37>,0
            {
                NoPreg = 4,
                blPressure = 58,
                BiSkinthck = 28,
                age = 37
            };
            var result = mlcontext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(model).Predict(input);
            Console.WriteLine($"Predicted bmi " + $"{result.bmi}");
        }

        public class ModelOutput
        {
            [ColumnName("Score")]
            public int bmi;
        }

        public class ModelInput
        {
            [LoadColumn(0)]
            public int NoPreg;
            [LoadColumn(2)]
            public int blPressure;
            [LoadColumn(3)]
            public int BiSkinthck;
            [LoadColumn(5)]
            public int bmi;
            [LoadColumn(7)]
            public int age;
        }
    }
</code>```

Some sample data being used is:

```<code>6,148,72,35,0,33.6,0.627,50,1
1,85,66,29,0,26.6,0.351,31,0
8,183,64,0,0,23.3,0.672,32,1
1,89,66,23,94,28.1,0.167,21,0
0,137,40,35,168,43.1,2.288,33,1
5,116,74,0,0,25.6,0.201,30,0
</code>```

Where only some of the data is used.

答:
You have some decimals in the data; change your ModelInput and ModelOutput to use floats instead (Also, the score of the prediction is a float in a regression)

```<code>public class ModelOutput
{
    [ColumnName("Score")]
    public float bmi;
}

public class ModelInput
{
    [LoadColumn(0)]
    public float NoPreg;
    [LoadColumn(2)]
    public float blPressure;
    [LoadColumn(3)]
    public float BiSkinthck;
    [LoadColumn(5)]
    public float bmi;
    [LoadColumn(7)]
    public float age;
}
</code>```

Hope it helps!

ContentLicense: CC BY-SA 4.0

Body:
While using ML.net package the error "System.ArgumentOutOfRangeException: 'Schema mismatch for feature column 'Features': expected Vector, got Vector
Parameter name: inputSchema'" was thrown on the line "var model = trainingPipeline.Fit(trainData);". While understanding the error I cannot understand why it was thrown for the code

 class Program
    {

        static void Main(string[] args)
        {

            MLContext mlcontext = new MLContext();
            IDataView trainData = mlcontext.Data.LoadFromTextFile<ModelInput>("StockTrain.csv", separatorChar: ',', hasHeader: false);
            var dataProcessPipeline = mlcontext.Transforms.Concatenate(outputColumnName: "Features", "age", "blPressure", "BiSkinthck", "NoPreg");

            var trainer = mlcontext.Regression.Trainers.LightGbm(labelColumnName: "bmi", featureColumnName: "Features");
            var trainingPipeline = dataProcessPipeline.Append(trainer);
            var model = trainingPipeline.Fit(trainData);

            IDataView testData = mlcontext.Data.LoadFromTextFile<ModelInput>("StockTest.csv", separatorChar: ',', hasHeader: false);
            IDataView predictions = model.Transform(testData);
            var metrics = mlcontext.Regression.Evaluate(predictions, "bmi");

                                                 //(0)     (2)  (3)       (5)         (7)
            var input = new ModelInput           //<4>,144,<58>,<28>,140,<29.5>,0.287,<37>,0
            {
                NoPreg = 4,
                blPressure = 58,
                BiSkinthck = 28,
                age = 37
            };
            var result = mlcontext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(model).Predict(input);
            Console.WriteLine($"Predicted bmi " + $"{result.bmi}");
        }

        public class ModelOutput
        {
            [ColumnName("Score")]
            public int bmi;
        }

        public class ModelInput
        {
            [LoadColumn(0)]
            public int NoPreg;
            [LoadColumn(2)]
            public int blPressure;
            [LoadColumn(3)]
            public int BiSkinthck;
            [LoadColumn(5)]
            public int bmi;
            [LoadColumn(7)]
            public int age;
        }
    }

Some sample data being used is:

6,148,72,35,0,33.6,0.627,50,1
1,85,66,29,0,26.6,0.351,31,0
8,183,64,0,0,23.3,0.672,32,1
1,89,66,23,94,28.1,0.167,21,0
0,137,40,35,168,43.1,2.288,33,1
5,116,74,0,0,25.6,0.201,30,0

Where only some of the data is used.

Body:
You have some decimals in the data; change your ModelInput and ModelOutput to use floats instead (Also, the score of the prediction is a float in a regression)

public class ModelOutput
{
    [ColumnName("Score")]
    public float bmi;
}

public class ModelInput
{
    [LoadColumn(0)]
    public float NoPreg;
    [LoadColumn(2)]
    public float blPressure;
    [LoadColumn(3)]
    public float BiSkinthck;
    [LoadColumn(5)]
    public float bmi;
    [LoadColumn(7)]
    public float age;
}

Hope it helps!


问:
Not getting unified_receipt in Apple iOS In App Purchase Server-to-Server Notification Sandbox
I am not getting unified_receipt as said in the developer documentation in the sandbox of apple in app purchase receipts.

As per their documentation : https://developer.apple.com/documentation/appstoreservernotifications/responsebody

Important

The following top-level objects are scheduled for deprecation:
  latest_receipt, latest_receipt_info, latest_expired_receipt, and
  latest_expired_receipt_info. Update any existing code to rely on the
  following objects in unified_receipt instead: latest_receipt and
  latest_receipt_info.

But in my response, I am not getting unified_receipt.

答:
As far as I know you will only see the unified_receipt when you receive the notifications at the endpoint that you've set up in the AppStore Connect. More info here

Hope this helps!!!


问:
APScheduler add lots of jobs concurrently (database Jobstore)
How can I schedule lots of APScheduler jobs (4,000+) concurrently? (I must schedule all these after certain user events.)

Iteratively calling add_job simply takes too long with many jobs. But when I try to use AsyncIOScheduler and the following async code, I don't get any added performance increase either.

NOTE: my scheduler needs to connect to a SQL jobstore via SqlAlchemy

```<code>scheduler = AsyncIOScheduler(jobstores={"default": SQLAlchemyJobStore(url="a valid db connection str")})
scheduler.start()

def schedule_jobs_quickly():
    # init lots of (fake) jobs
    jobs = []
    for i in range(3000):
        jobs.append(i)
    send_time = datetime.datetime.now() + datetime.timedelta(days=2)

    # try to schedule jobs concurrently
    start_time = time.time()
    asyncio.get_event_loop().run_until_complete(schedule_all_jobs(jobs, send_time))
    duration = time.time() - start_time
    print(f"Created {len(jobs)} jobs in {duration} seconds")

async def schedule_all_jobs(all_jobs, send_time):
    tasks = []
    for job in all_jobs:
        task = asyncio.ensure_future(schedule_job(job, send_time))
        tasks.append(task)
    await asyncio.gather(*tasks, return_exceptions=True)

async def schedule_job(job, send_time):
    scheduler.add_job(send_email_if_needed, trigger=send_time)

</code>```

Result is very slow. How to speed this up?

```<code>>>> schedule_jobs_quickly()
...
Created 3000 jobs in 401.9982771873474 seconds
</code>```

For comparison, this is how long it took with a BackgroundScheduler() using the default memory jobstore:

```<code>Created 3000 jobs in 0.9155495166778564 seconds
</code>```

So, it seems to be the database connections that are so expensive. Maybe there's a way to create multiple jobs using the same connection, instead of re-connecting for each add_job?

答:
It's not the solution I was looking for, but I decided to give up on AsyncIOScheduler and instead schedule my many tasks in a separate thread so the rest of my program could continue without being held up by all of the DB connections. Example below.

from threading import Thread

def schedule_jobs_quickly():
    # init lots of (fake) jobs
    jobs = []
    for i in range(3000):
        jobs.append(i)
    send_time = datetime.datetime.now() + datetime.timedelta(days=2)

    # schedule jobs in new thread
    scheduler_thread = Thread(target=schedule_email_jobs, args=(email_jobs,))
    scheduler_thread.start()

def schedule_email_jobs(jobs):
    for job in jobs:
        scheduler.add_job(send_email, trigger=send_time)

def send_email():
   # sends email
```

Body:
How can I schedule lots of APScheduler jobs (4,000+) concurrently? (I must schedule all these after certain user events.)

Iteratively calling add_job simply takes too long with many jobs. But when I try to use AsyncIOScheduler and the following async code, I don't get any added performance increase either.

NOTE: my scheduler needs to connect to a SQL jobstore via SqlAlchemy

scheduler = AsyncIOScheduler(jobstores={"default": SQLAlchemyJobStore(url="a valid db connection str")})
scheduler.start()

def schedule_jobs_quickly():
    # init lots of (fake) jobs
    jobs = []
    for i in range(3000):
        jobs.append(i)
    send_time = datetime.datetime.now() + datetime.timedelta(days=2)

    # try to schedule jobs concurrently
    start_time = time.time()
    asyncio.get_event_loop().run_until_complete(schedule_all_jobs(jobs, send_time))
    duration = time.time() - start_time
    print(f"Created {len(jobs)} jobs in {duration} seconds")

async def schedule_all_jobs(all_jobs, send_time):
    tasks = []
    for job in all_jobs:
        task = asyncio.ensure_future(schedule_job(job, send_time))
        tasks.append(task)
    await asyncio.gather(*tasks, return_exceptions=True)

async def schedule_job(job, send_time):
    scheduler.add_job(send_email_if_needed, trigger=send_time)

Result is very slow. How to speed this up?

>>> schedule_jobs_quickly()
...
Created 3000 jobs in 401.9982771873474 seconds

For comparison, this is how long it took with a BackgroundScheduler() using the default memory jobstore:

Created 3000 jobs in 0.9155495166778564 seconds

So, it seems to be the database connections that are so expensive. Maybe there's a way to create multiple jobs using the same connection, instead of re-connecting for each add_job?


问:
How to write an "exclusive" query in SQL?
I am going over a past paper for a database course I am taking and I am stuck on an SQL question

Here is the schema provided

Country(name, capital, area), name is the key

People(country, population, children, adult) where country refers to the
name in Country, population is the total population, and children and adult
is the percentage of the children and adult population.

Language(country,language,percentage) – for each language spoken in the
country, it lists the percentage of the population that speaks the language.

Here is the question:

Write the following query in SQL: Find languages that are only spoken in countries whose total population exceeds 10^7.

This is what I have so far:

```<code>SELECT l.language
FROM people p, language l
WHERE l.country = p.country AND
    p.population > 10^7
</code>```

The bit I am confused about is how to check that there are no other countries which a language is spoken in but the population is less than 10^7.

Any advice?
Thanks

答:
My approach would be to get the distinct languages spoken in each size-group of countries, then LEFT JOIN those two lists and end up with the list of languages only spoken in countries with population larger than 10^7 (or 10000000).</p>

```<code>;WITH Bigs AS
(
    SELECT DISTINCT l.language
    FROM people p
    INNER JOIN language l ON l.country = p.country
    WHERE p.population > 10000000
)
,Littles AS
(
    SELECT DISTINCT l.language
    FROM people p
    INNER JOIN language l ON l.country = p.country
    WHERE p.population <= 10000000
)
SELECT b.language
FROM Bigs b
LEFT JOIN Littles l ON l.language = b.language
WHERE l.language IS NULL
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am going over a past paper for a database course I am taking and I am stuck on an SQL question

Here is the schema provided

Country(name, capital, area), name is the key

People(country, population, children, adult) where country refers to the
name in Country, population is the total population, and children and adult
is the percentage of the children and adult population.

Language(country,language,percentage) – for each language spoken in the
country, it lists the percentage of the population that speaks the language.

Here is the question:

Write the following query in SQL: Find languages that are only spoken in countries whose total population exceeds 10^7.

This is what I have so far:

SELECT l.language
FROM people p, language l
WHERE l.country = p.country AND
    p.population > 10^7

The bit I am confused about is how to check that there are no other countries which a language is spoken in but the population is less than 10^7.

Any advice?
Thanks

Body:
My approach would be to get the distinct languages spoken in each size-group of countries, then LEFT JOIN those two lists and end up with the list of languages only spoken in countries with population larger than 10^7 (or 10000000).

;WITH Bigs AS
(
    SELECT DISTINCT l.language
    FROM people p
    INNER JOIN language l ON l.country = p.country
    WHERE p.population > 10000000
)
,Littles AS
(
    SELECT DISTINCT l.language
    FROM people p
    INNER JOIN language l ON l.country = p.country
    WHERE p.population <= 10000000
)
SELECT b.language
FROM Bigs b
LEFT JOIN Littles l ON l.language = b.language
WHERE l.language IS NULL


问:
Subtracting datetime UTC and datetime not UTC
From my dataframe I am trying to subtract one datetime64[ns, UTC] column against a datetime64[ns]. I believe I should normalize one of the columns and then subtract (should add UTC to the datetime64[ns] column or subtract UTC to the datetime64[ns, UTC] so afterwards I could subtract them).

```<code>df
estimated_delivery_time_local                  time_check
          2020-01-22 23:48:52   2020-01-22 23:48:52+00:00
          2020-01-23 00:45:05   2020-01-23 00:45:05+00:00
          2020-01-23 03:31:38   2020-01-23 03:31:38+00:00
          2020-01-23 00:19:06   2020-01-23 00:19:06+00:00
</code>```

I want to subtract this both column so as to check wether if all values are equal to zero

答:
I don't know if my answer meets your question but assuming your input data is in string format like this:

```<code>df=pd.DataFrame({'estimated_delivery_time_local':['2020-01-22 23:48:52','2020-01-23 00:45:05','2020-01-23 03:31:38','2020-01-23 00:19:06'],'time_check':['2020-01-22 23:48:52+00:00','2020-01-23 00:45:05+00:00','2020-01-23 03:31:38+00:00','2020-01-23 00:19:06+00:00']})
</code>```

then if you make the two columns with a normalized datetime format like this:

```<code>import datetime from datetime

df['time_check']=[datetime.strptime(x,'%Y-%m-%d %H:%M:%S+00:00') for x in  df['time_check']]

df['estimated_delivery_time_local']=[datetime.strptime(x,'%Y-%m-%d %H:%M:%S') for x in df['estimated_delivery_time_local']]
</code>```

in this case you should compare the two columns or the two timestamps and check if they are the same

```<code>df['estimated_delivery_time_local']-df['time_check']
</code>```

Body:
From my dataframe I am trying to subtract one datetime64[ns, UTC] column against a datetime64[ns]. I believe I should normalize one of the columns and then subtract (should add UTC to the datetime64[ns] column or subtract UTC to the datetime64[ns, UTC] so afterwards I could subtract them).

df
estimated_delivery_time_local                  time_check
          2020-01-22 23:48:52   2020-01-22 23:48:52+00:00
          2020-01-23 00:45:05   2020-01-23 00:45:05+00:00
          2020-01-23 03:31:38   2020-01-23 03:31:38+00:00
          2020-01-23 00:19:06   2020-01-23 00:19:06+00:00

I want to subtract this both column so as to check wether if all values are equal to zero

Body:
I don't know if my answer meets your question but assuming your input data is in string format like this:

df=pd.DataFrame({'estimated_delivery_time_local':['2020-01-22 23:48:52','2020-01-23 00:45:05','2020-01-23 03:31:38','2020-01-23 00:19:06'],'time_check':['2020-01-22 23:48:52+00:00','2020-01-23 00:45:05+00:00','2020-01-23 03:31:38+00:00','2020-01-23 00:19:06+00:00']})

then if you make the two columns with a normalized datetime format like this:

import datetime from datetime

df['time_check']=[datetime.strptime(x,'%Y-%m-%d %H:%M:%S+00:00') for x in  df['time_check']]

df['estimated_delivery_time_local']=[datetime.strptime(x,'%Y-%m-%d %H:%M:%S') for x in df['estimated_delivery_time_local']]

in this case you should compare the two columns or the two timestamps and check if they are the same

df['estimated_delivery_time_local']-df['time_check']


问:
How do I compress my GIF image to improve my Website?
I'm working on optimizing my website speed so that it is a lot faster. I have already compressed my image files, but one GIF that I have on my site is slowing everything down. The file size of it is 4.73 MB

I believe that's way too big for my site and is causing it to take a while to load. Anyone know how I can make the GIF compressed without losing quality of the image?

答: gifs has no jpeg compression. You can only work on the gif trying to use fewer colors. For example you can use a flat background instead of a gradient. Another thing you can do is load the gif in a lazy way. Try searching for lazy load gifs or have a look here https://css-tricks.com/snippets/javascript/lazy-loading-images/</p>


问:
How to change the column names and make a data frame of columns in the dataset
I am building a function to change the column names of 3 columns and make a new data frame with 3 column. The file name is noaaFilename, and Date, HrMn, and Slp were earlier column names and new names I want as Date, Time, AtmosPressure.</p>

```<code>  names(noaaFilename)[names(noaaFilename) == "Date"] <- "Date"
  names(noaaFilename)[names(noaaFilename) == "HrMn"] <- "Time"
  names(noaaFilename)[names(noaaFilename) == "Slp"] <- "AtmosPressure"

  noaaData <- subset(noaaFilename, select = c(Date, Time, AtmosPressure))
</code>```

答:
```<code>noaaData <- subset(noaaFilename, select = c(Date, HrMn, Slp))

names(noaaData) <- c("Date", "Time", "AtmosPressure")
</code>```

Body:
I am building a function to change the column names of 3 columns and make a new data frame with 3 column. The file name is noaaFilename, and Date, HrMn, and Slp were earlier column names and new names I want as Date, Time, AtmosPressure.

  names(noaaFilename)[names(noaaFilename) == "Date"] <- "Date"
  names(noaaFilename)[names(noaaFilename) == "HrMn"] <- "Time"
  names(noaaFilename)[names(noaaFilename) == "Slp"] <- "AtmosPressure"

  noaaData <- subset(noaaFilename, select = c(Date, Time, AtmosPressure))


问:
Adding a table row in jQuery
I'm using jQuery to add an additional row to a table as the last row.

I have done it this way:

```<code>$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
</code>```

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?

答:
You can use this great jQuery add table row function. It works great with tables that have
 and that don't. Also it takes into the consideration the colspan of your last table row.

Here is an example usage:

```<code>// One table
addTableRow($('#myTable'));
// add table row to number of tables
addTableRow($('.myTables'));
</code>```

OwnerDisplayName: Darryl Hein

Title: Adding a table row in jQuery

Body:
I'm using jQuery to add an additional row to a table as the last row.

I have done it this way:

$('#myTable').append('
my data	more data
');

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?

LastEditorDisplayName: Darryl Hein

Body:
You can use this great jQuery add table row function. It works great with tables that have <tbody> and that don't. Also it takes into the consideration the colspan of your last table row.

Here is an example usage:

// One table
addTableRow($('#myTable'));
// add table row to number of tables
addTableRow($('.myTables'));

OwnerDisplayName: Uzbekjon

ContentLicense: CC BY-SA 2.5


答:
```<code>mysubset <- function(df, oldnames, newnames){
  if(length(oldnames)!=length(newnames)){
    stop("oldnames and newnames are not the same length")
  }
  if(!all(oldnames%in%colnames(df)){
    stop("Not all of oldnames match column names of df")
  }
  df <- df[,oldnames, drop = F]
  colnames(df) <- newnames
  return(df)
}
</code>```

An example with the iris data set.

```<code>head(iris)
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1          5.1         3.5          1.4         0.2  setosa
#2          4.9         3.0          1.4         0.2  setosa
#3          4.7         3.2          1.3         0.2  setosa
#4          4.6         3.1          1.5         0.2  setosa
#5          5.0         3.6          1.4         0.2  setosa
#6          5.4         3.9          1.7         0.4  setosa
tmp <- mysubset(iris,
                oldnames = c("Sepal.Length","Sepal.Width","Species"),
                newnames = c("Date","Time","AtmosPressure"))
head(tmp)
#  Date Time AtmosPressure
#1  5.1  3.5        setosa
#2  4.9  3.0        setosa
#3  4.7  3.2        setosa
#4  4.6  3.1        setosa
#5  5.0  3.6        setosa
#6  5.4  3.9        setosa
</code>```

Writing the function like this makes it so you don't only need to specify 3 columns.

Title: How to change the column names and make a data frame of columns in the dataset

Body:
mysubset <- function(df, oldnames, newnames){
  if(length(oldnames)!=length(newnames)){
    stop("oldnames and newnames are not the same length")
  }
  if(!all(oldnames%in%colnames(df)){
    stop("Not all of oldnames match column names of df")
  }
  df <- df[,oldnames, drop = F]
  colnames(df) <- newnames
  return(df)
}

An example with the iris data set.

head(iris)
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1          5.1         3.5          1.4         0.2  setosa
#2          4.9         3.0          1.4         0.2  setosa
#3          4.7         3.2          1.3         0.2  setosa
#4          4.6         3.1          1.5         0.2  setosa
#5          5.0         3.6          1.4         0.2  setosa
#6          5.4         3.9          1.7         0.4  setosa
tmp <- mysubset(iris,
                oldnames = c("Sepal.Length","Sepal.Width","Species"),
                newnames = c("Date","Time","AtmosPressure"))
head(tmp)
#  Date Time AtmosPressure
#1  5.1  3.5        setosa
#2  4.9  3.0        setosa
#3  4.7  3.2        setosa
#4  4.6  3.1        setosa
#5  5.0  3.6        setosa
#6  5.4  3.9        setosa

Writing the function like this makes it so you don't only need to specify 3 columns.


问:
loop over table to set the background css
My HTML table has some classes and table tag is used

Want to retain the classes as is, but all my table and tr , th or td are using td bgcolor which is an old technique.

I want to loop over the table and find if that bgcolor is defined, use the same color and convert it to a css based background color so i can print it in IE

```<code>function setBackground() {

var table = document.getElementById("table1");

//i found this in a previous stack overflow answer and tried it

for (var i = 0, row; row = table.rows[i]; i++) {

   for (var j = 0, col; col = row.cells[j]; j++) {

  //this is for debugging purposes... I can't even get this to work
   alert(table.rows[i].cells[j]);

   table.rows[i].cells[j].style.background = "orange"; //just an example

    }
 }
}
</code>```

because IE is not able to print the background lines and colors for some reason using the webkit property

答:
You can do this:</p>

```<code>var cells = $("#targetTable td");
for(i in cells){
    color = $(cells[i]).attr('bgcolor');
    console.log(color);
    $(cells[i]).css({background: color});
}
</code>```

Body:
My HTML table has some classes and table tag is used

Want to retain the classes as is, but all my table and tr , th or td are using td bgcolor which is an old technique.

I want to loop over the table and find if that bgcolor is defined, use the same color and convert it to a css based background color so i can print it in IE

function setBackground() {

var table = document.getElementById("table1");

//i found this in a previous stack overflow answer and tried it

for (var i = 0, row; row = table.rows[i]; i++) {

   for (var j = 0, col; col = row.cells[j]; j++) {

  //this is for debugging purposes... I can't even get this to work
   alert(table.rows[i].cells[j]);

   table.rows[i].cells[j].style.background = "orange"; //just an example

    }
 }
}

because IE is not able to print the background lines and colors for some reason using the webkit property

Body:
You can do this:

var cells = $("#targetTable td");
for(i in cells){
    color = $(cells[i]).attr('bgcolor');
    console.log(color);
    $(cells[i]).css({background: color});
}


问:
How to plot uniform time-series in MongoDB Charts
I've just started to use MongoDB Charts to plot incoming data from a series of IoT devices that send at regular intervals. Each device sends a package with a timestamp and some data (JSON to our NoSQL db), and I would like to plot several devices on the same chart.

To visually check the continuity of the data flowing in (i.e. if a device fails to upload data) I want to plot each data-point over a continuous time-series x-axis. Does anyone know if MongoDB Charts has a feature to make the x-axis continuous? Currently, the chart plots one point per observation and space these equally no matter the time-in between.

Example of data: Point 1-2-3 all have 6 minutes in between, but visually appear to be non-uniform, since the x-axis is not continuous:

答: Yes, MongoDB Charts has a "Continuous Line" chart type that should do what you want. As you discovered, the discrete chart always aggregates values over binned time periods, but the continuous version plots a point for each document. Please see the following screenshot as an example.


问:
TermsAggregation on Array
have a problem with an index field that stores a list of strings in the way of

["abc_def_fgh", "abc_def_fgh" ,"123_345_456"]

Im trying to use TermsAggregation to get

"abc_def_fgh" (2)
"123_345_456" (1)

But cant get it working, as it results the count for each of the terms (abc (2), def(2) , etc)

Any idea?

Many thanks

答: This sounds like a mapping issue.  You need to make sure that you are using keyword opposed to text.  You do not want the field to be analyzed when using aggregations.

Title: TermsAggregation on Array


问:
How to loop a question until getting the answer from scanner?
I am trying to loop asking coordinates and getting input from the scanner. I want to ask for input until the coordinates are valid. However I am really new with java and the loops confused me for this task.
First I should print a console output asking the player to input a pair of board coordinates.

If the inputs are valid coordinates I will return the coordinates as a string array.

If the inputs are not valid coordinates I should print an error message and then ask again until I get valid coordinates.

public static String[] positionQuery(int dim, Scanner test_in) {
    Scanner stdin = new Scanner(System.in);
    System.out.println("Provide origin and destination coordinates.");
    System.out.println("Enter two positions between A1-H8:");
    String s1 = stdin.nextLine();
    String[] coordinates = s1.split(" ");
    String origin = coordinates[0];
    String dest = coordinates[1];

    while (!validCoordinate(origin, dim) && !validCoordinate(dest,dim)) {
        System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
        String s2 = stdin.nextLine();
        String[] coordinates2 = s2.split(" ");
        String origin2 = coordinates[0];
        String dest2 = coordinates[1];
    }
    return new String[0];
}
```

I created a helper function validCoordinate(String, int) that checks the validity.
How can I fix my code?

答:
You can use a recursion: call method which reads coordinate validetes them and calls himself again if validation failed. Here is final code of my implementation:</p>

```<code>public class Main {

    public static void main(String[] args) {
        int dim = 0;
        Scanner scanner = new Scanner(System.in);
        positionQuery(dim, scanner);
    }

    private static String[] positionQuery(int dim, Scanner scanner) {
        System.out.println("Provide origin and destination coordinates.");
        System.out.println("Enter two positions between A1-H8:");
        return readAndValidateCoordinates(dim, scanner);//read coordinates while they will be valid
    }

    /**
     * Reads coordinates from console and validates them.
     * If validation validation failed the recursion of this method will be invoked
     * @param dim
     * @param scanner
     * @return array of {@link String} coordinates
     */
    private static String[] readAndValidateCoordinates(int dim,  Scanner scanner) {
        String s1 = scanner.nextLine();
        String[] coordinates = s1.split(" ");
        String origin = coordinates[0];
        String dest = coordinates[1];
        if (validCoordinate(origin, dim) && validCoordinate(dest, dim)) {
            return coordinates;
        } else {
            System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
            return readAndValidateCoordinates(dim,  scanner); //read coordinates again
        }
    }

    private static boolean validCoordinate(String origin, int dim) {
        //perform your validation
        return true;
    }
}
</code>```

Body:
I am trying to loop asking coordinates and getting input from the scanner. I want to ask for input until the coordinates are valid. However I am really new with java and the loops confused me for this task.
First I should print a console output asking the player to input a pair of board coordinates.

If the inputs are valid coordinates I will return the coordinates as a string array.

If the inputs are not valid coordinates I should print an error message and then ask again until I get valid coordinates.

public static String[] positionQuery(int dim, Scanner test_in) {
    Scanner stdin = new Scanner(System.in);
    System.out.println("Provide origin and destination coordinates.");
    System.out.println("Enter two positions between A1-H8:");
    String s1 = stdin.nextLine();
    String[] coordinates = s1.split(" ");
    String origin = coordinates[0];
    String dest = coordinates[1];

    while (!validCoordinate(origin, dim) && !validCoordinate(dest,dim)) {
        System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
        String s2 = stdin.nextLine();
        String[] coordinates2 = s2.split(" ");
        String origin2 = coordinates[0];
        String dest2 = coordinates[1];
    }
    return new String[0];
}

I created a helper function validCoordinate(String, int) that checks the validity.
How can I fix my code?

Body:
You can use a recursion: call method which reads coordinate validetes them and calls himself again if validation failed. Here is final code of my implementation:

public class Main {

    public static void main(String[] args) {
        int dim = 0;
        Scanner scanner = new Scanner(System.in);
        positionQuery(dim, scanner);
    }

    private static String[] positionQuery(int dim, Scanner scanner) {
        System.out.println("Provide origin and destination coordinates.");
        System.out.println("Enter two positions between A1-H8:");
        return readAndValidateCoordinates(dim, scanner);//read coordinates while they will be valid
    }

    /**
     * Reads coordinates from console and validates them.
     * If validation validation failed the recursion of this method will be invoked
     * @param dim
     * @param scanner
     * @return array of {@link String} coordinates
     */
    private static String[] readAndValidateCoordinates(int dim,  Scanner scanner) {
        String s1 = scanner.nextLine();
        String[] coordinates = s1.split(" ");
        String origin = coordinates[0];
        String dest = coordinates[1];
        if (validCoordinate(origin, dim) && validCoordinate(dest, dim)) {
            return coordinates;
        } else {
            System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
            return readAndValidateCoordinates(dim,  scanner); //read coordinates again
        }
    }

    private static boolean validCoordinate(String origin, int dim) {
        //perform your validation
        return true;
    }
}


问:
Making app to count time since first time used
How to make an app to count the time since the first time opened? I have no idea which class to use. Is it possible to achieve this with a stopwatch or something similar? Can someone pls share some code? I don't know what to search on the internet just have an idea of what I want to build. Or just tell me an idea with what I can achieve this and how?</p>

```<code> statisticLayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          if (plusiliminus==0){
              Toast.makeText(getActivity(),R.string.toaststatistic,Toast.LENGTH_SHORT).show();
          } else {
              Fragment fragmentstatistic=new Statistic();
              FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
              transaction.replace(R.id.frameLayout,fragmentstatistic).commit();
          }
      }
  });
</code>```

答:
As far as I could understand, you need persistent storage for the time when it was first used. I think SharedPreferences is a good way of storing this in your case.

In the onCreate function of your launcher activity, you might get the System.currentTimeInMillis() and store it in the SharedPreferences as stated here.

Then when you need to reset the time, you just have to clear the value in the SharedPreferences and can set a new value again.

I hope this gives you an idea of your implementation.

Body:
How to make an app to count the time since the first time opened? I have no idea which class to use. Is it possible to achieve this with a stopwatch or something similar? Can someone pls share some code? I don't know what to search on the internet just have an idea of what I want to build. Or just tell me an idea with what I can achieve this and how?

 statisticLayout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          if (plusiliminus==0){
              Toast.makeText(getActivity(),R.string.toaststatistic,Toast.LENGTH_SHORT).show();
          } else {
              Fragment fragmentstatistic=new Statistic();
              FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
              transaction.replace(R.id.frameLayout,fragmentstatistic).commit();
          }
      }
  });


问:
CAN'T HIDE THE NAV ITEMS FROM THE FRONT-END UMBRACO-8
The  code below has been written in MVC5 controller. It throws an error
"Object does not contain definition of Where". The "IsToShow" is DocumentType
having a control "true/false" and this is used on every Document Type as a composition and its value is set on content template like UmbracoNaviHide.</p>

```<code>public List<NavigationList> GetSubNavigationList()
 {
     IPublishedContent page = Umbraco.Content(pageId);
     var subPages = page.Children.Where("IsToShow");//Error Line
 }
</code>```

答:
You need to query Where with Lamdba and property/equals like this in U8.

var subPages = page.Children.Where(x => x.GetProperty("isToShow").Value().Equals(true));```

Body:
The  code below has been written in MVC5 controller. It throws an error
"Object does not contain definition of Where". The "IsToShow" is DocumentType
having a control "true/false" and this is used on every Document Type as a composition and its value is set on content template like UmbracoNaviHide.

public List<NavigationList> GetSubNavigationList()
 {
     IPublishedContent page = Umbraco.Content(pageId);
     var subPages = page.Children.Where("IsToShow");//Error Line
 }


问:
google-datastore obtaining the correct blob item key for download
In the google appengine datastore, there is a BlobKey (labled as csv). The key is in the following format: encoded_gs_file:we1o5o7klkllfekomvcndhs345uh5pl31l. I would like to provide a download button to save this information.

The web app is being run using dev_appserver.py and uses python 2.7 (Django) as the backend. Currently, a button exists, but when clicking on it, it returns a 404 error. The download link that the button provides is:

```<code>https://localhost:8080/data?key=encoded_gs_file:dwndjndwamwljioihkm
</code>```

The interesting thing is that, when i go to localhost:8000/datastore and then navigate to the Blobstore Viewer, i can navigate to Entity Kind: GsFileInfo,  and there is a key generated. The problem is that it gives a 404.

The other blob item next to is a png and if i use the key for that png, i get a download. What is wrong with the key, how can i get the write key from the datastore.

答:
I'm still scratching my head in regards to your issue, but something that seems suspect is that size is None and finalized is False for your CSV file.

I looked back at your previous question (google cloud: downloading as an CSV) and noticed that you're not calling .close() on your GCS/blobstore file after you finish writing to it.

Maybe that will fix this.

Body:
In the google appengine datastore, there is a BlobKey (labled as csv). The key is in the following format: encoded_gs_file:we1o5o7klkllfekomvcndhs345uh5pl31l. I would like to provide a download button to save this information.

The web app is being run using dev_appserver.py and uses python 2.7 (Django) as the backend. Currently, a button exists, but when clicking on it, it returns a 404 error. The download link that the button provides is:

https://localhost:8080/data?key=encoded_gs_file:dwndjndwamwljioihkm

The interesting thing is that, when i go to localhost:8000/datastore and then navigate to the Blobstore Viewer, i can navigate to Entity Kind: GsFileInfo,  and there is a key generated. The problem is that it gives a 404.

The other blob item next to is a png and if i use the key for that png, i get a download. What is wrong with the key, how can i get the write key from the datastore.


问:
How to apply filter to new order emails only (wordpress, woocommerce)
I need help applying the following filter to woocommerce admin new order emails only. I've tried a few things but cant get it working.</p>

```<code>**function filter_woocommerce_email_order_item_quantity( $qty_display, $item ) {
$product = wc_get_product( $item['product_id'] );
$product_id = $product->get_id();

if ( $product_id == 6960 ) {
    $qty_display = $qty_display * 2;
}

return $qty_display;
};
add_filter( 'woocommerce_email_order_item_quantity', 'filter_woocommerce_email_order_item_quantity', 10, 2 );
</code>```

答:
It goes against some things ive read but this code is working for me</p>

```<code>add_action( 'woocommerce_email_order_details', 'add_order_instruction_email', 11, 4 );

function add_order_instruction_email( $order, $sent_to_admin, $plain_text, $email ) {

   remove_filter( 'woocommerce_email_order_item_quantity', 'filter_woocommerce_email_order_item_quantity', 10, 2 );

  };

function filter_woocommerce_email_order_item_quantity( $qty_display, $item ) {
    $product = wc_get_product( $item['product_id'] );
    $product_id = $product->get_id();

if ( $product_id == 6960 ) {
    $qty_display = $qty_display * 2;
}
    if ( $product_id == 6912 ) {
    $qty_display = $qty_display * 2;
}
    if ( $product_id == 6861 ) {
    $qty_display = $qty_display * 2;
}

return $qty_display;
};
add_filter( 'woocommerce_email_order_item_quantity', 'filter_woocommerce_email_order_item_quantity', 10, 2 );
</code>```

Body:
I need help applying the following filter to woocommerce admin new order emails only. I've tried a few things but cant get it working.

**function filter_woocommerce_email_order_item_quantity( $qty_display, $item ) {
$product = wc_get_product( $item['product_id'] );
$product_id = $product->get_id();

if ( $product_id == 6960 ) {
    $qty_display = $qty_display * 2;
}

return $qty_display;
};
add_filter( 'woocommerce_email_order_item_quantity', 'filter_woocommerce_email_order_item_quantity', 10, 2 );

Body:
It goes against some things ive read but this code is working for me

add_action( 'woocommerce_email_order_details', 'add_order_instruction_email', 11, 4 );

function add_order_instruction_email( $order, $sent_to_admin, $plain_text, $email ) {

   remove_filter( 'woocommerce_email_order_item_quantity', 'filter_woocommerce_email_order_item_quantity', 10, 2 );

  };

function filter_woocommerce_email_order_item_quantity( $qty_display, $item ) {
    $product = wc_get_product( $item['product_id'] );
    $product_id = $product->get_id();

if ( $product_id == 6960 ) {
    $qty_display = $qty_display * 2;
}
    if ( $product_id == 6912 ) {
    $qty_display = $qty_display * 2;
}
    if ( $product_id == 6861 ) {
    $qty_display = $qty_display * 2;
}

return $qty_display;
};
add_filter( 'woocommerce_email_order_item_quantity', 'filter_woocommerce_email_order_item_quantity', 10, 2 );


问:
Converting a member function to a static function in C++
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

```<code>typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}
</code>```

答:
If you are using GCC, then you can have the linker wrap the function for you with the --wrap option ( or -Wl,--wrap,malloc ).

Then you can intercept calls to malloc because all calls to that function will be redirected to __wrap_malloc.  You can call the real (original c-lib) malloc function using the name __real_malloc or you can substitute a replacement of your own (and if __real_malloc isn't called, then the linker may be able to dead-strip out the original c-lib malloc all-together).

```<code>void *__wrap_malloc (size_t c)
{
  printf ("malloc called with %zu\n", c);
  return __real_malloc (c);
}
</code>```

FWIW, you can replace the global new and delete operations and then you can have a program using only your own memory system (even when you use code from 3rd party compiled libraries as long as they haven't overloaded global new and delete).

Here's some great info: Tutorial of Replacing "new" and "delete"

Body:
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}

Body:
If you are using GCC, then you can have the linker wrap the function for you with the --wrap option ( or -Wl,--wrap,malloc ).

Then you can intercept calls to malloc because all calls to that function will be redirected to __wrap_malloc.  You can call the real (original c-lib) malloc function using the name __real_malloc or you can substitute a replacement of your own (and if __real_malloc isn't called, then the linker may be able to dead-strip out the original c-lib malloc all-together).

void *__wrap_malloc (size_t c)
{
  printf ("malloc called with %zu\n", c);
  return __real_malloc (c);
}

FWIW, you can replace the global new and delete operations and then you can have a program using only your own memory system (even when you use code from 3rd party compiled libraries as long as they haven't overloaded global new and delete).

Here's some great info: Tutorial of Replacing "new" and "delete"


问:
Swift: cannot convert value of type 'SomeType<T>' to expected argument type 'SomeType<_>'
I am using generics to build a paging library where I have code similar to this one (simplified):

struct PageData<T> {
    let item: T
    let pageNumber: Int
}

protocol PagedServiceProvider: class {
    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void)
}

class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData) // COMPILATION ERROR HERE
    }
}
```

<p>the call to <code>completion(pageData)</code> produces the following error:</p>

<blockquote>
  <p>Cannot convert value of type <code>PageData<ItemType>?</code> to expected argument type <code>PageData<_>?</code></p>
</blockquote>

<p>This workaround casting with <code>as?</code> gets rid of the error:</p>

<pre class="lang-swift prettyprint-override"><code>class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData as? PageData<ItemType>)
    }
}
</code>```

Also if var pageData: PageData<ItemType>? is declared as a local variable inside the fetchPage<ItemType>... method, the error is gone as well.

NOTE: This gist provides additional context.

I am confused as to why the compiler requires an explicit cast (that looks redundant to me in this case).

Could it be a matter of placeholder types scope (the ItemType in the fetchPage<ItemType>... method is not the same as the ItemType for the TestPagedServiceProvider<ItemType> class)?

I tried giving them different names and using where clauses to no avail.

答:
I think the below code will work for you. I have passed String as the Generic type while instantiating the PageData object.

```<code>func fetchPage<String>(page: Int, completion: @escaping (PageData<String>?) -> Void) {

        let page = PageData<String>(item: "Item", pageNumber: 1)
        completion(page)
}
</code>```

Body:
I am using generics to build a paging library where I have code similar to this one (simplified):

struct PageData<T> {
    let item: T
    let pageNumber: Int
}

protocol PagedServiceProvider: class {
    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void)
}

class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData) // COMPILATION ERROR HERE
    }
}

the call to completion(pageData) produces the following error:

Cannot convert value of type PageData<ItemType>? to expected argument type PageData<_>?

This workaround casting with as? gets rid of the error:

class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData as? PageData<ItemType>)
    }
}

Also if var pageData: PageData<ItemType>? is declared as a local variable inside the fetchPage<ItemType>... method, the error is gone as well.

NOTE: This gist provides additional context.

I am confused as to why the compiler requires an explicit cast (that looks redundant to me in this case).

Could it be a matter of placeholder types scope (the ItemType in the fetchPage<ItemType>... method is not the same as the ItemType for the TestPagedServiceProvider<ItemType> class)?

I tried giving them different names and using where clauses to no avail.

Body:
I think the below code will work for you. I have passed String as the Generic type while instantiating the PageData object.

func fetchPage<String>(page: Int, completion: @escaping (PageData<String>?) -> Void) {

        let page = PageData<String>(item: "Item", pageNumber: 1)
        completion(page)
}


问:
Revenuecat React-Native iPad Purchases.purchasePackage - promise not settling
using

```<code>"react": "16.9.0",
"react-native": "0.61.5",
"react-native-purchases": "^3.0.6",
</code>```

We're having a problem on an 11" iPad running through testflight on iOS version 13.3.1. Everything works on all simulators, and our iPhones and other iPads running on testflight work properly as well.

The problem is that the promise returned by Purchases.purchasePackage is neither resolving nor rejecting - it hangs. After combing thru the native Obj-C code, I've found relevant code in the file Pods/Purchases/RCPurchases.m. The method

```<code>- (void)purchaseProduct:(SKProduct *)product withPayment:(SKMutablePayment *)payment withPresentedOfferingIdentifier:(nullable NSString *)presentedOfferingIdentifier completion:(RCPurchaseCompletedBlock)completion
</code>```

is getting invoked, and the line

```<code>[self.storeKitWrapper addPayment:[payment copy]];
</code>```

is called, but the callback method

```<code>- (void)storeKitWrapper:(RCStoreKitWrapper *)storeKitWrapper
     updatedTransaction:(SKPaymentTransaction *)transaction
</code>```

is never invoked. Could this be an underlying issue with SKPaymentQueue?

Thanks!

答: It turns out my iPad was actually using an older version of iOS. Updating it resolved the issue.</p>

Body:
using

"react": "16.9.0",
"react-native": "0.61.5",
"react-native-purchases": "^3.0.6",

We're having a problem on an 11" iPad running through testflight on iOS version 13.3.1. Everything works on all simulators, and our iPhones and other iPads running on testflight work properly as well.

The problem is that the promise returned by Purchases.purchasePackage is neither resolving nor rejecting - it hangs. After combing thru the native Obj-C code, I've found relevant code in the file Pods/Purchases/RCPurchases.m. The method

- (void)purchaseProduct:(SKProduct *)product withPayment:(SKMutablePayment *)payment withPresentedOfferingIdentifier:(nullable NSString *)presentedOfferingIdentifier completion:(RCPurchaseCompletedBlock)completion

is getting invoked, and the line

[self.storeKitWrapper addPayment:[payment copy]];

is called, but the callback method

- (void)storeKitWrapper:(RCStoreKitWrapper *)storeKitWrapper
     updatedTransaction:(SKPaymentTransaction *)transaction

is never invoked. Could this be an underlying issue with SKPaymentQueue?

Thanks!


问:
How could I form a string of items grouped by a matching value? (e.g. "Red: Apples, Cherries")
I'm wondering if there is a decent way to do this (without scripts) - if not, I can attempt creating a script for it but some users of this sheet will be using Excel on their computers so I'm trying to keep it scriptless as much as possible.

I have a sheet set up to display text based on certain conditions that is meant to be copied and pasted into an external program.

There is a column for months jan-dec and a column next to that where the user can input a number from 1-10 (and those numbers are associated with strings that are found with Vlookup on another sheet. They're basically "error codes" just to keep the sheet clean. But I'm just omitting this part because it's not needed for this question)

Right now, the text that populates shows:

```<code>Jan: 1
Feb: 2
Apr: 1
</code>```

How could I group these by the value instead of listing them separately? Something like:

```<code>1: Jan, Apr
2: Feb
</code>```

Is it possible to grab the items from that months list and put them in their own lists?

This is the current formula for reference:

```<code>=if(countif(Calculator!B2:B13,">0"),CONCATENATE(C2:C13),"None")
</code>```

(Calculator sheet)B2:B13 --> column with the numbers

(Data sheet)C2:C13 --> a concatenated string that contains the month name from one cell and the number (or technically the string associated with that number as I mentioned before)

Each cell in the C column has the Jan: 1, Feb: 2 data and any month without data is left blank. When I concatenate the C cells together, it automatically omits the blank cells which is helpful but now I'd really like to group them by that value instead.

Here is the example sheet that reflects this

答:
delete A15 and paste this in A14:

```<code>={""; ARRAYFORMULA(TEXTJOIN(CHAR(10), 1, REGEXREPLACE(TRIM(
 TRANSPOSE(QUERY(QUERY({A2:A13&",", B2:B13&":"},
 "select max(Col1)
  where not Col2 matches ':'
  group by Col1
  pivot Col2"),,9^9))), ",$", )))}
</code>```

UPDATE:

if order matters...

```<code>={""; ARRAYFORMULA(TEXTJOIN(CHAR(10), 1, REGEXREPLACE(TRIM(
 TRANSPOSE(QUERY(QUERY({"♦"&ROW(A2:A13)&"♦"&A2:A13&",", B2:B13&":"},
 "select max(Col1)
  where not Col2 matches ':'
  group by Col1
  pivot Col2"),,9^9))), "♦\d+♦|,$", )))}
</code>```

UPDATE:

```<code>={""; ARRAYFORMULA(JOIN(CHAR(10), SUBSTITUTE(REGEXREPLACE(TRIM(QUERY(QUERY({
 SORT(FILTER({SUBSTITUTE(A1:A12, "'", "/"&20)*1, B1:B12&":"}, B1:B12<>""), 2, 1, 1, 1)},
 "select max(Col1)
  group by Col1
  pivot Col2
  format max(Col1) 'Mmm♦yy,'"),,99^99)), ",$", ), "♦", CHAR(39))))}
</code>```

Body:
I'm wondering if there is a decent way to do this (without scripts) - if not, I can attempt creating a script for it but some users of this sheet will be using Excel on their computers so I'm trying to keep it scriptless as much as possible.

I have a sheet set up to display text based on certain conditions that is meant to be copied and pasted into an external program.

There is a column for months jan-dec and a column next to that where the user can input a number from 1-10 (and those numbers are associated with strings that are found with Vlookup on another sheet. They're basically "error codes" just to keep the sheet clean. But I'm just omitting this part because it's not needed for this question)

Right now, the text that populates shows:

Jan: 1
Feb: 2
Apr: 1

How could I group these by the value instead of listing them separately? Something like:

1: Jan, Apr
2: Feb

Is it possible to grab the items from that months list and put them in their own lists?

This is the current formula for reference:

=if(countif(Calculator!B2:B13,">0"),CONCATENATE(C2:C13),"None")

(Calculator sheet)B2:B13 --> column with the numbers

(Data sheet)C2:C13 --> a concatenated string that contains the month name from one cell and the number (or technically the string associated with that number as I mentioned before)

Each cell in the C column has the Jan: 1, Feb: 2 data and any month without data is left blank. When I concatenate the C cells together, it automatically omits the blank cells which is helpful but now I'd really like to group them by that value instead.

Here is the example sheet that reflects this

Body:
delete A15 and paste this in A14:

={""; ARRAYFORMULA(TEXTJOIN(CHAR(10), 1, REGEXREPLACE(TRIM(
 TRANSPOSE(QUERY(QUERY({A2:A13&",", B2:B13&":"},
 "select max(Col1)
  where not Col2 matches ':'
  group by Col1
  pivot Col2"),,9^9))), ",$", )))}

UPDATE:

if order matters...

={""; ARRAYFORMULA(TEXTJOIN(CHAR(10), 1, REGEXREPLACE(TRIM(
 TRANSPOSE(QUERY(QUERY({"♦"&ROW(A2:A13)&"♦"&A2:A13&",", B2:B13&":"},
 "select max(Col1)
  where not Col2 matches ':'
  group by Col1
  pivot Col2"),,9^9))), "♦\d+♦|,$", )))}

UPDATE:

={""; ARRAYFORMULA(JOIN(CHAR(10), SUBSTITUTE(REGEXREPLACE(TRIM(QUERY(QUERY({
 SORT(FILTER({SUBSTITUTE(A1:A12, "'", "/"&20)*1, B1:B12&":"}, B1:B12<>""), 2, 1, 1, 1)},
 "select max(Col1)
  group by Col1
  pivot Col2
  format max(Col1) 'Mmm♦yy,'"),,99^99)), ",$", ), "♦", CHAR(39))))}


问:
Stream lots of screenshots from server
Let's say I have this tool that takes a screenshot of the user's desktop every 10 seconds and uploads the images to a server.  Images are deleted from the server after 24 hours.  I want to allow the user to view these screenshots in their browser.  So let's say each image is 300K and there are 5000 of them uploaded in a 24 hour period -- that's 1.5 GB of data.  These are png images, and often one screenshot isn't that different from the previous one, so I imagine I could compress them pretty well -- but I'm not sure how that would work.  I want to allow the user to view these images in their browser.  I want a slider under the images so the user can jump to any point in the 24 hour period.  I guess something like the YouTube player would be ideal.  Where the user could jump around and data is streamed, etc.  Image quality is important because the user needs to be able to read text in the screenshots.  I'd prefer a Python solution.

I've never done anything like this before, and am not sure how to approach the problem.  What would you do?

答:
The quick & easy solution is to

tile up the screen along a fixed grid

store the tiles separately, indexed by a strong hash (to eliminate duplicates, even between users)

store the entire screen as a 2-d array of tile hashes

reconstruct the original screen in the browser from the hashed tiles.

Going from one screen to another, very similar one, would be a matter of loading just a few tiles, so there's your compression.

Implement a simple reference counting scheme to remove the tiles again. You might even want to share screen parts between users to further reduce storage.

Experiment with various tile sizes to find out which works best; this may depend on screen resolution, user activity and the graphics format used to store the elements.

Image processing in Python can be done with PIL.

Title: Stream lots of screenshots from server


问:
Combine arrays of identical length into array of objects
I have 10 arrays of data that look like this:

```<code>var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays
</code>```

Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:

```<code>overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]
</code>```

I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.

答:
Assuming arr1,arr2 are not desired names of resulting object properties, if you need something

that scales nicely for arbitrary number of data arrays

assigns arbitrary key names (not necessarily corresponding to array variable names, or, worse, property name(s) that can't be valid variable name are needed)

works muuuch faster than accepted solution ;)

You may do the following:

const arr1 = [1,2,3,4,5,6,7,8,9,10],
      arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'],

      keyNames = ['id', 'greeting'],

      group = (...arrays) => (keys) =>
        arrays.reduce((res, arr, idx) =>
          (arr.forEach((e,i) => res[i][keys[idx]] = e), res),
          Array.from({length:arrays[0].length}, () => ({}))
        )

console.log(group(arr1,arr2)(keyNames))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {min-height:100%;}</code>```

Body:
I have 10 arrays of data that look like this:

var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays

Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:

overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]

I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.

Body:
Assuming arr1,arr2 are not desired names of resulting object properties, if you need something

that scales nicely for arbitrary number of data arrays

assigns arbitrary key names (not necessarily corresponding to array variable names, or, worse, property name(s) that can't be valid variable name are needed)

works muuuch faster than accepted solution ;)

You may do the following:

const arr1 = [1,2,3,4,5,6,7,8,9,10],
      arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'],

      keyNames = ['id', 'greeting'],

      group = (...arrays) => (keys) =>
        arrays.reduce((res, arr, idx) =>
          (arr.forEach((e,i) => res[i][keys[idx]] = e), res),
          Array.from({length:arrays[0].length}, () => ({}))
        )

console.log(group(arr1,arr2)(keyNames))

.as-console-wrapper {min-height:100%;}


问:
Could not convert string to float: '' in .prn
I'm trying to print the values between two heights in a prn file.

The error I have is that the delimiter just use one whitespace and not all.
The code works correctly because with .csv and .txt files works. I get the error in the first line of the loop because it's taking the second whitespace and not the first number. I tried too with a tab but the error that I got is list index out of range

This is the error I got

Traceback (most recent call last):   File

"c:/Users/name/Desktop/script.py", line 86, in
        col = float(row[4].replace(',','.')) ValueError: could not convert string to float: ''

```<code> with open(fileName) as File:
                reader = csv.reader(File, delimiter=delimiterOption)
                next(reader)
                for row in reader:
                    col = float(row[4].replace(',','.'))
                    if col>=float(height1)  and col<=float(height2)  or col==float(height1)  and col==float(height2) or col<=float(height1) and col>=float(height2):
                        print(row)
</code>```

This is the .prn file

Example: If I put the values 133 and 135 should print the first line(name1)

答:
You're having problems with your file because the csv module expects CSV files have their values separated by a single character. Your file's values are separated by several space characters, not just one. So it thinks that when you have a string like "foo    bar" (with four spaces in between the real words), you're actually looking at five values, the middle three of which are blank.

Fortunately, there is a way around this issue in this specific case. The reader class accepts a parameter named skipinitialspace which tells it to skip any extra whitespace immediately after a separator character. This works even if the separator is whitespace itself!

So try:

```<code>reader = csv.reader(File, delimiter=" ", skipinitialspace=True)
</code>```

Body:
I'm trying to print the values between two heights in a prn file.

The error I have is that the delimiter just use one whitespace and not all.
The code works correctly because with .csv and .txt files works. I get the error in the first line of the loop because it's taking the second whitespace and not the first number. I tried too with a tab but the error that I got is list index out of range

This is the error I got

Traceback (most recent call last):   File

"c:/Users/name/Desktop/script.py", line 86, in
        col = float(row[4].replace(',','.')) ValueError: could not convert string to float: ''

 with open(fileName) as File:
                reader = csv.reader(File, delimiter=delimiterOption)
                next(reader)
                for row in reader:
                    col = float(row[4].replace(',','.'))
                    if col>=float(height1)  and col<=float(height2)  or col==float(height1)  and col==float(height2) or col<=float(height1) and col>=float(height2):
                        print(row)

This is the .prn file

Example: If I put the values 133 and 135 should print the first line(name1)

Body:
You're having problems with your file because the csv module expects CSV files have their values separated by a single character. Your file's values are separated by several space characters, not just one. So it thinks that when you have a string like "foo    bar" (with four spaces in between the real words), you're actually looking at five values, the middle three of which are blank.

Fortunately, there is a way around this issue in this specific case. The reader class accepts a parameter named skipinitialspace which tells it to skip any extra whitespace immediately after a separator character. This works even if the separator is whitespace itself!

So try:

reader = csv.reader(File, delimiter=" ", skipinitialspace=True)


问:
Is it possible to hide/remove borders inside of intersected area of multiple divs?
When two or more div's intersect they just overlap and their borders are visible:

.circle {
  position: absolute;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px solid black;
}

#two {
  left: 50px;
}

#three {
  left: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div >
  <div class="circle" id="one"></div>
  <div class="circle" id="two"></div>
  <div class="circle" id="three"></div>
</div></code>```

The question is if it's possible to hide those border, that are inside of the intersected area so it looks like there is only one big shape. Taking the example above the result should look like this:

答:
another possibilitie is mix-blend-mode if avalaible:

 /* === HERE ==== comment where it matters , the rest is only styling */
div {
  width: 20vmax;
  height: 20vmax;
  border: solid;
  background: white;/* === HERE ====*/
  border-radius: 50%;
  margin: auto;
  position: relative;
  font-size:4vmax;
  display:flex;
  align-items:center;
  justify-content:center;
  box-shadow:0 0 10px, inset 0 0 2px;
  animation:shift 4s infinite ease-in-out alternate;
}
div::before,
div::after {
  content: "";
  position: absolute;
  height: inherit;
  width: inherit;
  background: inherit;
  border: inherit;
  border-radius: inherit;
  box-shadow:inherit;
  mix-blend-mode:screen;/* === HERE ====*/
  animation:shift 2s infinite ease-in-out alternate;
}
div::before {
  left:-50%;
}
div::after {
  left:50%;
  animation-delay:-1s;
}
p {z-index:1;}
@keyframes shift {
25% {transform:translate(5%,-5%) scale(1.2);}
50% {transform:translate(-5%,5%) scale(0.9);}
}
html {display:flex;min-height:100vh;}
body {margin:auto;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div><p>Hi, Cloudy</p></div></code>```

demo for the fun

Body:
When two or more div's intersect they just overlap and their borders are visible:

.circle {
  position: absolute;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px solid black;
}

#two {
  left: 50px;
}

#three {
  left: 100px;
}

The question is if it's possible to hide those border, that are inside of the intersected area so it looks like there is only one big shape. Taking the example above the result should look like this:

Body:
another possibilitie is mix-blend-mode if avalaible:

 /* === HERE ==== comment where it matters , the rest is only styling */
div {
  width: 20vmax;
  height: 20vmax;
  border: solid;
  background: white;/* === HERE ====*/
  border-radius: 50%;
  margin: auto;
  position: relative;
  font-size:4vmax;
  display:flex;
  align-items:center;
  justify-content:center;
  box-shadow:0 0 10px, inset 0 0 2px;
  animation:shift 4s infinite ease-in-out alternate;
}
div::before,
div::after {
  content: "";
  position: absolute;
  height: inherit;
  width: inherit;
  background: inherit;
  border: inherit;
  border-radius: inherit;
  box-shadow:inherit;
  mix-blend-mode:screen;/* === HERE ====*/
  animation:shift 2s infinite ease-in-out alternate;
}
div::before {
  left:-50%;
}
div::after {
  left:50%;
  animation-delay:-1s;
}
p {z-index:1;}
@keyframes shift {
25% {transform:translate(5%,-5%) scale(1.2);}
50% {transform:translate(-5%,5%) scale(0.9);}
}
html {display:flex;min-height:100vh;}
body {margin:auto;}

<div><p>Hi, Cloudy</p></div>

demo for the fun


问:
Access Azure Batch from an Azure Function
I'm trying to use a Service Principle to access a Batch pool from an Azure Function and running into authentication issues that I don't understand. The initial login with the Service Principle works fine, but then using the credentials to access the batch pool returns a 401.

Below is a condensed version of my code with comments at the key points

```<code>module.exports.dispatch = function (context) {

    MsRest.loginWithServicePrincipalSecret('AppId', 'Secret', 'TennantId', function(err, credentials){

        if (err) throw err;
        // This works as it prints the credentials
        context.log(credentials);

        var batch_client = new batch.ServiceClient(credentials, accountUrl);

        batch_client.pool.get('mycluster', function(error, result){

            if(error === null)
            {
                context.log('Accessed pool');
                context.log(result);
            }
            else
            {
                //Request to batch service returns a 401
                if(error.statusCode === 404)
                {
                    context.log('Pool not found yet returned 404...');

                }
                else
                {
                    context.log('Error occurred while retrieving pool data');
                    context.log(error);
                }

                //'Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly.
                context.res = { body: error.body.message.value };
                context.done();
            }
        });
    });
};
</code>```

How can the initial login with a service principle work no problem, but then the credentials it returns not be able to access the batch pool?

The actual error says to check the auth header on the request, which I can see and the Authorisation header isn't even present.

I've triple checked the Active Directory access control for the batch account the App ID and secret are the ones belonging to the owner of the batch account. Any ideas what to try next?

答:
I happened to run across this same issue and I didn't have the option of using SharedKeyCredentials so I wanted to share my solution in case anyone else finds it helpful.

As fpark mentions, we need to get an OAuth token to use with Batch instead of the default Azure Resource Management. Below is the original code posted by Mark with the minor modification needed to make it work with Batch:

```<code>module.exports.dispatch = function (context) {

    let authOptions = {tokenAudience: 'batch'};

    MsRest.loginWithServicePrincipalSecret('AppId', 'Secret', 'TennantId', authOptions, function(err, credentials){

        if (err) throw err;
        // This works as it prints the credentials
        context.log(credentials);

        var batch_client = new batch.ServiceClient(credentials, accountUrl);

        batch_client.pool.get('mycluster', function(error, result){

            if(error === null)
            {
                context.log('Accessed pool');
                context.log(result);
            }
            else
            {
                //Request to batch service returns a 401
                if(error.statusCode === 404)
                {
                    context.log('Pool not found yet returned 404...');

                }
                else
                {
                    context.log('Error occurred while retrieving pool data');
                    context.log(error);
                }

                //'Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly.
                context.res = { body: error.body.message.value };
                context.done();
            }
        });
    });
};
</code>```

Body:
I'm trying to use a Service Principle to access a Batch pool from an Azure Function and running into authentication issues that I don't understand. The initial login with the Service Principle works fine, but then using the credentials to access the batch pool returns a 401.

Below is a condensed version of my code with comments at the key points

module.exports.dispatch = function (context) {

    MsRest.loginWithServicePrincipalSecret('AppId', 'Secret', 'TennantId', function(err, credentials){

        if (err) throw err;
        // This works as it prints the credentials
        context.log(credentials);

        var batch_client = new batch.ServiceClient(credentials, accountUrl);

        batch_client.pool.get('mycluster', function(error, result){

            if(error === null)
            {
                context.log('Accessed pool');
                context.log(result);
            }
            else
            {
                //Request to batch service returns a 401
                if(error.statusCode === 404)
                {
                    context.log('Pool not found yet returned 404...');

                }
                else
                {
                    context.log('Error occurred while retrieving pool data');
                    context.log(error);
                }

                //'Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly.
                context.res = { body: error.body.message.value };
                context.done();
            }
        });
    });
};

How can the initial login with a service principle work no problem, but then the credentials it returns not be able to access the batch pool?

The actual error says to check the auth header on the request, which I can see and the Authorisation header isn't even present.

I've triple checked the Active Directory access control for the batch account the App ID and secret are the ones belonging to the owner of the batch account. Any ideas what to try next?

Body:
I happened to run across this same issue and I didn't have the option of using SharedKeyCredentials so I wanted to share my solution in case anyone else finds it helpful.

As fpark mentions, we need to get an OAuth token to use with Batch instead of the default Azure Resource Management. Below is the original code posted by Mark with the minor modification needed to make it work with Batch:

module.exports.dispatch = function (context) {

    let authOptions = {tokenAudience: 'batch'};

    MsRest.loginWithServicePrincipalSecret('AppId', 'Secret', 'TennantId', authOptions, function(err, credentials){

        if (err) throw err;
        // This works as it prints the credentials
        context.log(credentials);

        var batch_client = new batch.ServiceClient(credentials, accountUrl);

        batch_client.pool.get('mycluster', function(error, result){

            if(error === null)
            {
                context.log('Accessed pool');
                context.log(result);
            }
            else
            {
                //Request to batch service returns a 401
                if(error.statusCode === 404)
                {
                    context.log('Pool not found yet returned 404...');

                }
                else
                {
                    context.log('Error occurred while retrieving pool data');
                    context.log(error);
                }

                //'Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly.
                context.res = { body: error.body.message.value };
                context.done();
            }
        });
    });
};


问:
Recursive jQuery submit function doesn't submit the form
I need some code to run right after the submit button has been clicked and before the form has actually been submitted.
I've stripped the code and left only the parts needed to show you the problem.
What I need the code to do is go inside the submit function, but instead of submitting the form call the function again.
The form should submit only in that second iteration.
Except it doesn't. The code is fully executed as it should but the form doesn't submit in the end.

I would appreciate it if someone can explain why.

Here's the code (simplr-reg's the form's name):

```<code><script>

var reallySubmit = false;

$(‘#simplr-reg’).submit(function(event)
{
   if (false == reallySubmit)
   {
      reallySubmit = true;
      $(‘#simplr-reg’).submit();
      event.preventDefault();
      return false;
   }
   else
   {
      return true;
   }
});

</script>
</code>```

答:
```<code>$("#simplr-reg").submit();
</code>```

That says "call the submit method on the jQuery selection".  You have a jQuery submit handler bound to the selection.  Since you have triggered the event on the jQuery selection, the jQuery handler is also triggered.

If you trigger the event on the native DOM form object (this within the submit handler), the jQuery handler will not be triggered, so you won't go round in circles.  Call the form.submit method:

```<code>this.submit();
</code>```

Body:
$("#simplr-reg").submit();

That says "call the submit method on the jQuery selection".  You have a jQuery submit handler bound to the selection.  Since you have triggered the event on the jQuery selection, the jQuery handler is also triggered.

If you trigger the event on the native DOM form object (this within the submit handler), the jQuery handler will not be triggered, so you won't go round in circles.  Call the form.submit method:

this.submit();


问:
Python says that whatever variable I want to give a number is Literal and can't print it
so I'm new to Python and I'm learning from the book "Python for Everybody", I'm currently in Chapter 3 and I have to do an assignment. I'm supposed to give a value to numbers 1 through 7, where 1 is Monday, 2 is Tuesday...7 is Sunday. So I enter the following code, but the program says it can't print something literal and point at 1:

What am I doing wrong? Any help will be appreciated, thank you.

Sincerely,
Ana Baird

答:
Few mistakes here:

You need to use string literal 1 = "Monday" instead of just 1 = Monday. Otherwise Monday should be a variable declared before.

You can't assign string literal to a number and vice versa. But you can assign both numbers and literals to variables:

monday = "Monday"
day_of_week = 1
```

For this exercise you can remove everything before line with input('...').

P.S. Didn't find this exercise in a book. Would be better to see exact task to not guess.

P.P.S. Good practice - to keep code here, not screenshot.

Body:
Few mistakes here:

You need to use string literal 1 = "Monday" instead of just 1 = Monday. Otherwise Monday should be a variable declared before.

You can't assign string literal to a number and vice versa. But you can assign both numbers and literals to variables:

monday = "Monday"
day_of_week = 1

For this exercise you can remove everything before line with input('...').

P.S. Didn't find this exercise in a book. Would be better to see exact task to not guess.

P.P.S. Good practice - to keep code here, not screenshot.


问:
Split Dataframe into list of one-row Dataframes
I would like to split a dataframe

```<code>df <- data.frame(a = 1:4, b = letters[1:4])

  a b
1 1 a
2 2 b
3 3 c
4 4 d
</code>```

into a list of one-row dataframes

```<code>list(
    data.frame(a = 1, b = letters[1])
    , data.frame(a = 2, b = letters[2])
    , data.frame(a = 3, b = letters[3])
    , data.frame(a = 4, b = letters[4])
)

[[1]]
  a b
1 1 a

[[2]]
  a b
1 2 b

[[3]]
  a b
1 3 c

[[4]]
  a b
1 4 d
</code>```

Is there an elegant solution to this?

答:
A simple way would be to use the split() command built into R

```<code>split( df, 1:length( df$a ) )
</code>```

It should be robust enough to handle duplicates in df$a.

Body:
I would like to split a dataframe

df <- data.frame(a = 1:4, b = letters[1:4])

  a b
1 1 a
2 2 b
3 3 c
4 4 d

into a list of one-row dataframes

list(
    data.frame(a = 1, b = letters[1])
    , data.frame(a = 2, b = letters[2])
    , data.frame(a = 3, b = letters[3])
    , data.frame(a = 4, b = letters[4])
)

[[1]]
  a b
1 1 a

[[2]]
  a b
1 2 b

[[3]]
  a b
1 3 c

[[4]]
  a b
1 4 d

Is there an elegant solution to this?

Body:
A simple way would be to use the split() command built into R

split( df, 1:length( df$a ) )

It should be robust enough to handle duplicates in df$a.


问:
Css: Bootstrap, importing only tables
How do I import only tables from the Bootstrap framework?

What I want to do: I have found a couple of table examples from Bootstrap that I really like which I would like to import into my project.

The issue: When importing Bootstrap, in addition to tables, there are changes to other tags such as h1, h2, title and html.

What I tried: I got a minimized/customized Bootstrap that supposedly has only tables, but there are still changes to h1, h2, etc.

答:
normaly you should use the whole bootstrap package. There are great classes inside to make your whole page responsive.

If you only love the stilling of the tables maybe this snippet helps you:

https://gist.github.com/luisciphere/3c2d1710d90372784b072ebbcaf7bde4

Title: Css: Bootstrap, importing only tables


问:
Google apps script search in two columns get matching rows as 2D array
the following gs code is working well

```<code>function getData00(e) {
  var id = "SHEET_ID";
  var sheetname = "SHEET";
  var data = SpreadsheetApp.openById(id).getSheetByName(sheetname).getDataRange().getValues();
  var ar = [];
  data.forEach(function(f) {
    if (~f.indexOf(e.color)) {
      ar.push(f);
    }
  });
  return ar;
}
</code>```

So i can search in column for specific "color" value and get the corresponding row values.
Now i need to add another criteria to search also in another column and get the combined row values.

my spreadsheet:

```<code>Number |   color   |   level   |   price   |   size   |   type
1      |   red     |   first   |    25     |    4     |   local
2      |   blue    |   third   |    30     |    3     |   global
3      |   green   |   second  |    40     |    6     |   local
4      |   blue    |   second  |    60     |    5     |   global

</code>```

i need to search for "blue" in column B and for "local" in column F to get the matching rows values.

Result i am looking for:

```<code>2,blue,third,30,3,global
4,blue,second,60,5,global
</code>```

HTML:

```<code><html>
<body>
<p id="demo"></p>
</body>
</html>
<script>
function dispData(ar) {
 document.getElementById("demo").innerHTML = ar;
}
function getData00(e) {
  google.script.run.withSuccessHandler(dispData).getData00(e);
}
</script>
</code>```

Thanks in advance and appreciate any help

答:
Array.filter would be more appropriate:

```<code>function getData01(e) {
  var id = "SHEET_ID";
  var sheetname = "SHEET";
  var data = SpreadsheetApp.openById(id)
    .getSheetByName(sheetname)
    .getDataRange()
    .getValues();
  return data.filter(row => [e.color, e.type].every(prop => row.includes(prop)))
}
</code>```

Body:
the following gs code is working well

function getData00(e) {
  var id = "SHEET_ID";
  var sheetname = "SHEET";
  var data = SpreadsheetApp.openById(id).getSheetByName(sheetname).getDataRange().getValues();
  var ar = [];
  data.forEach(function(f) {
    if (~f.indexOf(e.color)) {
      ar.push(f);
    }
  });
  return ar;
}

So i can search in column for specific "color" value and get the corresponding row values.
Now i need to add another criteria to search also in another column and get the combined row values.

my spreadsheet:

Number |   color   |   level   |   price   |   size   |   type
1      |   red     |   first   |    25     |    4     |   local
2      |   blue    |   third   |    30     |    3     |   global
3      |   green   |   second  |    40     |    6     |   local
4      |   blue    |   second  |    60     |    5     |   global

i need to search for "blue" in column B and for "local" in column F to get the matching rows values.

Result i am looking for:

2,blue,third,30,3,global
4,blue,second,60,5,global

HTML:

Thanks in advance and appreciate any help

Body:
Array.filter would be more appropriate:

function getData01(e) {
  var id = "SHEET_ID";
  var sheetname = "SHEET";
  var data = SpreadsheetApp.openById(id)
    .getSheetByName(sheetname)
    .getDataRange()
    .getValues();
  return data.filter(row => [e.color, e.type].every(prop => row.includes(prop)))
}