问:
Combine two files and keep the non match lines
I am studying the sed command but I have a problem when combining 2 files.

file1.txt

```<code>A       1
C       3
E       5
</code>```

file2.txt

```<code>1 John Lennon
2 Mariah carey
3 Cool & The Gang
4 Westlife
5 Red Hot Chili Peppers
</code>```

desired output

```<code>1 John Lennon A
2 Mariah Carey
3 Cool & The Gang C
4 Westlife
5 Red Hot Chili Peppers E
</code>```

I try to make awk script like this:

```<code>awk 'FNR==NR{seen[$1]=$2; next} $1 in seen{seen[$1]=seen[$1] OFS $2} END{ for (e in seen) print e, seen[e]}' file2.txt file1.txt | sort -V
</code>```

but this output only display one word of the singer (John, Mariah, Cool, Westlife, and Red) and does not display the singer's full name. Is something wrong with my script?

答:
If the columns of the two files are separated by tabs instead of spaces (Looks like the first one is, second one I don't know; unfortunately SO's markdown is not tab friendly), it's a trivial join:

```<code>$ join -12 -21 -o 0,2.2,1.1 -t$'\t' -a2 <(sort -t$'\t' -k2,2 file1.txt) <(sort -t$'\t' -k1,1 file2.txt)
1   John Lennon A
2   Mariah carey
3   Cool & The Gang C
4   Westlife
5   Red Hot Chili Peppers   E
</code>```

(join requires its files to be sorted lexicographically on the join column, not numerically, hence the sorts).

If there's just a space between the number and the band in file2, convert it to a tab first with sed:

```<code>join -12 -21 -o 0,2.2,1.1 -t$'\t' -a2 <(sort -t$'\t' -k2,2 file1.txt) <(sed 's/ /\t/' file2.txt | sort -t$'\t' -k1,1)
</code>```

Body:
I am studying the sed command but I have a problem when combining 2 files.

file1.txt

A       1
C       3
E       5

file2.txt

1 John Lennon
2 Mariah carey
3 Cool & The Gang
4 Westlife
5 Red Hot Chili Peppers

desired output

1 John Lennon A
2 Mariah Carey
3 Cool & The Gang C
4 Westlife
5 Red Hot Chili Peppers E

I try to make awk script like this:

awk 'FNR==NR{seen[$1]=$2; next} $1 in seen{seen[$1]=seen[$1] OFS $2} END{ for (e in seen) print e, seen[e]}' file2.txt file1.txt | sort -V

but this output only display one word of the singer (John, Mariah, Cool, Westlife, and Red) and does not display the singer's full name. Is something wrong with my script?

Body:
If the columns of the two files are separated by tabs instead of spaces (Looks like the first one is, second one I don't know; unfortunately SO's markdown is not tab friendly), it's a trivial join:

$ join -12 -21 -o 0,2.2,1.1 -t$'\t' -a2 <(sort -t$'\t' -k2,2 file1.txt) <(sort -t$'\t' -k1,1 file2.txt)
1   John Lennon A
2   Mariah carey
3   Cool & The Gang C
4   Westlife
5   Red Hot Chili Peppers   E

(join requires its files to be sorted lexicographically on the join column, not numerically, hence the sorts).

If there's just a space between the number and the band in file2, convert it to a tab first with sed:

join -12 -21 -o 0,2.2,1.1 -t$'\t' -a2 <(sort -t$'\t' -k2,2 file1.txt) <(sed 's/ /\t/' file2.txt | sort -t$'\t' -k1,1)


来源: stackexchange

问:
How to reverse multiple lines of input? (C)
I've been stuck on this for a while and any help would be greatly appreciated.

I'm trying to reverse input one line at a time but display it all together at the end.

```<code>Eg Input = abc 123
           lorem ipsum
           dolor sit amet

Output = 321 cba
         muspi merol
         tema tis rolod
</code>```

This is what I have so far, but it only reverses the last line of input.
My thoughts are that I am possibly not reading in all the input, but am unusure how to remedy this?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse(char *input, int length){
    for(int i = length-1; i >= 0; i--){
        printf("%c", input[i]);

    }

}

int main(void){
    char input[100];

    while(!feof(stdin)){

        fgets(input, 100, stdin);

    }

    reverse(input, strlen(input));

    return 0;
}
</code>```

答:
Try This,

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse(char *str)
{
   int i,j,length;
   char ch;

   for(length=0;str[length]!='\n'&&str[length]!='\0';length++); //for length of string litrel between '\n' or '\0' not for full length of the string

   for(i=0,j=length-1;i<length/2;i++,j--)   //to reverse string
   {
        ch=str[i];
        str[i]=str[j];
        str[j]=ch;
   }

   if(str[length]=='\n')             //if the string literal is present
        reverse(&str[length+1]);     //then goes to recursion
   else
        return;                      //if no more string is present then return
}

int main(void)
{
    char input[100];
    int i;

    memset(input,'\0',sizeof(input));      // initialize to null

    for(i=0;!feof(stdin);i=strlen(input))
    {
     fgets(&input[i],(100-i), stdin);      // &input[i] is to merge the inputting string to the before string present in the char input[100];
    }
    input[strlen(input)-1]='\0';

    reverse(input);
    printf("\n%s",input);

    return 0;
}
</code>```

Input:

abc 123

lorem ipsum

dolor sit amet

ctrl+z

Note: ctrl+z is to send EOF to stdin in windows, It must be in new line.

output in cmd:

```<code>abc 123
lorem ipsum
dolor sit amet
^Z

321 cba
muspi merol
tema tis rolod
Process returned 0 (0x0)   execution time : 11.636 s
Press any key to continue.
</code>```

Note :In this execution of code You Can't erase(backspace) after pressing Enter. if you want you should change the logic for input.

See Below:

The inputting string will stored will be like

```<code>    "abc 123\nlorem ipsum\ndolor sit amet\0"
</code>```

The reverse function reverses the string between the new line('\n') character only.if there is an null('\0') the function will return, else the function goes on recursion.

First pass:

```<code>    "321 cba\nlorem ipsum\ndolor sit amet\0"
</code>```

There is an '\n' after "321 cba" so the function passes reference of next character of the '\n' to the same function(recursion).

Second pass:

```<code>    "321 cba\nmuspi merol\ndolor sit amet\0"
</code>```

'\n' is present so goes to recursion.

Third pass:

```<code>    "321 cba\nmuspi merol\ntema tis rolod\0"
</code>```

'\n' is not present so function returns.

ContentLicense: CC BY-SA 4.0

Body:
I've been stuck on this for a while and any help would be greatly appreciated.

I'm trying to reverse input one line at a time but display it all together at the end.

Eg Input = abc 123
           lorem ipsum
           dolor sit amet

Output = 321 cba
         muspi merol
         tema tis rolod

This is what I have so far, but it only reverses the last line of input.
My thoughts are that I am possibly not reading in all the input, but am unusure how to remedy this?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse(char *input, int length){
    for(int i = length-1; i >= 0; i--){
        printf("%c", input[i]);

    }

}

int main(void){
    char input[100];

    while(!feof(stdin)){

        fgets(input, 100, stdin);

    }

    reverse(input, strlen(input));

    return 0;
}

Body:
Try This,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse(char *str)
{
   int i,j,length;
   char ch;

   for(length=0;str[length]!='\n'&&str[length]!='\0';length++); //for length of string litrel between '\n' or '\0' not for full length of the string

   for(i=0,j=length-1;i<length/2;i++,j--)   //to reverse string
   {
        ch=str[i];
        str[i]=str[j];
        str[j]=ch;
   }

   if(str[length]=='\n')             //if the string literal is present
        reverse(&str[length+1]);     //then goes to recursion
   else
        return;                      //if no more string is present then return
}

int main(void)
{
    char input[100];
    int i;

    memset(input,'\0',sizeof(input));      // initialize to null

    for(i=0;!feof(stdin);i=strlen(input))
    {
     fgets(&input[i],(100-i), stdin);      // &input[i] is to merge the inputting string to the before string present in the char input[100];
    }
    input[strlen(input)-1]='\0';

    reverse(input);
    printf("\n%s",input);

    return 0;
}

Input:

abc 123

lorem ipsum

dolor sit amet

ctrl+z

Note: ctrl+z is to send EOF to stdin in windows, It must be in new line.

output in cmd:

abc 123
lorem ipsum
dolor sit amet
^Z

321 cba
muspi merol
tema tis rolod
Process returned 0 (0x0)   execution time : 11.636 s
Press any key to continue.

Note :In this execution of code You Can't erase(backspace) after pressing Enter. if you want you should change the logic for input.

See Below:

The inputting string will stored will be like

    "abc 123\nlorem ipsum\ndolor sit amet\0"

The reverse function reverses the string between the new line('\n') character only.if there is an null('\0') the function will return, else the function goes on recursion.

First pass:

    "321 cba\nlorem ipsum\ndolor sit amet\0"

There is an '\n' after "321 cba" so the function passes reference of next character of the '\n' to the same function(recursion).

Second pass:

    "321 cba\nmuspi merol\ndolor sit amet\0"

'\n' is present so goes to recursion.

Third pass:

    "321 cba\nmuspi merol\ntema tis rolod\0"

'\n' is not present so function returns.


问:
Id of newly added Entity before SaveChanges()
I am adding an entity to my database like so:

```<code>public TEntity Add(TEntity entity)
{
     return (TEntity)_database.Set<TEntity>().Add(entity);
}
</code>```

However, the DbSet.Add method isn't returning the newly added entity with the Id etc, it is simply returning the object I passed in to my Add method.

Should it be passing me back the complete new entity including Id, or is it not possible to get the Id before SaveChanges() is called?

答:
All the call to Add() is doing is effectively registering it with the data context so that the entity can be tracked. No actual operation is done against the database at this time until (as you rightly mention) you call SaveChanges().

I'm assuming that you're using automatically-generated Ids in your table; in this case, it's the database engine which will generate that Id when the record is inserted, and Entity Framework will read this back and populate your entity for you.

So, to confirm your suspicions, no - it's not possible to get the Id before SaveChanges() is called in this case.

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
I am adding an entity to my database like so:

public TEntity Add(TEntity entity)
{
     return (TEntity)_database.Set<TEntity>().Add(entity);
}

However, the DbSet.Add method isn't returning the newly added entity with the Id etc, it is simply returning the object I passed in to my Add method.

Should it be passing me back the complete new entity including Id, or is it not possible to get the Id before SaveChanges() is called?


问:
error window is not defined for defining a dynamic variable in node js
I want to make a dynamic variable in node js like this:

```<code>for (let i = 0; i < templates.length; i++) {
    window["t" + i] = i;
}
</code>```

but the error happens:

(node:1300) UnhandledPromiseRejectionWarning: ReferenceError: window
  is not defined

Why is this happening?

答:
You try to refer a window variable, but it doesn't exist, at least not in this context. Note that NodeJS runs on the server, so if this code tries to refer to the window object known at the client-side, then it will fail doing so.

The issue has nothing to do with creating a dynamic variable, for example:

```<code>window = {};
for (let i = 0; i < templates.length; i++) {
    window["t" + i] = i;
}
</code>```

should run without errors, but you probably want to refer to a specific window.

Body:
I want to make a dynamic variable in node js like this:

for (let i = 0; i < templates.length; i++) {
    window["t" + i] = i;
}

but the error happens:

(node:1300) UnhandledPromiseRejectionWarning: ReferenceError: window
  is not defined

Why is this happening?

Body:
You try to refer a window variable, but it doesn't exist, at least not in this context. Note that NodeJS runs on the server, so if this code tries to refer to the window object known at the client-side, then it will fail doing so.

The issue has nothing to do with creating a dynamic variable, for example:

window = {};
for (let i = 0; i < templates.length; i++) {
    window["t" + i] = i;
}

should run without errors, but you probably want to refer to a specific window.


问:
Unable to delete Google Cloud Storage object change notification webhook
I created a webhook to monitor changes on a bucket in 2015 using the command gsutil notification watchbucket https://my-project.appspot.com/myWebHook gs://my-bucket/

Today I would like to delete it but I'm unable to do it.

gsutil notification list -o gs://my-bucket/  is showing me the current webhooks

It is returning something like that:

```<code>Notification channel 1:
        Channel identifier: someid-905e-905e-905e-1fdca170d689
        Resource identifier: myIdentifierXXXfncnI0SuU-U
        Application URL: url=https://my-project.appspot.com/myWebHook&appEngine=true
        Created by:
        Creation time: 2015-09-08 11:44:26.775000
</code>```

when I try to delete it with the command gsutil notification stopchannel someid-905e-905e-905e-1fdca170d689 myIdentifierXXXfncnI0SuU-U

I get this:
NotFoundException: 404 Channel 'someid-905e-905e-905e-1fdca170d689' not found for project '32555940559'

All this is done with my account which is the owner of the project. By the way, the id of the project in the error message is not the one of my project

If I switch to a service account, I get a different error: AccessDeniedException: 403 Caller not owner of subscription

Do you have any idea how I could solve this?

答:
According to the official documentation Object change notification:

There are three steps to configuring authorization in an object change
  notification scenario:

1.Creating a Service Account

2.Configuring gsutil to Use the Service Account

3.Identifying a Domain to Receive Notifications

To be able to remove the notification channel you have to identify the service account used for creating the channel (owner service account of this channel). Then, you have to configure gsutil to use that specific service account and remove the notification channel. Therefore, trying to perform this action by authorizing gsutil using your personal account will not work.

Body:
I created a webhook to monitor changes on a bucket in 2015 using the command gsutil notification watchbucket https://my-project.appspot.com/myWebHook gs://my-bucket/

Today I would like to delete it but I'm unable to do it.

gsutil notification list -o gs://my-bucket/  is showing me the current webhooks

It is returning something like that:

Notification channel 1:
        Channel identifier: someid-905e-905e-905e-1fdca170d689
        Resource identifier: myIdentifierXXXfncnI0SuU-U
        Application URL: url=https://my-project.appspot.com/myWebHook&appEngine=true
        Created by:
        Creation time: 2015-09-08 11:44:26.775000

when I try to delete it with the command gsutil notification stopchannel someid-905e-905e-905e-1fdca170d689 myIdentifierXXXfncnI0SuU-U

I get this:
NotFoundException: 404 Channel 'someid-905e-905e-905e-1fdca170d689' not found for project '32555940559'

All this is done with my account which is the owner of the project. By the way, the id of the project in the error message is not the one of my project

If I switch to a service account, I get a different error: AccessDeniedException: 403 Caller not owner of subscription

Do you have any idea how I could solve this?


问:
How to use format() on a moment.js duration?
Is there any way I can use the moment.js format method on duration objects?  I can't find it anywhere in the docs and it doesn't seen to be an attribute on duration objects.

I'd like to be able to do something like:

```<code>var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')
</code>```

Also, if there are any other libraries which can easily accommodate this sort of functionality, I'd be interested in recommendations.

Thanks!

答:
moment.duration(x).format() has been deprecated.
You can usemoment.utc(4366589).format("HH:mm:ss") to get the desired response.

console.log(moment.utc(4366589).format("HH:mm:ss"))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Body:
Is there any way I can use the moment.js format method on duration objects?  I can't find it anywhere in the docs and it doesn't seen to be an attribute on duration objects.

I'd like to be able to do something like:

var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')

Also, if there are any other libraries which can easily accommodate this sort of functionality, I'd be interested in recommendations.

Thanks!

Body:
moment.duration(x).format() has been deprecated.
You can usemoment.utc(4366589).format("HH:mm:ss") to get the desired response.

console.log(moment.utc(4366589).format("HH:mm:ss"))

<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Cannot set headers after they are sent to client Expressjs router
I'm getting error cannot set headers on express js, I think the problem is have to write setHeader, i was set but stil can't, this my code:

```<code>router.get('/cek', (req, res) => {
const child = execFile(commandd, ['-c', 'config', 'GSM.Radio.C0']);
child.stdout.on('data',
    function (data) {
        value = (JSON.stringify(data));
        x = value.split('.');
        y = JSON.stringify(x[2])
        result = y.replace(/\D/g, "");
        res.setHeader('Content-Type', 'text/html');
        res.send(result);
    }
);

child.stderr.on('data',
    function (data) {
        console.log('err data: ' + data);
    }
);

});
</code>```

I tired to fixing this error for two days, but still cannot, anybody can help?

答:
As stated by Frederico Ibba, this is usually caused after res.send is sent and there is still data being processed... Your workaround for this may simply be to receive all the data before sending it out using res.send. You can try this.

async function executeCommand() {
    return new Promise((resolve, reject) => {
        const child = execFile(commandd, ['-c', 'config', 'GSM.Radio.C0']);

        child.stdout.on('data',
             function (data) {
                value = (JSON.stringify(data));
                x = value.split('.');
                y = JSON.stringify(x[2])
                result = y.replace(/\D/g, "");

                resolve(result);
             }
        );

        child.stderr.on('data',
           function (err) { // Renamed data for err for clarification
               reject(err);
           }
        );
    });
}

router.get('/url', async (req, res) => {
    try {
        const result = await executeCommand();
        res.setHeader('Content-Type', 'text/html');
        res.send(result);
    } catch(error) {
        // There was an error. I'm throwing a 500
        res.sendStatus(500);
    }
});
```

Note that this will be effective only if you are confident that the data is being fired once, as indicated by skirtle

Body:
I'm getting error cannot set headers on express js, I think the problem is have to write setHeader, i was set but stil can't, this my code:

router.get('/cek', (req, res) => {
const child = execFile(commandd, ['-c', 'config', 'GSM.Radio.C0']);
child.stdout.on('data',
    function (data) {
        value = (JSON.stringify(data));
        x = value.split('.');
        y = JSON.stringify(x[2])
        result = y.replace(/\D/g, "");
        res.setHeader('Content-Type', 'text/html');
        res.send(result);
    }
);

child.stderr.on('data',
    function (data) {
        console.log('err data: ' + data);
    }
);

});

I tired to fixing this error for two days, but still cannot, anybody can help?

Body:
As stated by Frederico Ibba, this is usually caused after res.send is sent and there is still data being processed... Your workaround for this may simply be to receive all the data before sending it out using res.send. You can try this.

async function executeCommand() {
    return new Promise((resolve, reject) => {
        const child = execFile(commandd, ['-c', 'config', 'GSM.Radio.C0']);

        child.stdout.on('data',
             function (data) {
                value = (JSON.stringify(data));
                x = value.split('.');
                y = JSON.stringify(x[2])
                result = y.replace(/\D/g, "");

                resolve(result);
             }
        );

        child.stderr.on('data',
           function (err) { // Renamed data for err for clarification
               reject(err);
           }
        );
    });
}

router.get('/url', async (req, res) => {
    try {
        const result = await executeCommand();
        res.setHeader('Content-Type', 'text/html');
        res.send(result);
    } catch(error) {
        // There was an error. I'm throwing a 500
        res.sendStatus(500);
    }
});

Note that this will be effective only if you are confident that the data is being fired once, as indicated by skirtle


问:
Spark with Hive : Table or view not found

ApplicationMaster: User class threw exception: org.apache.spark.sql.AnalysisException: Table or view not found: "DB_X"."table_Y"

Spark session :

```<code>  SparkSession
    .builder()
    .appName(appName)
    .config("spark.sql.warehouse.dir", "/apps/hive/warehouse")
    .enableHiveSupport()
    .getOrCreate();
</code>```

Hive warehouse directory in hive-site.xml : /apps/hive/warehouse/

```<code>hadoop fs -ls /apps/hive/warehouse/
drwxrwxrwx   - root hadoop          0 2018-09-03 11:22 /apps/hive/warehouse/DB_X.db

hadoop fs -ls /apps/hive/warehouse/DB_X.db
none
</code>```

Error is throw here :

```<code>spark
   .read()
   .table("DB_X.table_Y");
</code>```

in java :

```<code>spark.sql("show databases").show()
default
</code>```

in spark-shell interactive :

```<code>spark.sql("show databases").show()
default
DB_X
</code>```

show create table table_Y :

```<code>CREATE EXTERNAL TABLE `table_Y`(
...
PARTITIONED BY (
  `partition` string COMMENT '')
...
    location '/data/kafka-connect/topics/table_Y'
</code>```

hadoop files :

```<code>hadoop fs -ls /data/kafka-connect/topics/table_Y
drwxr-xr-x   - kafka hdfs          0 2018-09-11 17:24 /data/kafka-connect/topics/table_Y/partition=0
drwxr-xr-x   - kafka hdfs          0 2018-09-11 17:24 /data/kafka-connect/topics/table_Y/partition=1

hadoop fs -ls data/kafka-connect/topics/table_Y/partition=0
-rw-r--r--   3 kafka hdfs     102388 2018-09-11 17:24 /data/kafka-connect/topics/table_Y/partition=0/table_Y+0+0001823382+0001824381.avro
-rw-r--r--   3 kafka hdfs     102147 2018-09-11 17:24 /data/kafka-connect/topics/table_Y/partition=0/table_Y+0+0001824382+0001825381.avro
...
</code>```

everythings work fine in spark-shell or hive-shell

hive-site.xml from hive conf is copied in spark2/conf

using HDP 2.6.4.0-91 with spark 2.2

any help ?

答: relocating the table using the HA name solve the problem.</p>

Body:
ApplicationMaster: User class threw exception: org.apache.spark.sql.AnalysisException: Table or view not found: "DB_X"."table_Y"

Spark session :

  SparkSession
    .builder()
    .appName(appName)
    .config("spark.sql.warehouse.dir", "/apps/hive/warehouse")
    .enableHiveSupport()
    .getOrCreate();

Hive warehouse directory in hive-site.xml : /apps/hive/warehouse/

hadoop fs -ls /apps/hive/warehouse/
drwxrwxrwx   - root hadoop          0 2018-09-03 11:22 /apps/hive/warehouse/DB_X.db

hadoop fs -ls /apps/hive/warehouse/DB_X.db
none

Error is throw here :

spark
   .read()
   .table("DB_X.table_Y");

in java :

spark.sql("show databases").show()
default

in spark-shell interactive :

spark.sql("show databases").show()
default
DB_X

show create table table_Y :

CREATE EXTERNAL TABLE `table_Y`(
...
PARTITIONED BY (
  `partition` string COMMENT '')
...
    location '/data/kafka-connect/topics/table_Y'

hadoop files :

hadoop fs -ls /data/kafka-connect/topics/table_Y
drwxr-xr-x   - kafka hdfs          0 2018-09-11 17:24 /data/kafka-connect/topics/table_Y/partition=0
drwxr-xr-x   - kafka hdfs          0 2018-09-11 17:24 /data/kafka-connect/topics/table_Y/partition=1

hadoop fs -ls data/kafka-connect/topics/table_Y/partition=0
-rw-r--r--   3 kafka hdfs     102388 2018-09-11 17:24 /data/kafka-connect/topics/table_Y/partition=0/table_Y+0+0001823382+0001824381.avro
-rw-r--r--   3 kafka hdfs     102147 2018-09-11 17:24 /data/kafka-connect/topics/table_Y/partition=0/table_Y+0+0001824382+0001825381.avro
...

everythings work fine in spark-shell or hive-shell

hive-site.xml from hive conf is copied in spark2/conf

using HDP 2.6.4.0-91 with spark 2.2

any help ?


问:
.NET Razor engine - Implementing layouts
I'm using the following snippet to enable Razor templating in my solution (outside of ASP.NET MVC3). Is it possible to easily implement layouts?

Background info:

I'm at this point (templates are compiled into compiledTemplateAssembly):

```<code>var template = (RazorTemplateBase<TModel>) compiledTemplateAssembly.
    CreateInstance("RazorSpace." + entry.TemplateName + "Template");
template.Model = model;
template.Execute();
var output = template.Buffer.ToString();
template.Buffer.Clear();
return output;
</code>```

I can imagine having a Layout property on my RazorTemplateBase class. But then? I understand that Html.Partial is a helper function which I can just implement to parse a template. But how do I parse those method calls renderBody() or renderSection() to accept other Razor views?

答:
I'm currently working on something very similar. It is a front end templating framework based on Nancy. I extended the Nancy's Razor implementation by Phil Haack. I have managed to get Partials, Templated Helpers and Layouts working.

To render the layout I have a Layout property and inside the layout I have a content placeholder "{{content}}". So when I render the view if the Layout property is set I render the layout and then replace the content placeholder.

The project is called Appia. Have a look at the sample views.

Here is my baseView implementationbaseView implementation and here is the view engine code. It borrows a lot from the MVC Razor implementation and also has some Nancy specific stuff but it shouldn't be too hard to figure out what's happening.

Body:
I'm using the following snippet to enable Razor templating in my solution (outside of ASP.NET MVC3). Is it possible to easily implement layouts?

Background info:

I'm at this point (templates are compiled into compiledTemplateAssembly):

var template = (RazorTemplateBase<TModel>) compiledTemplateAssembly.
    CreateInstance("RazorSpace." + entry.TemplateName + "Template");
template.Model = model;
template.Execute();
var output = template.Buffer.ToString();
template.Buffer.Clear();
return output;

I can imagine having a Layout property on my RazorTemplateBase class. But then? I understand that Html.Partial is a helper function which I can just implement to parse a template. But how do I parse those method calls renderBody() or renderSection() to accept other Razor views?


问:
The response received in AJAX call is shown in another HTML page
I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.

Form HTML

```<code><form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">
    <div class="form-group">
        <input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
        <button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>
    </div>
</form>
</code>```

AJAX

```<code><script>
    $("#AssociateForm").submit(function(e) {
        e.preventDefault();

        var form = $(this);
        var url = form.attr('action');

        var local_id = $('input[name=J_ID]').attr('id');

        var formData = {
            'J_ID' : $('input[name=J_ID]').val()
        };
        console.log(formData)

        $.ajax({
            url: url,
            data: formData,
            dataType: 'json',

            success: function (datas) {
                var data = JSON.parse(datas);
                if(datas.status){
                    alert(datas);
                   //$('#Failure_'+local_id).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')'
                }
            },
            error: function(jqXHR, textStatus){
                alert("In error")
            }
        })
        .done(function(data){
            alert(data)
        });
    });
</script>
</code>```

for some reason, the above code is not printing the console log as well.

But,

When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.

JSON Response

{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

below is from View-Page-source

```<code><html>
   <head></head>
   <body data-gr-c-s-loaded="true">
     <pre style="word-wrap: break-word; white-space: pre-wrap;">

        {"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

     ```

```

答:
This worked for me, I removed the form completely.

Code in-place of Form

```<code> <div class="form-group AssociateForm" style="float:right">
    <input type="text" name="J_ID" style="width:150px;float:left" class="form-control has-success">
    <button name="button" type="submit" id="{{TR.id}}" class="Associater btn btn-primary">Associate</button>
</div>
</code>```

AJAX

```<code><script>
      $('.Associater').on('click', function () {
        var local_id = $(this).attr('id');
        var j_id = $(this).closest("div.AssociateForm").find('input[name=J_ID]').val();

        if (j_id === "") {
            alert("JID cannot be empty")
            return false
        }
        var url = "{% url 'Project:View' 0 %}".replace('0', local_id);

        var formData = {
            'J_ID' : j_id,
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        };
        console.log(local_id);
        console.log(j_id);
        console.log(url);
        console.log(formData);
        $.ajax({
            type: 'POST',
            url: url,
            data: formData,
            dataType: 'json',
            success: function (data) {
                if (data.status) {
                    ele = 'Failure_'+local_id;
                    document.getElementById(ele).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')';
                }
            },
            error: function (jqXHR, textStatus ) {
                alert("For some reason im here");
            }
        });

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

Body:
I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.

Form HTML

<form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">

        <input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
        <button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>

</form>

AJAX

for some reason, the above code is not printing the console log as well.

But,

When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.

JSON Response

{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

below is from View-Page-source

        {"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

Body:
This worked for me, I removed the form completely.

Code in-place of Form

 <div class="form-group AssociateForm" style="float:right">
    <input type="text" name="J_ID" style="width:150px;float:left" class="form-control has-success">
    <button name="button" type="submit" id="{{TR.id}}" class="Associater btn btn-primary">Associate</button>
</div>

AJAX

<script>
      $('.Associater').on('click', function () {
        var local_id = $(this).attr('id');
        var j_id = $(this).closest("div.AssociateForm").find('input[name=J_ID]').val();

        if (j_id === "") {
            alert("JID cannot be empty")
            return false
        }
        var url = "{% url 'Project:View' 0 %}".replace('0', local_id);

        var formData = {
            'J_ID' : j_id,
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        };
        console.log(local_id);
        console.log(j_id);
        console.log(url);
        console.log(formData);
        $.ajax({
            type: 'POST',
            url: url,
            data: formData,
            dataType: 'json',
            success: function (data) {
                if (data.status) {
                    ele = 'Failure_'+local_id;
                    document.getElementById(ele).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')';
                }
            },
            error: function (jqXHR, textStatus ) {
                alert("For some reason im here");
            }
        });

    });
</script>


问:
Overflow in spanned row with one row collapsed
I'd like to have overflow working inside row that is spanned and another being collapsed.

Right now the text is clipped, but when the row is uncollapsed - overflow works.
I tried position: absolute and it works...until you start scrolling. If I start putting position: relative anywhere the text becomes clipped again.

I searched for any hints but I found that this is how Webkit implemented it apparently: https://github.com/w3c/csswg-drafts/issues/478#issuecomment-318539983
There is no problem on Firefox, only on Webkit browsers.

table {
  border-collapse: collapse;
  border: 1px solid black;
}

tr {
  height: 20px;
  positon: relative;
}

td {
  max-width: 100px;
  height: 20px;
  vertical-align: top;
  white-space: nowrap;
  border: 1px solid black;
}

.collapsed {
  visibility: collapse;
}

div {
  height: 300px;
  overflow: scroll;
}

/* span {
  position: absolute;
} */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <table>
    <tbody>
      <tr>
        <td>1</td>
        <td rowspan="2">Very long sentence</td>
      </tr>
      <tr class="row2"><td>2</td></tr>

      <tr>
        <td>1</td>
        <td rowspan="2"><span>Very long sentence</span></td>
      </tr>
      <tr class="row2 collapsed"><td>2</td></tr>

      <tr>
        <td>1</td>
        <td rowspan="2">Very long sentence</td>
      </tr>
      <tr class="row2"><td>2</td></tr>

      <tr>
        <td>1</td>
        <td rowspan="2">Very long sentence</td>
      </tr>
      <tr class="row2"><td>2</td></tr>

      <tr>
        <td>1</td>
        <td rowspan="2">Very long sentence</td>
      </tr>
      <tr class="row2"><td>2</td></tr>

      <tr>
        <td>1</td>
        <td rowspan="2">Very long sentence</td>
      </tr>
      <tr class="row2"><td>2</td></tr>

      <tr>
        <td>1</td>
        <td rowspan="2">Very long sentence</td>
      </tr>
      <tr class="row2"><td>2</td></tr>

      <tr>
        <td>1</td>
        <td rowspan="2">Very long sentence</td>
      </tr>
      <tr class="row2"><td>2</td></tr>

      <tr>
        <td>1</td>
        <td rowspan="2">Very long sentence</td>
      </tr>
      <tr class="row2"><td>2</td></tr>
      <tr>
        <td>1</td>
        <td rowspan="2">Very long sentence</td>
      </tr>
      <tr class="row2"><td>2</td></tr>

      <tr>
        <td>1</td>
        <td rowspan="2">Very long sentence</td>
      </tr>
      <tr class="row2"><td>2</td></tr>
    </tbody>
  </table>
</div></code>```

答:
$(document).ready(function(){

  $("#change").click(function(){

    $(".row2").toggleClass("collapsed");

    // $(".spannedtd").removeAttr("rowspan");

    $('.spannedtd').attr('rowspan', function(index, attr){

        return attr == '2' ? null : '2';

    });

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {

  border-collapse: collapse;

  border: 1px solid black;

}

/* tr{

  height: 20px;

  position: relative;

} */

td{

  max-width: 100px;

/*   height: 20px; */

  vertical-align: top;

  white-space: nowrap;

  border: 1px solid black;

}

.collapsed {

  visibility: collapse;

}

div{

  height: 300px;

  overflow: scroll;

}</code>```

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

<button id="change" class="btn btn-primary">Change Visibility</button>

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

        1

        Data Data Data Data

        2

```

Above code Codepen Link

I have removed the rowspan on button click.

NOTE: Click on the change button above scroll window to see the change in table after applying visibility: collapse

Body:
I'd like to have overflow working inside row that is spanned and another being collapsed.

Right now the text is clipped, but when the row is uncollapsed - overflow works.
I tried position: absolute and it works...until you start scrolling. If I start putting position: relative anywhere the text becomes clipped again.

I searched for any hints but I found that this is how Webkit implemented it apparently: https://github.com/w3c/csswg-drafts/issues/478#issuecomment-318539983
There is no problem on Firefox, only on Webkit browsers.

table {
  border-collapse: collapse;
  border: 1px solid black;
}

tr {
  height: 20px;
  positon: relative;
}

td {
  max-width: 100px;
  height: 20px;
  vertical-align: top;
  white-space: nowrap;
  border: 1px solid black;
}

.collapsed {
  visibility: collapse;
}

div {
  height: 300px;
  overflow: scroll;
}

/* span {
  position: absolute;
} */

        1
        Very long sentence

2

        1
        Very long sentence

2

        1
        Very long sentence

2

        1
        Very long sentence

2

        1
        Very long sentence

2

        1
        Very long sentence

2

        1
        Very long sentence

2

        1
        Very long sentence

2

        1
        Very long sentence

2

        1
        Very long sentence

2

        1
        Very long sentence

2

Body:
$(document).ready(function(){

  $("#change").click(function(){

    $(".row2").toggleClass("collapsed");

    // $(".spannedtd").removeAttr("rowspan");

    $('.spannedtd').attr('rowspan', function(index, attr){

        return attr == '2' ? null : '2';

    });

  });

});

table {

  border-collapse: collapse;

  border: 1px solid black;

}

/* tr{

  height: 20px;

  position: relative;

} */

td{

  max-width: 100px;

/*   height: 20px; */

  vertical-align: top;

  white-space: nowrap;

  border: 1px solid black;

}

.collapsed {

  visibility: collapse;

}

div{

  height: 300px;

  overflow: scroll;

}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="change" class="btn btn-primary">Change Visibility</button>

<br/>

<br/>

<div>

  <table>

    <tbody>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

 <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

      <tr>

        <td>1</td>

        <td rowspan="2" class="spannedtd"><span>Data Data Data Data</span></td>

      </tr>

      <tr class="row2">

        <td>2</td>

      </tr>

    </tbody>

  </table>

</div>

Above code Codepen Link

I have removed the rowspan on button click.

NOTE: Click on the change button above scroll window to see the change in table after applying visibility: collapse


问:
Get Access Token Implicit Instagram Authentification
I'm trying to get access_token for my Instagram app(at the moment just empty container with configured settings, all valid), following this spec
https://www.instagram.com/developer/authentication/
Client-Side (Implicit) Authentication -> Step One: Direct your user to our authorization URL ->
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token

As client_id I'm using my App ID client_id=App ID from there
https://developers.facebook.com/apps/APP_ID/dashboard/
, as a redirect_uri I'm using my wordpress site address.
However instead of access_token there is a error message:
{"error_type": "OAuthException", "code": 400, "error_message": "Invalid platform app"}

What is the reason of such response, is it smth wrong with link parameters CLIENT-ID, REDIRECT-URI or I should post real app not just empty container for testing purposes?

Thanks

答:
The client_id which you are using is the Facebook App ID, but this is incorrect. There is a specific Instagram App ID that you should be using instead. From your App dashboard, on the left side menu, you'll want to find your Instagram App settings (likely by clicking on Instagram "Basic Display" if that is the kind of app you have set up).

From there, after your scroll down a bit on the right, you will see Instagram App ID along with your Instagram App Secret. This Instagram App ID is what you should be using in your authorization URL.


问:
How to change checkbox by icon validate not a input?
I have two forms. #form1 contains the date and the display button. The show button allows you to hide #form1 and display #form2. This form contains the chosen date and a datatable with checkboxes.

When I display the table I want just the checkboxes that verify these two conditions become a 'valid' icon, not the table input.

$(document).ready(function() {
  $("#form2").hide();
  $("#hide").click(function() {
    $("#form1").hide();
    $("#form2").show();
    let dat = $("#dateS").val();
    $("#da").text(dat);
    $("tr").each(function(i, r) {
      let mat = $(r)[0].cells[2].innerText;
      for (var i = 0; i < 2; i++) {
        if (dat == "2020-02-17" && mat == "52") {
          $(r).find("input").first().replaceWith('✔');
        }
      }
    });
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div id="form1">
  <div class=" col-md-10 col-md-offset-1">
    <div class="form-group col-md-3">
      <label for="titre">date</label>
    </div>
    <div class="form-group col-md-5">
      <input type="date" name="dateS" id="dateS" class="form-control">
    </div>
  </div>
  <div class="col-md-6 col-md-offset-3">
    <div class="form-group col-md-2">
      <button class="btn btn-primary" id="hide" data-url="">show</button>
    </div>
  </div>
</div>

<div id="form2">
  <div class="col-md-10 col-md-offset-1">
    <h4>dateS : <span id="da"></span></h4>
  </div>
  <table class="table table-bordered" id="mytable">
    <tr>
      <th><input type="checkbox" id="check_all"></th>
      <th>nom</th>
      <th>matricule</th>
      <th>adresse</th>
      <th>prime</th>
    </tr>
    <tr>
      <td><input type="checkbox" class="checkbox"></td>
      <td>najib</td>
      <td>52</td>
      <td>tihit</td>
      <td><input type="text" name="prime" class="form-control prime" value="0"></td>
    </tr>
    <tr>
      <td><input type="checkbox" class="checkbox"></td>
      <td>adil</td>
      <td>62</td>
      <td>tagmast</td>
      <td><input type="text" name="prime" class="form-control prime" value="0"></td>
    </tr>
  </table>
  <div class="form-group col-md-offset-5 ">
    <button class="btn btn-success add-all" type="submit" id="hide">Pointage men</button>
  </div>
</div></code>```

答:
you need to add the type of input that you want to replace.

$(document).ready(function() {
  $("#form2").hide();
  $("#hide").click(function() {
    $("#form1").hide();
    $("#form2").show();
    let dat = $("#dateS").val();
    $("#da").text(dat);
    $("tr").each(function(i, r) {
      let mat = $(r)[0].cells[2].innerText;
      for (var i = 0; i < 2; i++) {
        if (dat == "2020-02-17" && mat == "52") {
          $(r).find("input:checkbox").replaceWith('✔');

        }
      }
    });
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div id="form1">
  <div class=" col-md-10 col-md-offset-1">
    <div class="form-group col-md-3">
      <label for="titre">date</label>
    </div>
    <div class="form-group col-md-5">
      <input type="date" name="dateS" id="dateS" class="form-control">
    </div>
  </div>
  <div class="col-md-6 col-md-offset-3">
    <div class="form-group col-md-2">
      <button class="btn btn-primary" id="hide" data-url="">show</button>
    </div>
  </div>
</div>

<div id="form2">
  <div class="col-md-10 col-md-offset-1">
    <h4>dateS : <span id="da"></span></h4>
  </div>
  <table class="table table-bordered" id="mytable">
    <tr>
      <th><input type="checkbox" id="check_all"></th>
      <th>nom</th>
      <th>matricule</th>
      <th>adresse</th>
      <th>prime</th>
    </tr>
    <tr>
      <td><input type="checkbox" class="checkbox"></td>
      <td>najib</td>
      <td>52</td>
      <td>tihit</td>
      <td><input type="text" name="prime" class="form-control prime" value="0"></td>
    </tr>
    <tr>
      <td><input type="checkbox" class="checkbox"></td>
      <td>adil</td>
      <td>62</td>
      <td>tagmast</td>
      <td><input type="text" name="prime" class="form-control prime" value="0"></td>
    </tr>
  </table>
  <div class="form-group col-md-offset-5 ">
    <button class="btn btn-success add-all" type="submit" id="hide">Pointage men</button>
  </div>
</div></code>```

Body:
I have two forms. #form1 contains the date and the display button. The show button allows you to hide #form1 and display #form2. This form contains the chosen date and a datatable with checkboxes.

When I display the table I want just the checkboxes that verify these two conditions become a 'valid' icon, not the table input.

$(document).ready(function() {
  $("#form2").hide();
  $("#hide").click(function() {
    $("#form1").hide();
    $("#form2").show();
    let dat = $("#dateS").val();
    $("#da").text(dat);
    $("tr").each(function(i, r) {
      let mat = $(r)[0].cells[2].innerText;
      for (var i = 0; i < 2; i++) {
        if (dat == "2020-02-17" && mat == "52") {
          $(r).find("input").first().replaceWith('✔');
        }
      }
    });
  });
})

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      date

      <input type="date" name="dateS" id="dateS" class="form-control">

      <button class="btn btn-primary" id="hide" data-url="">show</button>

dateS :

      <input type="checkbox" id="check_all">
      nom
      matricule
      adresse
      prime

      <input type="checkbox" class="checkbox">
      najib
      52
      tihit
      <input type="text" name="prime" class="form-control prime" value="0">

      <input type="checkbox" class="checkbox">
      adil
      62
      tagmast
      <input type="text" name="prime" class="form-control prime" value="0">

    <button class="btn btn-success add-all" type="submit" id="hide">Pointage men</button>

Body:
you need to add the type of input that you want to replace.

$(document).ready(function() {
  $("#form2").hide();
  $("#hide").click(function() {
    $("#form1").hide();
    $("#form2").show();
    let dat = $("#dateS").val();
    $("#da").text(dat);
    $("tr").each(function(i, r) {
      let mat = $(r)[0].cells[2].innerText;
      for (var i = 0; i < 2; i++) {
        if (dat == "2020-02-17" && mat == "52") {
          $(r).find("input:checkbox").replaceWith('<span style="color: green;font-weight:  bolder;">✔</span>');

        }
      }
    });
  });
})

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div id="form1">
  <div class=" col-md-10 col-md-offset-1">
    <div class="form-group col-md-3">
      <label for="titre">date</label>
    </div>
    <div class="form-group col-md-5">
      <input type="date" name="dateS" id="dateS" class="form-control">
    </div>
  </div>
  <div class="col-md-6 col-md-offset-3">
    <div class="form-group col-md-2">
      <button class="btn btn-primary" id="hide" data-url="">show</button>
    </div>
  </div>
</div>

<div id="form2">
  <div class="col-md-10 col-md-offset-1">
    <h4>dateS : <span id="da"></span></h4>
  </div>
  <table class="table table-bordered" id="mytable">
    <tr>
      <th><input type="checkbox" id="check_all"></th>
      <th>nom</th>
      <th>matricule</th>
      <th>adresse</th>
      <th>prime</th>
    </tr>
    <tr>
      <td><input type="checkbox" class="checkbox"></td>
      <td>najib</td>
      <td>52</td>
      <td>tihit</td>
      <td><input type="text" name="prime" class="form-control prime" value="0"></td>
    </tr>
    <tr>
      <td><input type="checkbox" class="checkbox"></td>
      <td>adil</td>
      <td>62</td>
      <td>tagmast</td>
      <td><input type="text" name="prime" class="form-control prime" value="0"></td>
    </tr>
  </table>
  <div class="form-group col-md-offset-5 ">
    <button class="btn btn-success add-all" type="submit" id="hide">Pointage men</button>
  </div>
</div>


问:
How do I remove a specific character from an ARM template output?
Is there a way to remove specific characters from an ARM template output? Specifically, I have an output which uses the storagePrimaryEndpointsBlob value so this would be https://storageaccount.blob.core.windows.net/:

```<code>"StoragePrimaryEndpointsBlob": {
  "type": "string",
  "value": "[reference('storage-account').outputs.storagePrimaryEndpointsBlob.value]"
}
</code>```

I would like to remove the trailing '/' from the output.

答:
You can use the substring function on the ARM template.
substring(stringToParse, startIndex, length)

More info

Body:
Is there a way to remove specific characters from an ARM template output? Specifically, I have an output which uses the storagePrimaryEndpointsBlob value so this would be https://storageaccount.blob.core.windows.net/:

"StoragePrimaryEndpointsBlob": {
  "type": "string",
  "value": "[reference('storage-account').outputs.storagePrimaryEndpointsBlob.value]"
}

I would like to remove the trailing '/' from the output.


问:
Why does Jenkins skip the Create First Admin User wizard
I'm working on a docker configuration that creates a Jenkins image which bootstraps it with some default jobs, some ssh keys, and a new view with plugins pre-loaded, etc.

Everything goes well, but when I run it the first time it no longer asks for the initial admin user setup in the wizard.  It does run the plugins installation step and other parts of the wizard, but not the 'create first user' page.

Does anyone know what triggers Jenkins to skip that?

As far as I know, it lets me just log in anonymously and run my jobs.
It's not necessarily a bad thing that I can do this this way, but I'd like to know what might be triggering Jenkins to skip that configuration step.

Unfortunately, I can't easily post my configuration due to work restrictions, etc. so any advice on what to look for would be greatly helpful...

答:
As far as i know These line in the dockerfile is triggering Jenkins to skip the First Admin User wizard:

ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false

That, and other system properties are defined here.


问:
How to present iOS UIActionSheet in Swift?
How can I present a UIActionSheet in Swift within an iOS app?

Here is my code for displaying a UIActionSheet:

```<code>@IBAction func downloadSheet(sender: AnyObject) {
    let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)

    let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Saved")
    })

    let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Deleted")
    })

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Cancelled")
    })
    optionMenu.addAction(deleteAction)
    optionMenu.addAction(saveAction)
    optionMenu.addAction(cancelAction)
    self.presentViewController(optionMenu, animated: true, completion: nil)
}
</code>```

答:
You can use following code for Alert and ActionSheet in Swift 4:</p>
```<code>@IBAction func alert_act(_ sender: Any) {
    do {
        let alert = UIAlertController(title: "Alert", message: "Would you like to continue learning?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        self.present(alert, animated: true, completion: nil)
    }
}

@IBAction func action_sheet1(_ sender: Any) {
    let action_sheet1 = UIAlertController(title: nil, message: "Alert message.", preferredStyle: .actionSheet)

    let defaultAction = UIAlertAction(title: "Default", style: .default, handler: nil)
    let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: nil)
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

    action_sheet1.addAction(defaultAction)
    action_sheet1.addAction(deleteAction)
    action_sheet1.addAction(cancelAction)

    self.present(action_sheet1, animated: true, completion: nil)
}
</code>```

Body:
How can I present a UIActionSheet in Swift within an iOS app?

Here is my code for displaying a UIActionSheet:

@IBAction func downloadSheet(sender: AnyObject) {
    let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)

    let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Saved")
    })

    let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Deleted")
    })

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Cancelled")
    })
    optionMenu.addAction(deleteAction)
    optionMenu.addAction(saveAction)
    optionMenu.addAction(cancelAction)
    self.presentViewController(optionMenu, animated: true, completion: nil)
}

Body:
You can use following code for Alert and ActionSheet in Swift 4:

@IBAction func alert_act(_ sender: Any) {
    do {
        let alert = UIAlertController(title: "Alert", message: "Would you like to continue learning?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        self.present(alert, animated: true, completion: nil)
    }
}

@IBAction func action_sheet1(_ sender: Any) {
    let action_sheet1 = UIAlertController(title: nil, message: "Alert message.", preferredStyle: .actionSheet)

    let defaultAction = UIAlertAction(title: "Default", style: .default, handler: nil)
    let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: nil)
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

    action_sheet1.addAction(defaultAction)
    action_sheet1.addAction(deleteAction)
    action_sheet1.addAction(cancelAction)

    self.present(action_sheet1, animated: true, completion: nil)
}


问:
Android restart service correctly after app is closed
I am currently developing an email application which relies on a background service in order to be able to automatically fetch new emails. This works perfectly when the application is open (or in the running list of apps) but as soon as I close the app / remove it from the recent apps list, the service is also stopped. This can be confirmed by going into the 'Developer Settings' on the device and seeing that there are no processes or services running for my application.

I have read countless threads on StackOverflow but none of them seem to be doing the trick. Sometimes onTaskRemoved() is called and the service is restarted but then other times it isn't called at all or it is called, the logs show that the OS has scheduled a restart of the service but then the service gets forced closed by the OS whereas I always need to have this service running to retrieve new emails.

My current code can be seen below:

My Service:

```<code> @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        Log.i(TAG, "onStartCommand()");

        ...

        Log.d(TAG, "SERVICE IS RUNNING");

        if (host != null) {
            Log.d(TAG, "STARTING PUSH SERVICE");

            Handler handler = new Handler();
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "BR: " + ((BugReporting) getApplication()));
                    sharedRunnable = ((BugReporting) getApplication()).getSharedRunnable();

                    MailPush mailPush = new MailPush(getApplicationContext(), sharedRunnable);
                    Log.d(TAG, "sharedRunnable 1: " + sharedRunnable);
                    mailPush.checkInboxEmail(host, email, password);
                    //mailPush.checkSentEmail(host, email, password);
                }
            };
            handler.postDelayed(runnable, 5000);//0.5 seconds

        }

        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate()");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Log.i(TAG, "onTaskRemoved()");

        PendingIntent service = PendingIntent.getService(
                getApplicationContext(),
                1001,
                new Intent(getApplicationContext(), MyService.class),
                PendingIntent.FLAG_ONE_SHOT);

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy()");
        startService(new Intent(this, MyService.class));
    }
</code>```

Reboot Receiver:

```<code> public class AutoStart extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, MyService.class));
    }
}
</code>```

Manifest:

```<code>    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

...

        <receiver
                android:name="uk.co.tundracorestudios.securemail.notification.AutoStart"
                android:enabled="true"
                android:exported="true"
                android:process=":remote">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
            </receiver>

            <service
                android:name="uk.co.tundracorestudios.securemail.notification.MyService"
                android:enabled="true"
                android:exported="true"
                android:label="@string/mail_service"
                android:stopWithTask="false"/>
</code>```

I did attempt to run MyService as a different process but this then restricted me from getting the sharedRunnable that I have saved in the application class which can otherwise be access through:

```<code> updateListRunnable = ((BugReporting) getApplication()).getSharedRunnable();
</code>```

Therefore, I am asking, how can I ensure that my service continuously runs / works even when the application is closed or when the device is rebooted whilst still having access to the components located in getApplication()?

As when I attempted to run MyService as a separate process, the above updateListRunnable would always return null whereas when the application and service were running in the same process, it would return the correct runnable.

答:
For me restarting the service using AlarmManager from onDestroy didn't work but starting the service from onTaskRemoved worked. When you kill the app while a service is running the onTaskRemoved function is triggered.

```<code>@Override
        public void onTaskRemoved(Intent rootIntent) {
            Log.d(TAG, "onTaskRemoved: removed");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis() + 10000);
((AlarmManager) getSystemService(Context.ALARM_SERVICE)).setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), PendingIntent.getService(getApplicationContext(), 0, new Intent(getApplicationContext(), RegisterReceiverService.class), 0));
            super.onTaskRemoved(rootIntent);
        }
</code>```

So basically once you kill the app the service will be started after 10 seconds.
Note: In case you want to use

```<code>AlarmManager.ELAPSED_REALTIME_WAKEUP
</code>```

the minimum time after which you'll be able to restart the service will be 15 minutes.

Remember you also need to start the service on reboot using BroadcastReceiver.

Body:
I am currently developing an email application which relies on a background service in order to be able to automatically fetch new emails. This works perfectly when the application is open (or in the running list of apps) but as soon as I close the app / remove it from the recent apps list, the service is also stopped. This can be confirmed by going into the 'Developer Settings' on the device and seeing that there are no processes or services running for my application.

I have read countless threads on StackOverflow but none of them seem to be doing the trick. Sometimes onTaskRemoved() is called and the service is restarted but then other times it isn't called at all or it is called, the logs show that the OS has scheduled a restart of the service but then the service gets forced closed by the OS whereas I always need to have this service running to retrieve new emails.

My current code can be seen below:

My Service:

 @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        Log.i(TAG, "onStartCommand()");

        ...

        Log.d(TAG, "SERVICE IS RUNNING");

        if (host != null) {
            Log.d(TAG, "STARTING PUSH SERVICE");

            Handler handler = new Handler();
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "BR: " + ((BugReporting) getApplication()));
                    sharedRunnable = ((BugReporting) getApplication()).getSharedRunnable();

                    MailPush mailPush = new MailPush(getApplicationContext(), sharedRunnable);
                    Log.d(TAG, "sharedRunnable 1: " + sharedRunnable);
                    mailPush.checkInboxEmail(host, email, password);
                    //mailPush.checkSentEmail(host, email, password);
                }
            };
            handler.postDelayed(runnable, 5000);//0.5 seconds

        }

        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate()");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Log.i(TAG, "onTaskRemoved()");

        PendingIntent service = PendingIntent.getService(
                getApplicationContext(),
                1001,
                new Intent(getApplicationContext(), MyService.class),
                PendingIntent.FLAG_ONE_SHOT);

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy()");
        startService(new Intent(this, MyService.class));
    }

Reboot Receiver:

 public class AutoStart extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, MyService.class));
    }
}

Manifest:

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

...

        <receiver
                android:name="uk.co.tundracorestudios.securemail.notification.AutoStart"
                android:enabled="true"
                android:exported="true"
                android:process=":remote">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
            </receiver>

            <service
                android:name="uk.co.tundracorestudios.securemail.notification.MyService"
                android:enabled="true"
                android:exported="true"
                android:label="@string/mail_service"
                android:stopWithTask="false"/>

I did attempt to run MyService as a different process but this then restricted me from getting the sharedRunnable that I have saved in the application class which can otherwise be access through:

 updateListRunnable = ((BugReporting) getApplication()).getSharedRunnable();

Therefore, I am asking, how can I ensure that my service continuously runs / works even when the application is closed or when the device is rebooted whilst still having access to the components located in getApplication()?

As when I attempted to run MyService as a separate process, the above updateListRunnable would always return null whereas when the application and service were running in the same process, it would return the correct runnable.

Body:
For me restarting the service using AlarmManager from onDestroy didn't work but starting the service from onTaskRemoved worked. When you kill the app while a service is running the onTaskRemoved function is triggered.

@Override
        public void onTaskRemoved(Intent rootIntent) {
            Log.d(TAG, "onTaskRemoved: removed");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis() + 10000);
((AlarmManager) getSystemService(Context.ALARM_SERVICE)).setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), PendingIntent.getService(getApplicationContext(), 0, new Intent(getApplicationContext(), RegisterReceiverService.class), 0));
            super.onTaskRemoved(rootIntent);
        }

So basically once you kill the app the service will be started after 10 seconds.
Note: In case you want to use

AlarmManager.ELAPSED_REALTIME_WAKEUP

the minimum time after which you'll be able to restart the service will be 15 minutes.

Remember you also need to start the service on reboot using BroadcastReceiver.


问:
Eliminate Errors
Here is what I am struggling with.

This is a clocking system and I want to take out the errors.

Trying a select statment to get all the records where there is a duplicate "clock in" or duplicate "clock out" for the same user.

You have an employee_ID and a direction.

The data looks something like this:

```<code>ID.......employee_ID.........Direction

 1. .........1..................In
 2. .........2..................In
 3. .........3..................In
 4. .........1..................Out
 5. .........2..................Out
 6. .........3..................In
</code>```

So record 6 would be an error.

答: You could also think about having one row for each shift.  This row would hold both the clock-in and clock-out timestamp.  Your datediff operations would be much less complex with this design.</p>

Title: Eliminate Errors

Body:
Here is what I am struggling with.

This is a clocking system and I want to take out the errors.

Trying a select statment to get all the records where there is a duplicate "clock in" or duplicate "clock out" for the same user.

You have an employee_ID and a direction.

The data looks something like this:

ID.......employee_ID.........Direction

 1. .........1..................In
 2. .........2..................In
 3. .........3..................In
 4. .........1..................Out
 5. .........2..................Out
 6. .........3..................In

So record 6 would be an error.


问:
Translator Text API 3.0: Transliterate
I have followed this document and tried in postman to check for output by giving these parameters and headers

```<code>Headers:
Ocp-Apim-Subscription-Key:****************
Content-Type:application/json
Content-Length:32

Query Params:
api-version:3.0
language:hi
fromScript:Deva
toScript:Latn

body :
[
    {"Text":"मैं हूँ ना"}
]
</code>```

{"error":{"code":400000,"message":"One of the request inputs is not
  valid."}}

I'm not able to get the output. can anyone pls help me here.

答:
You should be able to execute directly on the browser by following the below url,

https://documenter.getpostman.com/view/5155784/RWaEyq9y?version=latest#4e3e8e9b-cdcf-4304-96c9-d4330017e851

You can open up the same request using PostMan in windows.

Title: Translator Text API 3.0: Transliterate

Body:
I have followed this document and tried in postman to check for output by giving these parameters and headers

Headers:
Ocp-Apim-Subscription-Key:****************
Content-Type:application/json
Content-Length:32

Query Params:
api-version:3.0
language:hi
fromScript:Deva
toScript:Latn

body :
[
    {"Text":"मैं हूँ ना"}
]

{"error":{"code":400000,"message":"One of the request inputs is not
  valid."}}

I'm not able to get the output. can anyone pls help me here.


问:
Is there a vmware ansible module that can give all VMs in a specific Data Center with its folder structure too?
I'm trying to write an ansible code that would fetch VMs from a particular datacenter using vmware modules retaining their folder structure. Imagine going through the VMs and Templates view in Vcenter. First we fix a data center and the first folder inside it. We collect all the VMs' detail pertaining to the data center and folder. We then move on to the next folder in the data center, similarly collecting its VM details as well. We do the same till all the VMs of the data center are covered. After this process, I would preferably need the data in json format with the data center and its corresponding folders inside it, with the details of VMs inside each folder respectively.

I've not found a way to organize the VMs in a data center directly this way by using a vmware ansible module. Any suggestion on getting the VMs of a data center with their folder structure would be really helpful.

I've so far tried to peruse through ansible's available Vmware modules but have not had any luck finding a module that searches by the data center and its folders for VMs. So, as of now the best bet for me was to find all VM details in a VCenter (using vmware_vm_facts module) and take each VM and find its folder location in Vcenter (using vmware_guest_find module) iteratively. If I go on with this method, I still have to find a way to organize the resultant data structure into - folder1 -> VMs of folder1, folder2 -> VMs of folder 2,... format.

答:
If you know the datacenter name, you can use vmware_folder_info to get all folders.

A module to list datacenters doen't currently exist, or at least I wasn't able to find it.


问:
Conditional logic vs duplication in MVVM
We have a module with its Views, ViewModels and Models and a requirement came in to have an exact copy of the module, but part of the functionality has to be read-only.
The read-only mode should be turned on by a configuration parameter. The Model part is the same - it will use the same data sources.

I see two possible solutions to this problem:

Change the existing Views and ViewModels, by manipulating controls' interactivity based on the param.
Downsides of this approach is additional conditional logic. We're worried that if we do this, another requirement might come in, where we have to add more conditional logic. Upside - no duplication.

Another way is to split the existing view's into multiple components and assemble the regular module version and the read-only version using those components. We could disable interactivity on the View level in read-only versions and inherit from the ViewModel of the View which we're splitting from and override needed behaviour. The upside would be modularity. Downside - duplication, multiple places to maintain when new components are added in the future.

What's the preferred approach to solve problems like this?

答:
Obviously impossible to give a definitive answer without knowing all the specifics, but I generally take the view that if something is only required once, or maybe even twice, then I'll take the quickest and easiest route. In your case that would be to add conditional logic to the existing classes.

At the third change, I'll review and see if it needs to be split out into a separate entity. but more often than not the third (or even second) change never comes. Don't code for the future, YAGNI.


问:
Code stops at MyObjectBox.build() but no error
My app is having issues which may or may not be down to ObjectBox.

I have made a tiny code change, completely unrelated to ObjectBox but when my app starts there is just a black screen. I've put a lot of logging around the initial lines of code, and I think there is something going wrong at the build() command, though there is nothing in the error log around this.

My code is

```<code>public class DB {

    private File boxStoreDir;
    private static BoxStore store;

    public DB() {
        try {
            Gdx.app.error("aidan","8a");
            createMyObjectBox();
        } catch (IOException e) {
            Gdx.app.error("aidan"," error 8a - "+e.getMessage());
            e.printStackTrace();
        }
    }

    private void createMyObjectBox() throws IOException {
        FileHandle fileHandle = Gdx.files.local("objectstorefile");
        Gdx.app.error("aidan","8b - file="+fileHandle.path());
        if(!fileHandle.isDirectory()) {
            Gdx.app.error("aidan","8b1 - having to call fileHandle.mkdirs()");
            fileHandle.mkdirs();
        }
        boxStoreDir = fileHandle.file();

        if(store == null) {
            Gdx.app.error("aidan","8c - MyObjectBox.builder().directory(boxStoreDir).build()");
            store = MyObjectBox.builder().directory(boxStoreDir).build();
            Gdx.app.error("aidan","8d - store="+store.getNativeStore());
        }
    }
}
</code>```

and the error logs show...

```<code>02-19 20:59:02.052 16625 16694 E aidan   : 8
02-19 20:59:02.052 16625 16694 E aidan   : 8a
02-19 20:59:02.052 16625 16780 W Ads     : Not retrying to fetch app settings
02-19 20:59:02.054 16625 16694 E aidan   : 8b - file=objectstorefile
02-19 20:59:02.054 16625 16694 E aidan   : 8c - MyObjectBox.builder().directory(boxStoreDir).build()
02-19 20:59:02.055  4439  4977 W GamesServiceBroker: Client connected with SDK 200414000, Services 200414037, and Games 157090048
02-19 20:59:02.070  4439 14826 W Ads     : App does not have the required permissions to get location
02-19 20:59:02.078 16625 16662 D skia    : --- Failed to create image decoder with message 'unimplemented'
02-19 20:59:02.080  4439  4569 I PeopleChimeraService: onService. callbacks = zwr@66e7b0d, request = com.google.android.gms.common.internal.GetServiceRequest@f968ac2
</code>```

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

答:
"App does not have the required permissions to get location" seems relevant.

Please try the Android standard way to build ObjectBox:

```<code>    boxStore = MyObjectBox.builder()
            .androidContext(context.getApplicationContext())
            .build();
</code>```

Does that work?

Body:
My app is having issues which may or may not be down to ObjectBox.

I have made a tiny code change, completely unrelated to ObjectBox but when my app starts there is just a black screen. I've put a lot of logging around the initial lines of code, and I think there is something going wrong at the build() command, though there is nothing in the error log around this.

My code is

public class DB {

    private File boxStoreDir;
    private static BoxStore store;

    public DB() {
        try {
            Gdx.app.error("aidan","8a");
            createMyObjectBox();
        } catch (IOException e) {
            Gdx.app.error("aidan"," error 8a - "+e.getMessage());
            e.printStackTrace();
        }
    }

    private void createMyObjectBox() throws IOException {
        FileHandle fileHandle = Gdx.files.local("objectstorefile");
        Gdx.app.error("aidan","8b - file="+fileHandle.path());
        if(!fileHandle.isDirectory()) {
            Gdx.app.error("aidan","8b1 - having to call fileHandle.mkdirs()");
            fileHandle.mkdirs();
        }
        boxStoreDir = fileHandle.file();

        if(store == null) {
            Gdx.app.error("aidan","8c - MyObjectBox.builder().directory(boxStoreDir).build()");
            store = MyObjectBox.builder().directory(boxStoreDir).build();
            Gdx.app.error("aidan","8d - store="+store.getNativeStore());
        }
    }
}

and the error logs show...

02-19 20:59:02.052 16625 16694 E aidan   : 8
02-19 20:59:02.052 16625 16694 E aidan   : 8a
02-19 20:59:02.052 16625 16780 W Ads     : Not retrying to fetch app settings
02-19 20:59:02.054 16625 16694 E aidan   : 8b - file=objectstorefile
02-19 20:59:02.054 16625 16694 E aidan   : 8c - MyObjectBox.builder().directory(boxStoreDir).build()
02-19 20:59:02.055  4439  4977 W GamesServiceBroker: Client connected with SDK 200414000, Services 200414037, and Games 157090048
02-19 20:59:02.070  4439 14826 W Ads     : App does not have the required permissions to get location
02-19 20:59:02.078 16625 16662 D skia    : --- Failed to create image decoder with message 'unimplemented'
02-19 20:59:02.080  4439  4569 I PeopleChimeraService: onService. callbacks = zwr@66e7b0d, request = com.google.android.gms.common.internal.GetServiceRequest@f968ac2

Body:
"App does not have the required permissions to get location" seems relevant.

Please try the Android standard way to build ObjectBox:

    boxStore = MyObjectBox.builder()
            .androidContext(context.getApplicationContext())
            .build();

Does that work?


问:
Downsize 3 queries to a single SQL query for server-side pagination
Essentially I need to recover the result of 3 queries, in a single query (for server-side pagination ordering).
This is a little intricate.

Here is the diagram containing the required fields.

Two column results I need are considered of function related tasks (count).

This first query successfully recover all rows, except two, that i need.

```<code>SELECT DISTINCT vue_cdc_for_opera.libelle as CDC,
                               vue_cdc_for_opera.id_cdc as \"id\",
                               COALESCE(vue_cdc_for_opera.signe_ue, vue_cdc_for_opera.signe_fr) as Signe,
                               vue_cdc_for_opera.classe_ue as \"Classe produit\",
                               vue_cdc_for_opera.code_cdc as \"Code CDC\",
                               dt_bdd_produit.libelle_dt as DT,
                               0 as \"Nombre OCO\",
                               0 as \"Nombre Operateur\"
                FROM vue_cdc_for_opera
                    INNER JOIN cdc_postgresql ON vue_cdc_for_opera.code_cdc = cdc_postgresql.code_cdc
                    INNER JOIN dt_bdd_produit ON vue_cdc_for_opera.id_dt = dt_bdd_produit.id_dt
                    ORDER BY " . $order . " " . $sortOrder . "
                    OFFSET :offset
                    LIMIT :limit
</code>```

In order to obtain the "Nombre Operateur", I run the following query:

```<code>  SELECT
            COUNT(o.id) as \"Nombre Opérateurs\"
            FROM habilitation
            INNER JOIN operateur o ON habilitation.id_operateur = o.id and o.actif = true
            WHERE habilitation.id_cdc_postgresql = :idCdc
            AND habilitation.actif = true
</code>```

in order to obtain the "Nombre OCO", I run the following query:

```<code>SELECT id_oc, oc FROM vue_for_lien_oco_cdc WHERE oc != '' AND code_cdc = :codeCdc;
</code>```

Essentially I need to recover everything in a single query, to be able to order the "Nombre Operateur" and "Nombre OCO" in the server-side pagination, and it's a above my current SQL skills.
The :params refer to binded params later in the PHP code.

I've been told it could be possible with a built-in SQL function inside the query, but I'm not sure where to start.
Is this doable, would you have any lead or can help?

答:
I don't know how to do COALESCE and ON in the first and second queries, using DQL, but for the latest we can have:</p>

```<code>$qb->createQueryBuilder('o')
->from(<insert your entity class here>)
->where('o.oc <> ""')
->andWhere('o.code_cdc = :codeCdc')->setParameter('codeCdc',$<insert variable for code_cdc>)
->getQuery()
->getResult();
</code>```

Body:
Essentially I need to recover the result of 3 queries, in a single query (for server-side pagination ordering).
This is a little intricate.

Here is the diagram containing the required fields.

Two column results I need are considered of function related tasks (count).

This first query successfully recover all rows, except two, that i need.

SELECT DISTINCT vue_cdc_for_opera.libelle as CDC,
                               vue_cdc_for_opera.id_cdc as \"id\",
                               COALESCE(vue_cdc_for_opera.signe_ue, vue_cdc_for_opera.signe_fr) as Signe,
                               vue_cdc_for_opera.classe_ue as \"Classe produit\",
                               vue_cdc_for_opera.code_cdc as \"Code CDC\",
                               dt_bdd_produit.libelle_dt as DT,
                               0 as \"Nombre OCO\",
                               0 as \"Nombre Operateur\"
                FROM vue_cdc_for_opera
                    INNER JOIN cdc_postgresql ON vue_cdc_for_opera.code_cdc = cdc_postgresql.code_cdc
                    INNER JOIN dt_bdd_produit ON vue_cdc_for_opera.id_dt = dt_bdd_produit.id_dt
                    ORDER BY " . $order . " " . $sortOrder . "
                    OFFSET :offset
                    LIMIT :limit

In order to obtain the "Nombre Operateur", I run the following query:

  SELECT
            COUNT(o.id) as \"Nombre Opérateurs\"
            FROM habilitation
            INNER JOIN operateur o ON habilitation.id_operateur = o.id and o.actif = true
            WHERE habilitation.id_cdc_postgresql = :idCdc
            AND habilitation.actif = true

in order to obtain the "Nombre OCO", I run the following query:

SELECT id_oc, oc FROM vue_for_lien_oco_cdc WHERE oc != '' AND code_cdc = :codeCdc;

Essentially I need to recover everything in a single query, to be able to order the "Nombre Operateur" and "Nombre OCO" in the server-side pagination, and it's a above my current SQL skills.
The :params refer to binded params later in the PHP code.

I've been told it could be possible with a built-in SQL function inside the query, but I'm not sure where to start.
Is this doable, would you have any lead or can help?

Body:
I don't know how to do COALESCE and ON in the first and second queries, using DQL, but for the latest we can have:

$qb->createQueryBuilder('o')
->from(<insert your entity class here>)
->where('o.oc <> ""')
->andWhere('o.code_cdc = :codeCdc')->setParameter('codeCdc',$<insert variable for code_cdc>)
->getQuery()
->getResult();


问:
CodePro: where to find the plugin for Intellij Idea?
I have Codepro analytics plugin installed on my eclipse https://dl.google.com/eclipse/inst/codepro/latest/3.7 which I am using since may days. However I don't see any new version coming up for this. I am now shifting to Intellij Idea for my development. However does anybody know that is there any Codepro available for Intellij or how can I use this eclipse plugin in Intellij?

答:
There's no IntelliJ plugin for CodePro and you can't use Eclipse plugins in IDEA.

However, there's a feature in IntelliJ IDEA called 'Inspections': built-in static code analysis tools that help you find probable bugs, locate dead code, detect performance issues, and improve the overall code structure. Its functionality should match that of CodePro's and maybe even exceed it.

Check this IntelliJ documentation page as well.


问:
Can I replace the atomic with a volatile in an one-reader/one-writer queue?
Let us consider the following one-reader/one-writer queue implemented with a linked list.

struct queue {
  queue() {
    tail = head = &reserved;
    n = 0;
  }
  void push(item *it) {
     tail->next = it;
     tail = it;
     n++;
  }
  item* pop() {
     while (n == used);
     ++used;
     head = head->next;
     return head;
  }

  item reserved;
  item *tail, *head;

  int used = 0;
  std::atomic <int> n;
}
```

<p>Now I find that using <code>volatile int n</code> could make my writer run faster, while I'm not sure whether it guarantees that <code>head = head->next</code> can always read the correct value.</p>

<p>UPDATED: What if adding an atomic operation between <code>tail->next</code>, <code>n++</code>, i.e.,</p>

<pre class="lang-cpp prettyprint-override"><code>void push(item *it) {
   tail->next = it;
   tail = it;
   a.store(0, std::memory_order_release);
   a.load(std::memory_order_acquire);
   n++;
}
</code>```

in which a is never accessed by the reader? Will this guarantees the order of tail->next = it and head = head->next? (Still, it runs faster than using atomic n)

答:
As already pointed out in several other comments, volatile is unrelated to multithreading, so it should not be used here. However, the reason why volatile performs better then an atmoic simply is, because with a volatile ++n translates to simple load, inc, store instructions, while with an atomic it translates to a more expensive lock xadd (assuming you compile for x86).

But since this is only a single-reader single-writer queue, you don't need expensive read-modify-write operations:

struct queue {
  queue() {
    tail = head = &reserved;
    n = 0;
  }
  void push(item *it) {
     tail->next = it;
     tail = it;
     auto new_n = n.load(std::memory_order_relaxed) + 1;
     n.store(new_n, std::memory_order_release);
  }
  item* pop() {
     while (n.load(std::memory_order_acquire) == used);
     ++used;
     head = head->next;
     return head;
  }

  item reserved;
  item *tail, *head;

  int used = 0;
  std::atomic <int> n;
}
```

This should perform equally good as a volatile version. If the acquire-load in pop "sees" the value written by the store-release in push, the two operations synchronize-with each other, thereby establishing the required happens-before relation.

Body:
Let us consider the following one-reader/one-writer queue implemented with a linked list.

struct queue {
  queue() {
    tail = head = &reserved;
    n = 0;
  }
  void push(item *it) {
     tail->next = it;
     tail = it;
     n++;
  }
  item* pop() {
     while (n == used);
     ++used;
     head = head->next;
     return head;
  }

  item reserved;
  item *tail, *head;

  int used = 0;
  std::atomic <int> n;
}

Now I find that using volatile int n could make my writer run faster, while I'm not sure whether it guarantees that head = head->next can always read the correct value.

UPDATED: What if adding an atomic operation between tail->next, n++, i.e.,

void push(item *it) {
   tail->next = it;
   tail = it;
   a.store(0, std::memory_order_release);
   a.load(std::memory_order_acquire);
   n++;
}

in which a is never accessed by the reader? Will this guarantees the order of tail->next = it and head = head->next? (Still, it runs faster than using atomic n)

Body:
As already pointed out in several other comments, volatile is unrelated to multithreading, so it should not be used here. However, the reason why volatile performs better then an atmoic simply is, because with a volatile ++n translates to simple load, inc, store instructions, while with an atomic it translates to a more expensive lock xadd (assuming you compile for x86).

But since this is only a single-reader single-writer queue, you don't need expensive read-modify-write operations:

struct queue {
  queue() {
    tail = head = &reserved;
    n = 0;
  }
  void push(item *it) {
     tail->next = it;
     tail = it;
     auto new_n = n.load(std::memory_order_relaxed) + 1;
     n.store(new_n, std::memory_order_release);
  }
  item* pop() {
     while (n.load(std::memory_order_acquire) == used);
     ++used;
     head = head->next;
     return head;
  }

  item reserved;
  item *tail, *head;

  int used = 0;
  std::atomic <int> n;
}

This should perform equally good as a volatile version. If the acquire-load in pop "sees" the value written by the store-release in push, the two operations synchronize-with each other, thereby establishing the required happens-before relation.


问:
How can I get a clip of a MongoDB stored video file？
I've stored some video files in the database using gridfs, because the stored video is accompanied by some information (e.g., the action that the person does in this video, from a few seconds to a few seconds), and GridFs is characterized by block storage, And the data show that the stored file can be partially read without downloading the entire file, how should this video be read?
I'm sorry my English is not very good.

My code like this:

```<code>from pymongo import MongoClient
from gridfs import GridFS
client = MongoClient()
db = client.gridfs
fs = GridFS(db)
grid_out = fs.find({"filename": "--1DO2V4K74"})
data = grid_out[0].read()
out = open('test.mp4', 'wb')
out.write(data)
out.close()
</code>```

I can get a whole video by this. And I want to get a part of the video.

答:
Actually you should not save media(image or video) in DB, you store it in some storage drive(locally or cloud) like s3 bucket, and then store its location url in your DB. and this code might be helpful.

or

You can use Formidable. As It support multipart data(efficient). And for retrieve video you can use fs(file system)

Body:
I've stored some video files in the database using gridfs, because the stored video is accompanied by some information (e.g., the action that the person does in this video, from a few seconds to a few seconds), and GridFs is characterized by block storage, And the data show that the stored file can be partially read without downloading the entire file, how should this video be read?
I'm sorry my English is not very good.

My code like this:

from pymongo import MongoClient
from gridfs import GridFS
client = MongoClient()
db = client.gridfs
fs = GridFS(db)
grid_out = fs.find({"filename": "--1DO2V4K74"})
data = grid_out[0].read()
out = open('test.mp4', 'wb')
out.write(data)
out.close()

I can get a whole video by this. And I want to get a part of the video.


问:
How to access extension function from inner class[AsyncTask] in Kotlin?
I am programming in Kotlin and I have extension function for Date class.

```<code>fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
    val formatter = SimpleDateFormat(format, locale)
    return formatter.format(this)
}
</code>```

It is working fine in onCreate, But inside doInBackground in Async task it gives me error

I have these lines inside doInBackground

```<code>    val currentDateTime = MainActivity().getCurrentDateTime()
    val timeIs = currentDateTime.toString("HH:mm:ss")
</code>```

getCurrentDateTime() returns instance of Date class
and error is given for the arguments inside toString() is

Too may arguments for public open fun toString():String defined in java.util.Date

I think it is trying to apply Java here like Date.toString().

But how should I solve it?

答:
Check, that you imported extension function in your class, also check if it class or instance function, latter would not work.
code snippet of your AsyncTask may help.

Extension function, placed inside class, is a member function of enclosing class, so you need reference to instance of that class, e.g of activity, which - is bad idea.
So, putting extension function to companion object or making it static, using @JvmStatic annotation, will make it accessible from other places.

Body:
I am programming in Kotlin and I have extension function for Date class.

fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
    val formatter = SimpleDateFormat(format, locale)
    return formatter.format(this)
}

It is working fine in onCreate, But inside doInBackground in Async task it gives me error

I have these lines inside doInBackground

    val currentDateTime = MainActivity().getCurrentDateTime()
    val timeIs = currentDateTime.toString("HH:mm:ss")

getCurrentDateTime() returns instance of Date class
and error is given for the arguments inside toString() is

Too may arguments for public open fun toString():String defined in java.util.Date

I think it is trying to apply Java here like Date.toString().

But how should I solve it?