问:
Not able to write in self locked file
I have situation where file is being used by two processes. So I check my process if file is already locked then wait until is unlocked.

And once its unlocked by another process, I put up my lock then start reading and writing to the file. But am getting error like below. I know its a error because its locked by me, but I want to put lock on file first then start reading and writing so that other process could not use it till the time am using.

```<code>Exception in thread "main" java.io.IOException: The process cannot access the file because another process has locked a portion of the file
</code>```

Here is my code snippet

```<code>package RestClient;
import java.io.*;
import java.nio.Buffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;

public class Filelocking {

       public static void main(String[] args) throws IOException {

              String Name = "E:\\RestAPI\\Token.txt";
              File File = new File(Name);
              File FileRename = new File(Name);

              boolean FileEdit = false;

              if (!File.renameTo(FileRename)) {

                     while (!File.renameTo(FileRename)) {
                           System.out.println("rename failed");

                           if (File.renameTo(FileRename)) {
                                  FileEdit = true;
                                  break;
                           }

                     }

              }

              else {

                     FileEdit = true;

              }

              System.out.println("rename success");

              if (FileEdit) {

                  RandomAccessFile AccessFile = new RandomAccessFile(File, "rw");
                  FileChannel channel = AccessFile.getChannel();

                     FileLock lock = null;
                     try {

                           lock = channel.lock();
                           System.out.println("Lock Status: " + lock.isValid());
                           BufferedReader read = new BufferedReader (new FileReader(File));

                           System.out.println( read.readLine());

                     }

                     catch (OverlappingFileLockException e) {

                           System.out.println("File Lock Error: " + e.getMessage());
                     }

                     lock.close();

              }

       }

}
</code>```

Can anyone tell me please how can I fix this and what am doing wrong here ?

答:
It's your own FileLock that's causing the problem. You should read your file from your FileLock.

You should read it like this :

```<code>ByteBuffer buffer = ByteBuffer.allocate(20);
int noOfBytesRead = channel.read(buffer);
</code>```

You can find more info here

If you want readline you could do :

```<code>FileInputStream fin = new FileInputStream(file);
if (FileEdit) {

    RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
    FileChannel channel = accessFile.getChannel();

        FileLock lock = null;
        try {

            lock = channel.lock();
            System.out.println("Lock Status: " + lock.isValid());
            InputStream is = Channels.newInputStream(channel);
            BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            System.out.println(read.readLine());

        } catch (OverlappingFileLockException e) {
              System.out.println("File Lock Error: " + e.getMessage());
        }

        lock.close();

    }
</code>```

As mentionned here

Title: Not able to write in self locked file

Body:
I have situation where file is being used by two processes. So I check my process if file is already locked then wait until is unlocked.

And once its unlocked by another process, I put up my lock then start reading and writing to the file. But am getting error like below. I know its a error because its locked by me, but I want to put lock on file first then start reading and writing so that other process could not use it till the time am using.

Exception in thread "main" java.io.IOException: The process cannot access the file because another process has locked a portion of the file

Here is my code snippet

package RestClient;
import java.io.*;
import java.nio.Buffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;

public class Filelocking {

       public static void main(String[] args) throws IOException {

              String Name = "E:\\RestAPI\\Token.txt";
              File File = new File(Name);
              File FileRename = new File(Name);

              boolean FileEdit = false;

              if (!File.renameTo(FileRename)) {

                     while (!File.renameTo(FileRename)) {
                           System.out.println("rename failed");

                           if (File.renameTo(FileRename)) {
                                  FileEdit = true;
                                  break;
                           }

                     }

              }

              else {

                     FileEdit = true;

              }

              System.out.println("rename success");

              if (FileEdit) {

                  RandomAccessFile AccessFile = new RandomAccessFile(File, "rw");
                  FileChannel channel = AccessFile.getChannel();

                     FileLock lock = null;
                     try {

                           lock = channel.lock();
                           System.out.println("Lock Status: " + lock.isValid());
                           BufferedReader read = new BufferedReader (new FileReader(File));

                           System.out.println( read.readLine());

                     }

                     catch (OverlappingFileLockException e) {

                           System.out.println("File Lock Error: " + e.getMessage());
                     }

                     lock.close();

              }

       }

}

Can anyone tell me please how can I fix this and what am doing wrong here ?

Body:
It's your own FileLock that's causing the problem. You should read your file from your FileLock.

You should read it like this :

ByteBuffer buffer = ByteBuffer.allocate(20);
int noOfBytesRead = channel.read(buffer);

You can find more info here

If you want readline you could do :

FileInputStream fin = new FileInputStream(file);
if (FileEdit) {

    RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
    FileChannel channel = accessFile.getChannel();

        FileLock lock = null;
        try {

            lock = channel.lock();
            System.out.println("Lock Status: " + lock.isValid());
            InputStream is = Channels.newInputStream(channel);
            BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            System.out.println(read.readLine());

        } catch (OverlappingFileLockException e) {
              System.out.println("File Lock Error: " + e.getMessage());
        }

        lock.close();

    }

As mentionned here


来源: stackexchange

问:
Processing records in order in Storm
I'm new to Storm and I'm having problems to figure out how to process records in order.

I have a dataset which contains records with the following fields:

user_id, location_id, time_of_checking

Now, I would like to identify users which have fulfilled the path I specified (for example, users that went from location A to location B to location C).

I'm using Kafka producer and reading this records from a file to simulate live data. Data is sorted by date.

So, to check if my pattern is fulfilled I need to process records in order. The thing is, due to parallelization (bolt replication) I don't get check-ins of user in order. Because of that patterns won't work.

How to overcome this problem? How to process records in order?

答:
Storm supports this use case. For this you just have to ensure that order is maintained throughout your flow in all the involved components. So as first step, in Kafka producer, all the messages for a particular user id should go to the same partition in Kafka. For this you can implement a custom Partitioner in your KafkaProducer. Please refer to the link here for implementation details.

Since a partition in Kafka can be read by one and only one kafkaSpout instance in Storm, the messages in that partition come in order in the spout instance. Thereby ensuring that all the messages of the same user id arrive to the same spout.

Now comes the tricky part - to maintain order in bolt, you want to ensure that you use field grouping on bolt based on "user_id" field emitted from the Kafka spout. A provided kafkaSpout does not break the message to emit field, you would have to override the kafkaSpout to read the message and emit a "user_id" field from the spout. One way of doing so is to have an intermediate bolt which reads the message from the Kafkaspout and emits a stream with "user_id" field.

When finally you specify a bolt with field grouping on "user_id", all messages of a particular user_id value would go to the same instance of the bolt, whatever be the degree of parallelism of the bolt.

A sample topology which work for your case could be as follow -

builder.setSpout("KafkaSpout", Kafkaspout);

builder.setBolt("FieldsEmitterBolt", FieldsEmitterBolt).shuffleGrouping("KafkaSpout");

builder.setBolt("CalculatorBolt", CalculatorBolt).fieldsGrouping("FieldsEmitterBolt", new Fields("user_id")); //user_id field emitted by Bolt2

--Beware, there could be case when all the user_id values come to the same CalculatorBolt instance if you have limited number of user_ids. This in turn would decrease the effective 'parallelism'!

ContentLicense: CC BY-SA 3.0

Title: Processing records in order in Storm


问:
R: csv data ends in one column no matter what reading function I use
I didn't expect to ask my first question here about data reading, but here it comes.
I've got "ugly" data files from brain-imaging machine which are in csv format (basically a raw data + a header/description in few rows on top).

I'd like to use R for some simple subsetting. First of all, when I open the data in Excel, it looks like a mess(all in one column), but when I use a reading function in Excel (data, read from csv) it looks normal(and excel tells me it uses comma as a delimiter).

I've tried to use multiple reading functions(even trying different delimiter options) in R, but the thing always ends up in one long ugly column.
I can bypass it by saving the data in Excel (after first deading them in), but it changes the delimiter and makes it impossible for me to feed the data afterwards to some other custom analysis software.

Thus, I need the data to stay in the same format (and only cut some parts of the raw data) and move on.

Thanks.

Edit: I am adding a link to file download. It is only a few entries of test measurement on my head (there were ~16000 entries before, but I erased most of them to keep it short & private). You can download the csv here

Edit2: Solved. I realized it might be caused by the way how the functions handle the native header, which was the case. It can be avoided by assigning the header (column) names in the script with col.names. Stupid mistake, still lot to learn :).

Edit - the data looks as follows. Rows 1-39 are the header, and the data starts after row 40 which only has the string 'Data'.

```<code>Header
File Version,1.21
Patient Information

Comment,,,
Birth Date,0000/00/00
Age,  0y
Sex,Male
Analyze Information
AnalyzeMode,Continuous
Pre Time[s],9.0
Post Time[s],7.0
Recovery Time[s],12.0
Base Time[s],5
Fitting Degree,1
HPF[Hz],No Filter
LPF[Hz],No Filter
Moving Average[s],0.1
Measure Information

Probe Type,adult
Mode,3x3
Wave[nm],695,830
Wave Length,CH1(700.0),CH1(830.8),CH2(698.3),CH2(828.4),CH3(700.0),CH3(830.8),CH4(698.9),CH4(827.8),CH5(698.3),CH5(828.4),CH6(698.9),CH6(827.8),CH7(698.9),CH7(827.8),CH8(699.2),CH8(830.0),CH9(698.9),CH9(827.8),CH10(703.7),CH10(828.2),CH11(699.2),CH11(830.0),CH12(703.7),CH12(828.2),CH13(700.2),CH13(831.2),CH14(701.4),CH14(828.2),CH15(700.2),CH15(831.2),CH16(699.7),CH16(830.7),CH17(701.4),CH17(828.2),CH18(699.7),CH18(830.7),CH19(699.7),CH19(830.7),CH20(698.1),CH20(831.0),CH21(699.7),CH21(830.7),CH22(698.3),CH22(830.6),CH23(698.1),CH23(831.0),CH24(698.3),CH24(830.6)
Analog Gain,59.60784300,59.60784300,59.60784300,59.60784300,600.00000000,600.00000000,59.60784300,59.60784300,242.35294100,242.35294100,600.00000000,600.00000000,242.35294100,242.35294100,600.00000000,600.00000000,235.29411800,235.29411800,242.35294100,242.35294100,235.29411800,235.29411800,235.29411800,235.29411800,31.29411800,31.29411800,31.29411800,31.29411800,284.70588200,284.70588200,31.29411800,31.29411800,200.00000000,200.00000000,284.70588200,284.70588200,200.00000000,200.00000000,284.70588200,284.70588200,75.29411800,75.29411800,200.00000000,200.00000000,75.29411800,75.29411800,75.29411800,75.29411800
Digital Gain,21.76000000,5.61000000,28.46000000,5.76000000,15.21000000,4.46000000,100.00000000,32.86000000,25.72000000,4.09000000,19.43000000,4.42000000,17.86000000,3.81000000,32.66000000,10.99000000,100.00000000,21.47000000,25.16000000,5.03000000,14.26000000,3.62000000,13.59000000,3.06000000,12.91000000,3.42000000,32.35000000,6.98000000,9.66000000,2.11000000,100.00000000,44.11000000,12.41000000,4.17000000,49.73000000,7.74000000,12.48000000,2.81000000,36.93000000,6.75000000,100.00000000,100.00000000,65.63000000,17.46000000,100.00000000,100.00000000,100.00000000,100.00000000
Sampling Period[s],0.1
StimType,EVENT
Stim Time[s]
F1,15,F2,15,F3,15,F4,15,F5,15,F6,15,F7,15,F8,15,F9,15,M,15
Repeat Count,3
Exception Ch,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

Data
Probe1(Total),CH1,CH2,CH3,CH4,CH5,CH6,CH7,CH8,CH9,CH10,CH11,CH12,CH13,CH14,CH15,CH16,CH17,CH18,CH19,CH20,CH21,CH22,CH23,CH24,Mark,Time,BodyMovement,RemovalMark,PreScan
1,0.01750125,-0.00731065,-0.0229914,-0.01572692,0.04387726,-0.05805205,0.01678475,0.12706034,0.15895581,0.11640126,0.07686448,0.05669941,0.02798176,0.00731046,0.04893643,-0.03621271,0.04504761,0.02515063,0.02962047,0.03181091,-5.10545969,-0.05849782,-2.40030622,42.36789703,0,13:31:07.95,0,0,0
2,-0.01928233,-0.00760579,-0.04548376,0.14481309,-0.02861471,-0.0563355,-0.0301471,-0.07790314,0.0972455,0.08708155,0.02634541,0.03705737,0.00716472,-0.01115488,0.02829455,0.09065069,0.01211305,0.02277327,0.02067163,0.04387939,2.23265266,-0.0207526,-3.71421456,36.16513062,0,13:31:08.06,0,0,0
3,-0.03335796,-0.02295596,-0.07686513,0.01852697,-0.07737321,-0.13283072,-0.10482638,-0.06564587,-0.03146207,0.01997223,-0.02385158,-0.01002161,-0.026086,-0.03784704,-0.02308246,-0.08081956,-0.00761192,0.01914825,-0.00956007,0.00668299,2.47277832,-0.10391754,3.8903904,6.78369522,0,13:31:08.15,0,0,0
</code>```

答:
Here's what you could do to only edit the 'Data' part of your data. </p>

```<code>library(stringr)
library(data.table)
fileName <- 'test_probes.csv'
inString <- readChar(fileName, file.info(fileName)$size)

header <- str_split(inString, 'Data')[[1]][1]
d <- fread(str_split(inString, 'Data')[[1]][2])

## do stuff to d here

# write output to out.csv
write(header, file = 'out.csv')
write('Data', file = 'out.csv', append=T)
write.table(d, file='out.csv', append=T, quote=F, row.names=F, sep=',', col.names=T)
</code>```

Body:
I didn't expect to ask my first question here about data reading, but here it comes.
I've got "ugly" data files from brain-imaging machine which are in csv format (basically a raw data + a header/description in few rows on top).

I'd like to use R for some simple subsetting. First of all, when I open the data in Excel, it looks like a mess(all in one column), but when I use a reading function in Excel (data, read from csv) it looks normal(and excel tells me it uses comma as a delimiter).

I've tried to use multiple reading functions(even trying different delimiter options) in R, but the thing always ends up in one long ugly column.
I can bypass it by saving the data in Excel (after first deading them in), but it changes the delimiter and makes it impossible for me to feed the data afterwards to some other custom analysis software.

Thus, I need the data to stay in the same format (and only cut some parts of the raw data) and move on.

Thanks.

Edit: I am adding a link to file download. It is only a few entries of test measurement on my head (there were ~16000 entries before, but I erased most of them to keep it short & private). You can download the csv here

Edit2: Solved. I realized it might be caused by the way how the functions handle the native header, which was the case. It can be avoided by assigning the header (column) names in the script with col.names. Stupid mistake, still lot to learn :).

Edit - the data looks as follows. Rows 1-39 are the header, and the data starts after row 40 which only has the string 'Data'.

Header
File Version,1.21
Patient Information

Comment,,,
Birth Date,0000/00/00
Age,  0y
Sex,Male
Analyze Information
AnalyzeMode,Continuous
Pre Time[s],9.0
Post Time[s],7.0
Recovery Time[s],12.0
Base Time[s],5
Fitting Degree,1
HPF[Hz],No Filter
LPF[Hz],No Filter
Moving Average[s],0.1
Measure Information

Probe Type,adult
Mode,3x3
Wave[nm],695,830
Wave Length,CH1(700.0),CH1(830.8),CH2(698.3),CH2(828.4),CH3(700.0),CH3(830.8),CH4(698.9),CH4(827.8),CH5(698.3),CH5(828.4),CH6(698.9),CH6(827.8),CH7(698.9),CH7(827.8),CH8(699.2),CH8(830.0),CH9(698.9),CH9(827.8),CH10(703.7),CH10(828.2),CH11(699.2),CH11(830.0),CH12(703.7),CH12(828.2),CH13(700.2),CH13(831.2),CH14(701.4),CH14(828.2),CH15(700.2),CH15(831.2),CH16(699.7),CH16(830.7),CH17(701.4),CH17(828.2),CH18(699.7),CH18(830.7),CH19(699.7),CH19(830.7),CH20(698.1),CH20(831.0),CH21(699.7),CH21(830.7),CH22(698.3),CH22(830.6),CH23(698.1),CH23(831.0),CH24(698.3),CH24(830.6)
Analog Gain,59.60784300,59.60784300,59.60784300,59.60784300,600.00000000,600.00000000,59.60784300,59.60784300,242.35294100,242.35294100,600.00000000,600.00000000,242.35294100,242.35294100,600.00000000,600.00000000,235.29411800,235.29411800,242.35294100,242.35294100,235.29411800,235.29411800,235.29411800,235.29411800,31.29411800,31.29411800,31.29411800,31.29411800,284.70588200,284.70588200,31.29411800,31.29411800,200.00000000,200.00000000,284.70588200,284.70588200,200.00000000,200.00000000,284.70588200,284.70588200,75.29411800,75.29411800,200.00000000,200.00000000,75.29411800,75.29411800,75.29411800,75.29411800
Digital Gain,21.76000000,5.61000000,28.46000000,5.76000000,15.21000000,4.46000000,100.00000000,32.86000000,25.72000000,4.09000000,19.43000000,4.42000000,17.86000000,3.81000000,32.66000000,10.99000000,100.00000000,21.47000000,25.16000000,5.03000000,14.26000000,3.62000000,13.59000000,3.06000000,12.91000000,3.42000000,32.35000000,6.98000000,9.66000000,2.11000000,100.00000000,44.11000000,12.41000000,4.17000000,49.73000000,7.74000000,12.48000000,2.81000000,36.93000000,6.75000000,100.00000000,100.00000000,65.63000000,17.46000000,100.00000000,100.00000000,100.00000000,100.00000000
Sampling Period[s],0.1
StimType,EVENT
Stim Time[s]
F1,15,F2,15,F3,15,F4,15,F5,15,F6,15,F7,15,F8,15,F9,15,M,15
Repeat Count,3
Exception Ch,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

Data
Probe1(Total),CH1,CH2,CH3,CH4,CH5,CH6,CH7,CH8,CH9,CH10,CH11,CH12,CH13,CH14,CH15,CH16,CH17,CH18,CH19,CH20,CH21,CH22,CH23,CH24,Mark,Time,BodyMovement,RemovalMark,PreScan
1,0.01750125,-0.00731065,-0.0229914,-0.01572692,0.04387726,-0.05805205,0.01678475,0.12706034,0.15895581,0.11640126,0.07686448,0.05669941,0.02798176,0.00731046,0.04893643,-0.03621271,0.04504761,0.02515063,0.02962047,0.03181091,-5.10545969,-0.05849782,-2.40030622,42.36789703,0,13:31:07.95,0,0,0
2,-0.01928233,-0.00760579,-0.04548376,0.14481309,-0.02861471,-0.0563355,-0.0301471,-0.07790314,0.0972455,0.08708155,0.02634541,0.03705737,0.00716472,-0.01115488,0.02829455,0.09065069,0.01211305,0.02277327,0.02067163,0.04387939,2.23265266,-0.0207526,-3.71421456,36.16513062,0,13:31:08.06,0,0,0
3,-0.03335796,-0.02295596,-0.07686513,0.01852697,-0.07737321,-0.13283072,-0.10482638,-0.06564587,-0.03146207,0.01997223,-0.02385158,-0.01002161,-0.026086,-0.03784704,-0.02308246,-0.08081956,-0.00761192,0.01914825,-0.00956007,0.00668299,2.47277832,-0.10391754,3.8903904,6.78369522,0,13:31:08.15,0,0,0

Body:
Here's what you could do to only edit the 'Data' part of your data.

library(stringr)
library(data.table)
fileName <- 'test_probes.csv'
inString <- readChar(fileName, file.info(fileName)$size)

header <- str_split(inString, 'Data')[[1]][1]
d <- fread(str_split(inString, 'Data')[[1]][2])

## do stuff to d here

# write output to out.csv
write(header, file = 'out.csv')
write('Data', file = 'out.csv', append=T)
write.table(d, file='out.csv', append=T, quote=F, row.names=F, sep=',', col.names=T)


问:
How to maintain multiple cordova versions in development system?
How can we maintain multiple versions of Cordova in a system . We develop multiple applications and my system currently runs 3.6.3-0.2.12 . But another application that is in development works only upto Cordova v3.5. Is it possible to maintain multiple versions of cordova in one system ?

答:
To piggy-back on the answer from @codevision, you could have an older cordova CLI version and install later platforms.  This would allow you to keep a global CLI for multiple cordova projects, yet have them run on older or later platforms.  To add a specific platform, for example, you can run cordova platform add android@6.3.0

You likely can't install older platforms than your CLI version, but you certainly can install platforms newer than your CLI version.


问:
spring boot 2 M5 oauth authentication issue
I'm using Sprig boot 2 M5 and spring oauth
I have this configuration for my oauth client app

```<code>security:
  oauth2:
    client:
        registration:
            my-client:
                client-id: blabla
                client-secret: asecret
                client-name: a name
                provider: my-provider
                scope: read
                redirect-uri: https://localhost:8780/dp
                authentication-method: basic
                authorization-grant-type: authorization_code
    provider:
        my-provider:
            authorization-uri: https://blabla/oauth-server/oauth/authorize
            token-uri: https://blaba/oauth-server/oauth/token
            user-info-uri: https://lmfr:8780/user
            user-name-attribute: username
</code>```

I was expecting to be redirected to the login page of my Oauth provider but instead I get redirected to the default spring login page.

any suggestion ?

答:
Remove the redirect-uri then it should work

See also this bug

Body:
I'm using Sprig boot 2 M5 and spring oauth
I have this configuration for my oauth client app

security:
  oauth2:
    client:
        registration:
            my-client:
                client-id: blabla
                client-secret: asecret
                client-name: a name
                provider: my-provider
                scope: read
                redirect-uri: https://localhost:8780/dp
                authentication-method: basic
                authorization-grant-type: authorization_code
    provider:
        my-provider:
            authorization-uri: https://blabla/oauth-server/oauth/authorize
            token-uri: https://blaba/oauth-server/oauth/token
            user-info-uri: https://lmfr:8780/user
            user-name-attribute: username

I was expecting to be redirected to the login page of my Oauth provider but instead I get redirected to the default spring login page.

any suggestion ?


问:
Laravel redirect back on submit
I have paginated model in the front-end which has standard CRUD options available. I would like to redirect back to the page I was before I edited or deleted my model.

That means if I was deleting the model on 3rd page, I would like to be redirected to 3rd page, not to original landing page, so naturally I did

```<code>return redirect()->back()
</code>```

the issue with this approach is on the edit when the validation fails. Once validation fails I get redirected to the same edit page, thus effectively making that page the one that back() leads to.

Is there some simple solution to this without having to use sessions for remembering where I was on the time of editing and such?

EDIT: example

I am coming from /customers link

If I edit the customer I will get redirected to /customers?page=5 if there are no errors.

If validation fails, I get redirected back to editing page to fix my errors.

Now when I fix errors so that validation passes, on submit I will get redirected to /customer/{id}/edit instead of /customers?page=5

答:
I think you want withInput() to get back old input values in old function

```<code>return redirect()->back()->withInput();
</code>```

Read about old input

Also check Answer

Title: Laravel redirect back on submit

Body:
I have paginated model in the front-end which has standard CRUD options available. I would like to redirect back to the page I was before I edited or deleted my model.

That means if I was deleting the model on 3rd page, I would like to be redirected to 3rd page, not to original landing page, so naturally I did

return redirect()->back()

the issue with this approach is on the edit when the validation fails. Once validation fails I get redirected to the same edit page, thus effectively making that page the one that back() leads to.

Is there some simple solution to this without having to use sessions for remembering where I was on the time of editing and such?

EDIT: example

I am coming from /customers link

If I edit the customer I will get redirected to /customers?page=5 if there are no errors.

If validation fails, I get redirected back to editing page to fix my errors.

Now when I fix errors so that validation passes, on submit I will get redirected to /customer/{id}/edit instead of /customers?page=5

Body:
I think you want withInput() to get back old input values in old function

return redirect()->back()->withInput();

Read about old input

Also check Answer


问:
R:How to Create an Interaction Plot for Two-Way ANOVA
I am having a coding issue when trying to create an interaction plot of fixed-effects(Model 1) Two-Way ANOVA data.I typed and imported my data from excel into RStudio. The data was as follows.

```<code>Sex Genotype    Activity
Female  I   2.838
Female  I   4.216
Female  I   2.889
Female  I   4.198
Female  II  3.55
Female  II  4.556
Female  II  3.087
Female  II  1.943
Female  III 3.62
Female  III 3.079
Female  III 3.586
Female  III 1.943
Male    I   1.884
Male    I   2.283
Male    I   2.939
Male    I   1.486
Male    II  2.396
Male    II  2.956
Male    II  3.105
Male    II  2.649
Male    III 2.801
Male    III 3.421
Male    III 2.275
Male    III 2.11
</code>```

I then saved it as an Excel Workbook. I then in RStudio went File>Import Dataset>Excel>Selected my dataset file>Selected First Row As Names & Open Data Viewer.
I checked my data and it was all under the three headers in three columns.
Then to do my ANOVA I did:

```<code>Model_1 <- aov(Activity ~ Sex*Genotype, data=data7)
> summary(Model_1)
         Df Sum Sq Mean Sq F value Pr(>F)
Sex           1  3.527   3.527   6.563 0.0196 *
Genotype      2  0.178   0.089   0.165 0.8488
Sex:Genotype  2  1.166   0.583   1.085 0.3591
Residuals    18  9.673   0.537
</code>```

Next, I tried to make an interaction plot:

```<code>interaction.plot(Genotype,Sex,Activity, fun = mean, type= c("b"), xlab=
"Genotype" ,ylab = "Enzyme Activity (enzyme unit (U)=1µmol min-
1)",main="Interaction Plot" )
</code>```

But, when I do so I get this error:

```<code> Error in tapply(response, list(x.factor, trace.factor), fun) : object 'Genotype' not found
</code>```

How do I make Genotype and Sex an object? Shouldn't they already be objects as they show up in the ANOVA table?

Also, I want to make a table of the Mean,SD, and n for each cell, but when I tried to do so using what worked for a one-way ANOVA it did not work for Two-way. How do you make such a table?

I have tried following examples online, but none of them have helped me with the getting the interaction plot to be created, and I have not seen any good examples (even on this site) on how to make a table of mean, SD, and n for Two-way ANOVA that have worked for my situation.
Is there any package that I can use to help me?

If anyone can help explain what I did wrong and how to make the table I would greatly appreciate it.

答:
Two ways to do it.
Using base functions

```<code>#nj is your dataframe which I loaded using
nj <-read.table("nj_data.txt", header = T)
#Base R - using built-in functions
# the Dot indicates variable(column) to work on
# if you have more than one variable use their names
#good practice to use na.rm = T, to make sure you exclude
# NA - missing values, other wise mean and sd will report NA
aggregate(. ~ Sex+Genotype, data = nj,
          FUN = function(x) c(Mean = mean(x, na.rm = T),
                              n = length(x),
                              sd = sd(x, na.rm = T)))

#using dplyr - I suggest this as syntax is nicer
library(dplyr)
nj %>% group_by(Sex, Genotype) %>%
summarise_all(funs(mean(., na.rm = T),sd(., na.rm = T),n()))
#here the "." in mean and sd means using the data given
#equivalent to x in base R above
</code>```

Read-up Tidyverse ( a new bunch of libraries to make data analysis easier)
at https://www.tidyverse.org/

and also ggplot - here's a nice primer on interaction plot using ggplot
https://sebastiansauer.github.io/vis_interaction_effects/

Body:
I am having a coding issue when trying to create an interaction plot of fixed-effects(Model 1) Two-Way ANOVA data.I typed and imported my data from excel into RStudio. The data was as follows.

Sex Genotype    Activity
Female  I   2.838
Female  I   4.216
Female  I   2.889
Female  I   4.198
Female  II  3.55
Female  II  4.556
Female  II  3.087
Female  II  1.943
Female  III 3.62
Female  III 3.079
Female  III 3.586
Female  III 1.943
Male    I   1.884
Male    I   2.283
Male    I   2.939
Male    I   1.486
Male    II  2.396
Male    II  2.956
Male    II  3.105
Male    II  2.649
Male    III 2.801
Male    III 3.421
Male    III 2.275
Male    III 2.11

I then saved it as an Excel Workbook. I then in RStudio went File>Import Dataset>Excel>Selected my dataset file>Selected First Row As Names & Open Data Viewer.
I checked my data and it was all under the three headers in three columns.
Then to do my ANOVA I did:

Model_1 <- aov(Activity ~ Sex*Genotype, data=data7)
> summary(Model_1)
         Df Sum Sq Mean Sq F value Pr(>F)
Sex           1  3.527   3.527   6.563 0.0196 *
Genotype      2  0.178   0.089   0.165 0.8488
Sex:Genotype  2  1.166   0.583   1.085 0.3591
Residuals    18  9.673   0.537

Next, I tried to make an interaction plot:

interaction.plot(Genotype,Sex,Activity, fun = mean, type= c("b"), xlab=
"Genotype" ,ylab = "Enzyme Activity (enzyme unit (U)=1µmol min-
1)",main="Interaction Plot" )

But, when I do so I get this error:

 Error in tapply(response, list(x.factor, trace.factor), fun) : object 'Genotype' not found

How do I make Genotype and Sex an object? Shouldn't they already be objects as they show up in the ANOVA table?

Also, I want to make a table of the Mean,SD, and n for each cell, but when I tried to do so using what worked for a one-way ANOVA it did not work for Two-way. How do you make such a table?

I have tried following examples online, but none of them have helped me with the getting the interaction plot to be created, and I have not seen any good examples (even on this site) on how to make a table of mean, SD, and n for Two-way ANOVA that have worked for my situation.
Is there any package that I can use to help me?

If anyone can help explain what I did wrong and how to make the table I would greatly appreciate it.

Body:
Two ways to do it.
Using base functions

#nj is your dataframe which I loaded using
nj <-read.table("nj_data.txt", header = T)
#Base R - using built-in functions
# the Dot indicates variable(column) to work on
# if you have more than one variable use their names
#good practice to use na.rm = T, to make sure you exclude
# NA - missing values, other wise mean and sd will report NA
aggregate(. ~ Sex+Genotype, data = nj,
          FUN = function(x) c(Mean = mean(x, na.rm = T),
                              n = length(x),
                              sd = sd(x, na.rm = T)))

#using dplyr - I suggest this as syntax is nicer
library(dplyr)
nj %>% group_by(Sex, Genotype) %>%
summarise_all(funs(mean(., na.rm = T),sd(., na.rm = T),n()))
#here the "." in mean and sd means using the data given
#equivalent to x in base R above

Read-up Tidyverse ( a new bunch of libraries to make data analysis easier)
at https://www.tidyverse.org/

and also ggplot - here's a nice primer on interaction plot using ggplot
https://sebastiansauer.github.io/vis_interaction_effects/


问:
Portability of binary serialization of double/float type in C++
The C++ standard does not discuss the underlying layout of float and double types, only the range of values they should represent.  (This is also true for signed types, is it two's compliment or something else)

My question is: What the are techniques used to serialize/deserialize POD types such as double and float in a portable manner? At the moment it seems the only way to do this is to have the value represented literally(as in "123.456"), The ieee754 layout for double is not standard on all architectures.

答:
Brian "Beej Jorgensen" Hall gives in his Guide to Network Programming some code to pack float (resp. double)  to uint32_t (resp. uint64_t) to be able to safely transmit it over the network between two machine that may not both agree to their representation. It has some limitation, mainly it does not support NaN and infinity.

Here is his packing function:

```<code>#define pack754_32(f) (pack754((f), 32, 8))
#define pack754_64(f) (pack754((f), 64, 11))

uint64_t pack754(long double f, unsigned bits, unsigned expbits)
{
    long double fnorm;
    int shift;
    long long sign, exp, significand;
    unsigned significandbits = bits - expbits - 1; // -1 for sign bit

    if (f == 0.0) return 0; // get this special case out of the way

    // check sign and begin normalization
    if (f < 0) { sign = 1; fnorm = -f; }
    else { sign = 0; fnorm = f; }

    // get the normalized form of f and track the exponent
    shift = 0;
    while(fnorm >= 2.0) { fnorm /= 2.0; shift++; }
    while(fnorm < 1.0) { fnorm *= 2.0; shift--; }
    fnorm = fnorm - 1.0;

    // calculate the binary form (non-float) of the significand data
    significand = fnorm * ((1LL<<significandbits) + 0.5f);

    // get the biased exponent
    exp = shift + ((1<<(expbits-1)) - 1); // shift + bias

    // return the final answer
    return (sign<<(bits-1)) | (exp<<(bits-expbits-1)) | significand;
}
</code>```

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

ContentLicense: CC BY-SA 2.5

Body:
Brian "Beej Jorgensen" Hall gives in his Guide to Network Programming some code to pack float (resp. double)  to uint32_t (resp. uint64_t) to be able to safely transmit it over the network between two machine that may not both agree to their representation. It has some limitation, mainly it does not support NaN and infinity.

Here is his packing function:

#define pack754_32(f) (pack754((f), 32, 8))
#define pack754_64(f) (pack754((f), 64, 11))

uint64_t pack754(long double f, unsigned bits, unsigned expbits)
{
    long double fnorm;
    int shift;
    long long sign, exp, significand;
    unsigned significandbits = bits - expbits - 1; // -1 for sign bit

    if (f == 0.0) return 0; // get this special case out of the way

    // check sign and begin normalization
    if (f < 0) { sign = 1; fnorm = -f; }
    else { sign = 0; fnorm = f; }

    // get the normalized form of f and track the exponent
    shift = 0;
    while(fnorm >= 2.0) { fnorm /= 2.0; shift++; }
    while(fnorm < 1.0) { fnorm *= 2.0; shift--; }
    fnorm = fnorm - 1.0;

    // calculate the binary form (non-float) of the significand data
    significand = fnorm * ((1LL<<significandbits) + 0.5f);

    // get the biased exponent
    exp = shift + ((1<<(expbits-1)) - 1); // shift + bias

    // return the final answer
    return (sign<<(bits-1)) | (exp<<(bits-expbits-1)) | significand;
}


问:
C - Matrix input function gets runtime error if matrix is bigger than 5x5, but there is no size defined at the code
I'm using this function to read the input matrix:

```<code>void leMatInt(int **M,int linhas,int colunas){
    int i, j;
    for (i = 0; i < linhas; i++){
      for (j = 0; j < colunas; j++){
        scanf("%d", &M[i][j]);
        //printf("Leu [%d, %d]\n", i, j);
      }
    }
}
</code>```

And I'm creating the matrix like this:

```<code>scanf("%d", &v1);
int **matriz1=(int **)malloc(v1 * sizeof(int));
for(i = 0;i < v1; i++){
    matriz1[i] = (int *)malloc(v1 * sizeof(int));
}
leMatInt(matriz1, v1, v1);
</code>```

The code works nicely for v1 <= 4, but if I try to input a 5v5 matrix, the code gets runtime error at the function.

答:
```<code>int **matriz1=malloc(v1 * sizeof(int*));
</code>```

A double (**) pointer variable will hold pointer to an int.

matriz1 is a pointer to a pointer variable (pointer to a int*).

So it will contain int* variables.

Also casting the return type of malloc is unnecessary and check the return value of malloc.

It's undefined behavior here. That's why it works for 4 unexpectedly but doesn't work for 5x5 matrices.

An example: (Considering a particular case)-

Though sizeof int is implementation defined, but it's usually 4
  bytes. But sizeof pointer is usually 8 byte in 64-bit compiler.

Now to hold 5 int* variable you need 40 byte. But you are allocating 20
  bytes. So you are allocating less memory than what you need. And
  accessing memory that you are not permitted to, invoking undefined
  behavior.

Body:
I'm using this function to read the input matrix:

void leMatInt(int **M,int linhas,int colunas){
    int i, j;
    for (i = 0; i < linhas; i++){
      for (j = 0; j < colunas; j++){
        scanf("%d", &M[i][j]);
        //printf("Leu [%d, %d]\n", i, j);
      }
    }
}

And I'm creating the matrix like this:

scanf("%d", &v1);
int **matriz1=(int **)malloc(v1 * sizeof(int));
for(i = 0;i < v1; i++){
    matriz1[i] = (int *)malloc(v1 * sizeof(int));
}
leMatInt(matriz1, v1, v1);

The code works nicely for v1 <= 4, but if I try to input a 5v5 matrix, the code gets runtime error at the function.

Body:
int **matriz1=malloc(v1 * sizeof(int*));

A double (**) pointer variable will hold pointer to an int.

matriz1 is a pointer to a pointer variable (pointer to a int*).

So it will contain int* variables.

Also casting the return type of malloc is unnecessary and check the return value of malloc.

It's undefined behavior here. That's why it works for 4 unexpectedly but doesn't work for 5x5 matrices.

An example: (Considering a particular case)-

Though sizeof int is implementation defined, but it's usually 4
  bytes. But sizeof pointer is usually 8 byte in 64-bit compiler.

Now to hold 5 int* variable you need 40 byte. But you are allocating 20
  bytes. So you are allocating less memory than what you need. And
  accessing memory that you are not permitted to, invoking undefined
  behavior.


问:
gcloud: permission denied (public key) when ssh-ing to server
I am trying to set up a new ssh key for a gcloud instance. I followed the instructions here verbatim (https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys), generating a new key, putting the public rsa-ssh key with my username on the SSH Keys section of the Metadata tab in the Google Cloud Platform interface, and setting the appropriate permissions for my public and private keys with chmod.

I am getting an error which ends as follows, when attempting to ss using the -vvv verbose flag:

...

debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/erickofman/.ssh/salsadb
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

I have (with a co-worker) ensured that my public key is contained within the authorized_keys file in the server's .ssh folder. Thinking that perhaps something was just stale, I also tried restarting the ssh server using service sshd restart to no avail.

I also tried setting up ssh using the gcloud tool, same result.

I have the correct role/permissions for the site from what I can tell.

This is what the log looks like on the server side:

admin@awesome-website:~$ tail  /var/log/auth.log
Nov 15 20:40:16 awesome-website sshd[18846]: input_userauth_request: invalid user ekofman [preauth]
Nov 15 20:40:17 awesome-website sshd[18846]: Connection closed by 10.100.100.10 port 90001 [preauth]
Nov 15 20:41:17 awesome-website sshd[18848]: Connection closed by 200.200.20.20 port 90002 [preauth]

Been banging my head on this for a bit, any help much appreciated!

答: Whelp, turns out that new ssh keys do not get incorporated unless a full instance restart is effected. Not ssh server restart, but a full instance restart (stop gcloud instance, then start gcloud instance). It doesn't say this in the documentation, good to know for future reference.


问:
How do you change the launcher logo of an app in Android Studio?
I was wondering how to change the launcher icon in Android Studio.</p>

答:
Go to your project folder\app\src\main\res\mipmap-mdpi\ic_launcher.png

You will see 5 mipmap folders. Replace the icon inside of the each mipmap folder, with the icon you want.

ContentLicense: CC BY-SA 4.0


问:
Styling every 3rd and 4th item
I have an array of items that should be displayed as cards. Every 3rd and 4th item should be wider than the others (pattern: narrow - narrow - wide - wide - narrow - narrow - wide - wide... and so on). What I tried so far:

```<code>.card {
    &:nth-child(1n) {width: 33%;}
    &:nth-child(2n) {width: 33%;}
    &:nth-child(3n) {width: 66%;}
    &:nth-child(4n) {width: 66%;}
}
</code>```

Of course this only works for the first 4 items. I want to be able to use this for an infinite amount of items though.
I could figure it out neither with &:nth-child(3n) and similar stuff.

Is it possible to solve this with a css grid?

答:
To select every 3rd and 4th item you can use 4n + 3 and 4n + 4 in nth-child selector.

div > div {
  width: 50px;
  display: inline-block;
  height: 50px;
  border: 1px solid black;
}

div > div:nth-child(4n + 3),
div > div:nth-child(4n + 4){
  width: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div></code>```

Title: Styling every 3rd and 4th item

Body:
I have an array of items that should be displayed as cards. Every 3rd and 4th item should be wider than the others (pattern: narrow - narrow - wide - wide - narrow - narrow - wide - wide... and so on). What I tried so far:

.card {
    &:nth-child(1n) {width: 33%;}
    &:nth-child(2n) {width: 33%;}
    &:nth-child(3n) {width: 66%;}
    &:nth-child(4n) {width: 66%;}
}

Of course this only works for the first 4 items. I want to be able to use this for an infinite amount of items though.
I could figure it out neither with &:nth-child(3n) and similar stuff.

Is it possible to solve this with a css grid?

Body:
To select every 3rd and 4th item you can use 4n + 3 and 4n + 4 in nth-child selector.

div > div {
  width: 50px;
  display: inline-block;
  height: 50px;
  border: 1px solid black;
}

div > div:nth-child(4n + 3),
div > div:nth-child(4n + 4){
  width: 100px;
}

<div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>


问:
What would be a good project to learn node.js
Everyone is talking about NodeJS so I though I'll look into it by creating a usefull project but I cant really think of something usefull to build on NodeJS tha fully demonstrates it's capabilities.

does any of you have a good idea ?

答: Just any website should do. You could for example do a blog involving NodeJS and MongoDB.</p>


问:
Smarty concat string to variable to get another variable
Hi I would like to concat a string into a variable to retrieve the value of another variable let say the example is below

```<code># Variable one
filter_var = "The value to get"
name = "var"

# now I want to retrieve the value of filter_var. What I was thinking is something like this
{{ "filter_".name }} # assuming "name" variable has dynamic content
</code>```

How do I solve this?

Edit:

Another sample is below

```<code>traduction.Product = "the value"
categorie = "Product"

# Now I'm trying to output the value in a div tag
<div>{{ traduction.{{categorie}} }}</div>
</code>```

but I'm getting an error of Expected name or number.

答:
Assuming you're using Smarty 3, you can use this:

```<code>{$filter_{$name}}
</code>```

It's mentioned in the "Variable variables" section on this page: https://www.smarty.net/docs/en/language.syntax.variables.tpl

Body:
Hi I would like to concat a string into a variable to retrieve the value of another variable let say the example is below

# Variable one
filter_var = "The value to get"
name = "var"

# now I want to retrieve the value of filter_var. What I was thinking is something like this
{{ "filter_".name }} # assuming "name" variable has dynamic content

How do I solve this?

Edit:

Another sample is below

traduction.Product = "the value"
categorie = "Product"

# Now I'm trying to output the value in a div tag

{{ traduction.{{categorie}} }}

but I'm getting an error of Expected name or number.

Body:
Assuming you're using Smarty 3, you can use this:

{$filter_{$name}}

It's mentioned in the "Variable variables" section on this page: https://www.smarty.net/docs/en/language.syntax.variables.tpl


问:
C# MVC TinyMCE editor not displaying content in Adobe typekit font
I am using TinyMCE editor 4.7.0. I have a custom Adobe typekit font that I want to display the editor content in. I am loading the typekit in the _Layout file. In my TinyMce.init file I have the following settings:

```<code>font_formats: 'Freight="freight-sans-pro",sans-serif;
Arial=arial,helvetica,sans-serif; Courier New=courier new,courier,monospace;',
</code>```

which makes sure the fonts drop down list has a number of choices.

I also have setup function to set the editor to the font:

```<code> setup: function (ed) {
    // set the editor font size
    ed.on('init', function (e) {
        ed.execCommand("fontSize", false, "16px");
        ed.execCommand("fontName", false, "\"freight-sans-pro\",sans-serif");
    });
},
</code>```

I also have a custom_css pointed to in the init file that contains:

```<code>.tinymcebody {
font-family: "freight-sans-pro",sans-serif;
font-size: 16px;
font-weight: normal;
}
</code>```

My text is not displayed in freight-sans-pro but rather in Arial according to the Chrome developer tools which identifies the rendered font. If set the body of the whole site to have font-family: freight then all content except the TinyMCE editor content is displayed in the right font.

Can anybody help resolve what I am doing wrong in the setup please as it looks like TinyMCE is incapable of using this font and is falling back to a standard sans-serif font?

答:
Try to add the font in theme_advanced_fonts in the TinyMCE init file.</p>

```<code>tinyMCE.init({
    ...
    theme_advanced_fonts : "Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;Freight=freight-sans-pro,sans-serif"
});
</code>```

Body:
I am using TinyMCE editor 4.7.0. I have a custom Adobe typekit font that I want to display the editor content in. I am loading the typekit in the _Layout file. In my TinyMce.init file I have the following settings:

font_formats: 'Freight="freight-sans-pro",sans-serif;
Arial=arial,helvetica,sans-serif; Courier New=courier new,courier,monospace;',

which makes sure the fonts drop down list has a number of choices.

I also have setup function to set the editor to the font:

 setup: function (ed) {
    // set the editor font size
    ed.on('init', function (e) {
        ed.execCommand("fontSize", false, "16px");
        ed.execCommand("fontName", false, "\"freight-sans-pro\",sans-serif");
    });
},

I also have a custom_css pointed to in the init file that contains:

.tinymcebody {
font-family: "freight-sans-pro",sans-serif;
font-size: 16px;
font-weight: normal;
}

My text is not displayed in freight-sans-pro but rather in Arial according to the Chrome developer tools which identifies the rendered font. If set the body of the whole site to have font-family: freight then all content except the TinyMCE editor content is displayed in the right font.

Can anybody help resolve what I am doing wrong in the setup please as it looks like TinyMCE is incapable of using this font and is falling back to a standard sans-serif font?

Body:
Try to add the font in theme_advanced_fonts in the TinyMCE init file.

tinyMCE.init({
    ...
    theme_advanced_fonts : "Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;Freight=freight-sans-pro,sans-serif"
});


问:
Python double for loop
I'm having trouble with my loops. I get an error for 400 being out of range. Am I applying something that is not allowed, or what is my issue? It looks like legal syntax to me? </p>

```<code>survTime=np.array([400, 800, 1100, 900])
age=np.array([40, 40, 40, 40])
counter_1yr=0
counter_2yr=0
counter_3yr=0
n=1
for i in survTime:
     for j in age:
        if survTime[i] > 365 and age[j] < 50:
            counter_1yr+=1
            n+=1
            continue
        elif survTime[i] > 730 and age[j] < 50:
            counter_2yr+=1
            n+=1
            continue
        elif survTime[i] > 1095 and age[j] < 50:
            counter_3yr+=1
            n+=1
            continue
print("1 year probability: ", counter_1yr/n)
print("2 year probability: ", counter_2yr/n)
print("3 year probability: ", counter_3yr/n)
</code>```

答:
for in enables you the iterate over items, not index. I would guess you want to have

```<code>for i in survTime:
    for j in age:
        # now i == survTime[0] and j == age[0]
        if i > 365 and j < 50:
            # more code
</code>```

Or if you want to work with index, use for i in range(len(survTime))

Or if you want to work with both, use for index, value in enumerate(survTime)

Title: Python double for loop

Body:
I'm having trouble with my loops. I get an error for 400 being out of range. Am I applying something that is not allowed, or what is my issue? It looks like legal syntax to me?

survTime=np.array([400, 800, 1100, 900])
age=np.array([40, 40, 40, 40])
counter_1yr=0
counter_2yr=0
counter_3yr=0
n=1
for i in survTime:
     for j in age:
        if survTime[i] > 365 and age[j] < 50:
            counter_1yr+=1
            n+=1
            continue
        elif survTime[i] > 730 and age[j] < 50:
            counter_2yr+=1
            n+=1
            continue
        elif survTime[i] > 1095 and age[j] < 50:
            counter_3yr+=1
            n+=1
            continue
print("1 year probability: ", counter_1yr/n)
print("2 year probability: ", counter_2yr/n)
print("3 year probability: ", counter_3yr/n)

Body:
for in enables you the iterate over items, not index. I would guess you want to have

for i in survTime:
    for j in age:
        # now i == survTime[0] and j == age[0]
        if i > 365 and j < 50:
            # more code

Or if you want to work with index, use for i in range(len(survTime))

Or if you want to work with both, use for index, value in enumerate(survTime)


问:
How to use jquery to populate textarea but mutliple sentences with line break?
```<code><script>
jQuery(document).ready(function($){

$('#user-submitted-title').on('keyup',function(e){
  $('#user-submitted-content').val('Watch this video'+ $(this).val() +'.');
});

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

This will result in:
Watch this video xxx.

I want to add more sentences in new rows...
ass example...

```<code>val('Watch this video'+ $(this).val() +'.');
val('Watch this best video'+ $(this).val() +'.');
val('Watch this great video'+ $(this).val() +'.');
val('Watch this something'+ $(this).val() +'.');
val('Watch this that'+ $(this).val() +'.');
</code>```

All this in up function, how?

答:
Not sure how you are setting the textarea content, but if you use the jQuery val method, \n works consistently in Firefox and IE (Including IE8):

try this : val('Watch this video'+ $(this).val() +'. \n')

var txt = $("textarea#idhere");
txt.val( txt.val() + "\nSomething here\n\nAgain");
Check below  link and it's answer for more help!

jQuery textarea append newline behavior1

DEMO

Body:
This will result in:
Watch this video xxx.

I want to add more sentences in new rows...
ass example...

val('Watch this video'+ $(this).val() +'.');
val('Watch this best video'+ $(this).val() +'.');
val('Watch this great video'+ $(this).val() +'.');
val('Watch this something'+ $(this).val() +'.');
val('Watch this that'+ $(this).val() +'.');

All this in up function, how?


问:
Friendsystem on PHP and MySQL
at this moment I'm stucked on my code.

I want to display the names of accepted friends.

I have two tables:

```<code>Users
[id, useruniqueid, username]

Friends
[id, user_a, user_b, status]
</code>```

(status can be requested, pending or accepted)

For example:

```<code>Users:
1, 123, Kaan2106
2, 321, SOUser1
3, 456, SOU2
4, 654, Some4

Friends:
1, 123, 321, accepted
2, 321, 123, accepted
3, 456, 123, accepted
4, 123, 456, accepted
5, 654, 123, pending
6, 123, 654, requested
</code>```

I want to display my friend(s) names like: "SOUser1" (because it's accepted)

And this is what I done:

```<code><table>
<tr>
    <td>Name</td>
</tr>
<?php
$getem = mysql_query("SELECT * FROM Friends WHERE (`status` = 'accepted') AND (`user_a` = '$UserUUID' OR `user_b` = '$UserUUID') LIMIT 10");
while($row = mysql_fetch_assoc($getem)) {
    $friendsql = mysql_query("SELECT * FROM Users WHERE useruniqueid = '" . ($row['user_a'] == $UserUUID ? $row['user_b'] : $row['user_a']) . "'");
    $friendrow = mysql_fetch_assoc($friendsql);
?>
<tr>
    <td class="friend-name">
        <?php echo $friendrow['username']; ?>
    </td>
</tr>
<?php } ?>
</table>
</code>```

And my output is like this SOUser1, SOUser1, SOU2, SOU2
(unwanted doubles)

The expected output should be like this SOUser1, SOU2
(no doubles)

I know that mysql_* is deprecated

答:
If you do it all in one query (with a join), you can use MySQL's distinct operator to only return one instance of each user's name.

Try using a query like the one below. The join uses a case statement so that it joins the Friends table by either user_a or user_b, depending on which one is not the $UserUUID.

```<code>select distinct
    u.username
from
    Friends f
    join Users u
        on (
            u.useruniqueid = case
                                when f.user_a='{$UserUUID}' then f.user_b
                                else f.user_a
                            end
            )
where
    (f.user_a = '{$UserUUID}' or f.user_b = '{$UserUUID}')
    and f.status='accepted'
</code>```

See it in an SQL Fiddle, with $UserUUID being set to '123'.

Title: Friendsystem on PHP and MySQL

Body:
at this moment I'm stucked on my code.

I want to display the names of accepted friends.

I have two tables:

Users
[id, useruniqueid, username]

Friends
[id, user_a, user_b, status]

(status can be requested, pending or accepted)

For example:

Users:
1, 123, Kaan2106
2, 321, SOUser1
3, 456, SOU2
4, 654, Some4

Friends:
1, 123, 321, accepted
2, 321, 123, accepted
3, 456, 123, accepted
4, 123, 456, accepted
5, 654, 123, pending
6, 123, 654, requested

I want to display my friend(s) names like: "SOUser1" (because it's accepted)

And this is what I done:

    Name

<?php
$getem = mysql_query("SELECT * FROM Friends WHERE (`status` = 'accepted') AND (`user_a` = '$UserUUID' OR `user_b` = '$UserUUID') LIMIT 10");
while($row = mysql_fetch_assoc($getem)) {
    $friendsql = mysql_query("SELECT * FROM Users WHERE useruniqueid = '" . ($row['user_a'] == $UserUUID ? $row['user_b'] : $row['user_a']) . "'");
    $friendrow = mysql_fetch_assoc($friendsql);
?>

        <?php echo $friendrow['username']; ?>

<?php } ?>

And my output is like this SOUser1, SOUser1, SOU2, SOU2
(unwanted doubles)

The expected output should be like this SOUser1, SOU2
(no doubles)

I know that mysql_* is deprecated

Body:
If you do it all in one query (with a join), you can use MySQL's distinct operator to only return one instance of each user's name.

Try using a query like the one below. The join uses a case statement so that it joins the Friends table by either user_a or user_b, depending on which one is not the $UserUUID.

select distinct
    u.username
from
    Friends f
    join Users u
        on (
            u.useruniqueid = case
                                when f.user_a='{$UserUUID}' then f.user_b
                                else f.user_a
                            end
            )
where
    (f.user_a = '{$UserUUID}' or f.user_b = '{$UserUUID}')
    and f.status='accepted'

See it in an SQL Fiddle, with $UserUUID being set to '123'.


问:
How to embed large arrays in Google Cloud Datastore without reaching the 1MB size limit?
My project mainly utilizes two different tools from Google:

Natural Language API to analyze and save entities and syntax of hundreds of docs

Datastore to store each document along with its data retrieved from the Google NL API

I absolutely must save the tokens and entities otherwise I would have to call the Google NL API each and every time I work with a given document.

However, when a document is over a thousand words (i.e. extremely often) I cannot save my document inside Google Datastore.

I receive a 400 error saying entity is too big. It's around 2 to 5MB depending on the topic.

I also have The value of property 'tokens' is longer than 1048487 bytes when I try to Blob it.

I tried serializing the array and turning it into a Blob but same result.

Any way I could make this work without migrating to MongoDB?

答:
I can suggest you 3 options:

Use compression. (tactical) Usually text data are very well compressed. So you may begin to fit into 1MB limit

Use sharding. Split the data in multiple entities and store/read them together. Join on read as needed.

Migrate to blob storage. For example https://cloud.google.com/storage/

There are other options/solutions but this 3 are probably easiest to implement.


问:
Python global variable is not updating it's value in threads
So, I have a guess-the-number type of game in python and I made a threaded server to accept multiple clients to play at once. A thing I want to do is with every answer (S-smaller, H-higher, W-winner, L-loser) I send from the server to the client, to also send a message telling the client how many clients are currently connected, hence client_count. The problem is that the first client will always be told that there is 1 client playing, the second one will be told that there are 2 players and so on. The global variable client_count doesn't seem to update over all the threads.

server.py

```<code>__author__ = 'emil'

import socket
import threading
import random
import struct
import time

random.seed()
start = 1
stop = 2 ** 17 - 1
my_num = random.randint(start, stop)
print('Server number: ', my_num)
mylock = threading.Lock()
client_guessed = False
winner_thread = 0
e = threading.Event()
e.clear()
threads = []
client_count = 0

def worker(cs):
    global mylock, client_guessed, my_num, winner_thread, client_count, e

    my_idcount = client_count
    print('client #', client_count, 'from: ', cs.getpeername())
    message = 'Hello client #' + \
              str(client_count) + \
              ' ! You are entering the number guess competion now !\n' + \
              'There are currently ' + str(len(threads)) + \
              ' players int game.'
    cs.sendall(bytes(message, 'ascii'))

    players_count_message = "There are currently " + str(client_count) + \
                            " players in game."

    while not client_guessed:
        try:
            cnumber = cs.recv(4)

            if client_guessed:
                break

            cnumber = struct.unpack('!I', cnumber)[0]
            if cnumber > my_num:
                cs.sendall(b'S')
                cs.sendall(bytes(players_count_message, 'ascii'))
            if cnumber < my_num:
                cs.sendall(b'H')
                cs.sendall(bytes(players_count_message, 'ascii'))
            if cnumber == my_num:
                mylock.acquire()
                client_guessed = True
                winner_thread = threading.get_ident()
                mylock.release()

        except socket.error as msg:
            print('Error:', msg.strerror)
            break

    if client_guessed:
        if threading.get_ident() == winner_thread:
            cs.sendall(b'G')
            cs.sendall(bytes(players_count_message, 'ascii'))
            print('We have a winner', cs.getpeername())
            print("Thread ", my_idcount, " winner")
            e.set()
        else:
            cs.sendall(b'L')
            cs.sendall(bytes(players_count_message, 'ascii'))
            print("Thread ", my_idcount, " looser")
    time.sleep(1)
    cs.close()
    print("Worker Thread ", my_idcount, " end")

def reset_srv():
    global mylock, client_guessed, winner_thread, my_num, threads, e, client_count
    while True:
        e.wait()
        for thread in threads:
            thread.join()
        print("all threads are finished now")
        e.clear()
        mylock.acquire()
        threads = []
        client_guessed = False
        winner_thread = 0
        client_count = 0
        my_num = random.randint(start, stop)
        print('Server number: ', my_num)
        mylock.release()

if __name__ == '__main__':
    try:
        rs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        rs.bind(('0.0.0.0', 1234))
        rs.listen(5)
    except socket.error as msg:
        print(msg.strerror)
        exit(-1)

    t = threading.Thread(target=reset_srv, daemon=True)
    t.start()

    while True:
        client_socket, addrc = rs.accept()
        t = threading.Thread(target=worker, args=(client_socket,))
        threads.append(t)
        client_count += 1
        t.start()
</code>```

client.py

```<code>__author__ = 'emil'

import socket
import struct
import time

if __name__ == '__main__':
    try:
        s = socket.create_connection(('localhost', 1234))
    except socket.error as msg:
        print("Error: ", msg.strerror)
        exit(-1)

    finished = False

    data = s.recv(1024)
    print(data.decode('ascii'))
    step_count = 0
    while not finished:
        my_num = 0

        while True:
            try:
                my_num = int(input("Enter number: "))
                break
            except ValueError:
                print("Invalid input.")

        try:
            s.sendall(struct.pack('!I', my_num))
            answer = s.recv(1)
            message = s.recv(1024)

            if answer == b'S' or answer == b'H':
                print(message.decode('ascii'))
        except socket.error as msg:
            print('Error: ', msg.strerror)
            s.close()
            exit(-2)
        step_count += 1
        print('Sent ', my_num, ' Answer ', answer.decode('ascii'))
        if answer == b'H':
            sr = my_num
        if answer == b'S':
            er = my_num
        if answer == b'G' or answer == b'L':
            finished = True
        time.sleep(0.25)

    s.close()
    if answer == b'G':
        print("You won with", my_num, "in", step_count, "steps")
    else:
        print("You lost. Someone got it right before you!")
</code>```

答:
You create players_count_message at the first and sent it again and again! Change Your server code to this:

```<code>def worker(cs):
    .
    .
    .
    players_count_message = "There are currently %s players in game."

    while not client_guessed:
        try:
            .
            .
            .
            if cnumber > my_num:
                cs.sendall(b'S')
                cs.sendall(bytes(players_count_message %(str(client_count)), 'ascii'))
            if cnumber < my_num:
                cs.sendall(b'H')
                cs.sendall(bytes(players_count_message %(str(client_count)), 'ascii'))

            .
            .
            .
</code>```

Also, You must check if a players left the game, or connections closed, You must discount that variable.

Body:
So, I have a guess-the-number type of game in python and I made a threaded server to accept multiple clients to play at once. A thing I want to do is with every answer (S-smaller, H-higher, W-winner, L-loser) I send from the server to the client, to also send a message telling the client how many clients are currently connected, hence client_count. The problem is that the first client will always be told that there is 1 client playing, the second one will be told that there are 2 players and so on. The global variable client_count doesn't seem to update over all the threads.

server.py

__author__ = 'emil'

import socket
import threading
import random
import struct
import time

random.seed()
start = 1
stop = 2 ** 17 - 1
my_num = random.randint(start, stop)
print('Server number: ', my_num)
mylock = threading.Lock()
client_guessed = False
winner_thread = 0
e = threading.Event()
e.clear()
threads = []
client_count = 0

def worker(cs):
    global mylock, client_guessed, my_num, winner_thread, client_count, e

    my_idcount = client_count
    print('client #', client_count, 'from: ', cs.getpeername())
    message = 'Hello client #' + \
              str(client_count) + \
              ' ! You are entering the number guess competion now !\n' + \
              'There are currently ' + str(len(threads)) + \
              ' players int game.'
    cs.sendall(bytes(message, 'ascii'))

    players_count_message = "There are currently " + str(client_count) + \
                            " players in game."

    while not client_guessed:
        try:
            cnumber = cs.recv(4)

            if client_guessed:
                break

            cnumber = struct.unpack('!I', cnumber)[0]
            if cnumber > my_num:
                cs.sendall(b'S')
                cs.sendall(bytes(players_count_message, 'ascii'))
            if cnumber < my_num:
                cs.sendall(b'H')
                cs.sendall(bytes(players_count_message, 'ascii'))
            if cnumber == my_num:
                mylock.acquire()
                client_guessed = True
                winner_thread = threading.get_ident()
                mylock.release()

        except socket.error as msg:
            print('Error:', msg.strerror)
            break

    if client_guessed:
        if threading.get_ident() == winner_thread:
            cs.sendall(b'G')
            cs.sendall(bytes(players_count_message, 'ascii'))
            print('We have a winner', cs.getpeername())
            print("Thread ", my_idcount, " winner")
            e.set()
        else:
            cs.sendall(b'L')
            cs.sendall(bytes(players_count_message, 'ascii'))
            print("Thread ", my_idcount, " looser")
    time.sleep(1)
    cs.close()
    print("Worker Thread ", my_idcount, " end")

def reset_srv():
    global mylock, client_guessed, winner_thread, my_num, threads, e, client_count
    while True:
        e.wait()
        for thread in threads:
            thread.join()
        print("all threads are finished now")
        e.clear()
        mylock.acquire()
        threads = []
        client_guessed = False
        winner_thread = 0
        client_count = 0
        my_num = random.randint(start, stop)
        print('Server number: ', my_num)
        mylock.release()

if __name__ == '__main__':
    try:
        rs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        rs.bind(('0.0.0.0', 1234))
        rs.listen(5)
    except socket.error as msg:
        print(msg.strerror)
        exit(-1)

    t = threading.Thread(target=reset_srv, daemon=True)
    t.start()

    while True:
        client_socket, addrc = rs.accept()
        t = threading.Thread(target=worker, args=(client_socket,))
        threads.append(t)
        client_count += 1
        t.start()

client.py

__author__ = 'emil'

import socket
import struct
import time

if __name__ == '__main__':
    try:
        s = socket.create_connection(('localhost', 1234))
    except socket.error as msg:
        print("Error: ", msg.strerror)
        exit(-1)

    finished = False

    data = s.recv(1024)
    print(data.decode('ascii'))
    step_count = 0
    while not finished:
        my_num = 0

        while True:
            try:
                my_num = int(input("Enter number: "))
                break
            except ValueError:
                print("Invalid input.")

        try:
            s.sendall(struct.pack('!I', my_num))
            answer = s.recv(1)
            message = s.recv(1024)

            if answer == b'S' or answer == b'H':
                print(message.decode('ascii'))
        except socket.error as msg:
            print('Error: ', msg.strerror)
            s.close()
            exit(-2)
        step_count += 1
        print('Sent ', my_num, ' Answer ', answer.decode('ascii'))
        if answer == b'H':
            sr = my_num
        if answer == b'S':
            er = my_num
        if answer == b'G' or answer == b'L':
            finished = True
        time.sleep(0.25)

    s.close()
    if answer == b'G':
        print("You won with", my_num, "in", step_count, "steps")
    else:
        print("You lost. Someone got it right before you!")

Body:
You create players_count_message at the first and sent it again and again! Change Your server code to this:

def worker(cs):
    .
    .
    .
    players_count_message = "There are currently %s players in game."

    while not client_guessed:
        try:
            .
            .
            .
            if cnumber > my_num:
                cs.sendall(b'S')
                cs.sendall(bytes(players_count_message %(str(client_count)), 'ascii'))
            if cnumber < my_num:
                cs.sendall(b'H')
                cs.sendall(bytes(players_count_message %(str(client_count)), 'ascii'))

            .
            .
            .

Also, You must check if a players left the game, or connections closed, You must discount that variable.


问:
Checking if item is in list says it is true, then wont let me reference the index because it says the item is not in the list
I create a list:

```<code>temp_cards = []
</code>```

then add values to the list:

```<code>for number in cards:
    for type in suits:
        temp_cards.append(str(number) + " of " + str(type))
</code>```

and then I choose a random value from the list and try to get the index - but it says it isn't in the list.

```<code>dealers_card = random.choice(temp_cards)
y = cards.index(dealers_card)
print(y)
# ValueError: 'Two of Clubs' is not in list
</code>```

but i checked if it is in the list and it says true

```<code>x = dealers_card in temp_cards
print(x)
# True
</code>```

答: temp_cards consists of a series of strings in the format "number of suit". That string is not in cards, which consists of a series of numbers.

Body:
I create a list:

temp_cards = []

then add values to the list:

for number in cards:
    for type in suits:
        temp_cards.append(str(number) + " of " + str(type))

and then I choose a random value from the list and try to get the index - but it says it isn't in the list.

dealers_card = random.choice(temp_cards)
y = cards.index(dealers_card)
print(y)
# ValueError: 'Two of Clubs' is not in list

but i checked if it is in the list and it says true

x = dealers_card in temp_cards
print(x)
# True


问:
searching for all words in a 5x5 matrix
My objective is to find all words 2 to 5 letters in length from a 5x5 matrix. my search method works but it does not work for every word in the dictionary.

Search method:

```<code>public static void Search(char board[][])
{
    int X = board.length;
    int Y = board[0].length;
    //Mark all characters as not visited
    boolean visited[][] = new boolean[X][Y];
    //Initialize current string
    String str = "";
    //Consider every character and look for all words
    //starting with this character
    for(int i=0;i<X;i++)
    {
        for(int j=0;j<Y;j++)
        {
            System.out.println("Starting at: "+i+" "+j);
            WordsFound(board, visited, i, j, str);
        }
    }
}
</code>```

WordsFound method:

```<code>public static void WordsFound(char board[][], boolean visited[][], int i, int j, String str)
{
    visited[i][j] = true;
    if(str.length() == 5)
        return;
    str = str + board[i][j];
    //If the word is present in dictionary, then print it
    if(isWord(str))
        System.out.println("Found Word: "+str);
    int X = board.length;
    int Y = board[0].length;
    //Search the word in the 5 by 5 matrix.
    for(int row=i-1;row<=i+1 && row<X;row++)
    {
        for(int col=j-1;col<=j+1 && col<Y;col++)
        {
            if(row>=0 && col>=0 && !visited[row][col])
                //Call the method WordsFound.
                WordsFound(board,visited, row, col, str);
        }
    }
    if(str != null && str.length() > 0 )
    {
        str = str.substring(0, str.length()-1);
    }
    visited[i][j] = false;
}
</code>```

main class:

```<code>public static void main(String[] args) throws FileNotFoundException
{
    readFile("dictionary.txt");
    char board[][] = {
            {'R','A','H','J','M'},
            {'Y','U','W','W','K'},
            {'R','X','N','F','M'},
            {'Q','G','E','E','B'},
            {'E','O','A','P','E'}};
    System.out.println("R A H J M\nY U W W K\nR X N F M\nQ G E E B\nE O A P E");
    System.out.println("");
    Search(board);
}
</code>```

My program does find the word "RAW" but why doesn't it find the word "RUN"?

Running the program just showing the index 0 0:

```<code>R A H J M
Y U W W K
R X N F M
Q G E E B
E O A P E

Starting at: 0 0
Found Word: RAY
Found Word: RAW
</code>```

答:
To find "RUN", you need to ensure when you are in "U", "N" is not already visited, otherwise you won't go to that cell.

But since you are running dfs, the "N" cell might already be visited from a cell around it other than "U", which will set visited for "N" true, and search from "U" will fail.

To solve it, you will need to have 3D visited, where apart from indexes, you will also need to store path traversed so far. (i.e the string so far)

EDIT: I'm from python. So I wasn't aware of the complexity of mixing int and string as I suggested for visited variable. Just use hash of the string instead of the direct string, it will also be a lot space-efficient.

Title: searching for all words in a 5x5 matrix

Body:
My objective is to find all words 2 to 5 letters in length from a 5x5 matrix. my search method works but it does not work for every word in the dictionary.

Search method:

public static void Search(char board[][])
{
    int X = board.length;
    int Y = board[0].length;
    //Mark all characters as not visited
    boolean visited[][] = new boolean[X][Y];
    //Initialize current string
    String str = "";
    //Consider every character and look for all words
    //starting with this character
    for(int i=0;i<X;i++)
    {
        for(int j=0;j<Y;j++)
        {
            System.out.println("Starting at: "+i+" "+j);
            WordsFound(board, visited, i, j, str);
        }
    }
}

WordsFound method:

public static void WordsFound(char board[][], boolean visited[][], int i, int j, String str)
{
    visited[i][j] = true;
    if(str.length() == 5)
        return;
    str = str + board[i][j];
    //If the word is present in dictionary, then print it
    if(isWord(str))
        System.out.println("Found Word: "+str);
    int X = board.length;
    int Y = board[0].length;
    //Search the word in the 5 by 5 matrix.
    for(int row=i-1;row<=i+1 && row<X;row++)
    {
        for(int col=j-1;col<=j+1 && col<Y;col++)
        {
            if(row>=0 && col>=0 && !visited[row][col])
                //Call the method WordsFound.
                WordsFound(board,visited, row, col, str);
        }
    }
    if(str != null && str.length() > 0 )
    {
        str = str.substring(0, str.length()-1);
    }
    visited[i][j] = false;
}

main class:

public static void main(String[] args) throws FileNotFoundException
{
    readFile("dictionary.txt");
    char board[][] = {
            {'R','A','H','J','M'},
            {'Y','U','W','W','K'},
            {'R','X','N','F','M'},
            {'Q','G','E','E','B'},
            {'E','O','A','P','E'}};
    System.out.println("R A H J M\nY U W W K\nR X N F M\nQ G E E B\nE O A P E");
    System.out.println("");
    Search(board);
}

My program does find the word "RAW" but why doesn't it find the word "RUN"?

Running the program just showing the index 0 0:

R A H J M
Y U W W K
R X N F M
Q G E E B
E O A P E

Starting at: 0 0
Found Word: RAY
Found Word: RAW


问:
How Can I Detect If One Div Is Outside Another Div?
I am making a game and I am using div's instead of canvas.rect's and I want one div to always be inside of another div. I ran into this problem when I made a test script that looked like this.

        var mousex, mousey;
          function mousepos(e){
            mousex = e.clientX;
            mousey = e.clientY;
            document.getElementById("xy").innerText = mousex + " , " + mousey;
          }
          function testdiv(){
            document.getElementById("testdiv").style.left = mousex;
            document.getElementById("testdiv").style.top = mousey;
            setTimeout(testdiv, 30);
          }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>          #city{
            border: 1px dotted white;
            background-color: lightgreen;
            height: 500;
            width: 500;
            resize: both;
            overflow: hidden;
            max-height: 500px;
            max-width: 500px;
            min-height: 100px;
            min-width: 100px;
          }
          #xy{
            color: white;
          }
          #testdiv{
            background-color: white;
            position: absolute;
            width: 100px;
            height: 100px;
          }
          #body{
            background-color: black;
          }</code>```

     ```

The code detects your mouse X and mouse Y when your mouse is over the big green div, then it puts the white div's left corner on your mouse X and mouse Y. My problem is that when my mouse is draging the white div down or right, I can drag it off of the green div.

Is there a way I could fix this problem?

答:
Since there are no supported parent selectors in the current JS.

You could either use Jquery or CSS, I am listing both Javascript options, and CSS options

Option 1: $("a.active").parents('li').css("property", "value");

Option 2: Sibling Combination to match any ParentElement
element that is preceded by an ChildElement element.

// Just change the parent and child elemets below
ParentElement ~ ChildElement {
    property: value;
}

Body:
I am making a game and I am using div's instead of canvas.rect's and I want one div to always be inside of another div. I ran into this problem when I made a test script that looked like this.

        var mousex, mousey;
          function mousepos(e){
            mousex = e.clientX;
            mousey = e.clientY;
            document.getElementById("xy").innerText = mousex + " , " + mousey;
          }
          function testdiv(){
            document.getElementById("testdiv").style.left = mousex;
            document.getElementById("testdiv").style.top = mousey;
            setTimeout(testdiv, 30);
          }

          #city{
            border: 1px dotted white;
            background-color: lightgreen;
            height: 500;
            width: 500;
            resize: both;
            overflow: hidden;
            max-height: 500px;
            max-width: 500px;
            min-height: 100px;
            min-width: 100px;
          }
          #xy{
            color: white;
          }
          #testdiv{
            background-color: white;
            position: absolute;
            width: 100px;
            height: 100px;
          }
          #body{
            background-color: black;
          }

The code detects your mouse X and mouse Y when your mouse is over the big green div, then it puts the white div's left corner on your mouse X and mouse Y. My problem is that when my mouse is draging the white div down or right, I can drag it off of the green div.

Is there a way I could fix this problem?


问:
Excel: Leading Zeros on Dates.. Formula to do it for me?
Is there a way to add a leading zero to a date that is 7 digits and should be 8?

7301982 should be 07301982.

I have a column full of these values, and need a way to do so with a formula. Any ideas?

答: Simply go to custom for the format of the number and select yyyy\m\d and add more m or d to it.</p>


问:
Remove Seaborn barplot legend title
I use seaborn to plot a grouped bar plot as in https://seaborn.pydata.org/examples/factorplot_bars.html

Giving me:
https://seaborn.pydata.org/_images/factorplot_bars.png

there is a title (sex) on the legend which I would like to remove.

How could I achieve that?

答:
If you want the legend to be shown outside of the plot axis, as is default for factorplot, you can use FacetGrid.add_legend (factorplot returns a FacetGrid instance). Other methods allow you to adjust the labels of every axis in the FacetGrid at once

```<code>import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

# Load the example Titanic dataset
titanic = sns.load_dataset("titanic")

# Draw a nested barplot to show survival for class and sex
g = sns.factorplot(x="class", y="survived", hue="sex", data=titanic,
                   size=6, kind="bar", palette="muted", legend=False)
(g.despine(left=True)
  .set_ylabels('survival probability')
  .add_legend(title='Whatever you want')
)
</code>```

Title: Remove Seaborn barplot legend title

Body:
If you want the legend to be shown outside of the plot axis, as is default for factorplot, you can use FacetGrid.add_legend (factorplot returns a FacetGrid instance). Other methods allow you to adjust the labels of every axis in the FacetGrid at once

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

# Load the example Titanic dataset
titanic = sns.load_dataset("titanic")

# Draw a nested barplot to show survival for class and sex
g = sns.factorplot(x="class", y="survived", hue="sex", data=titanic,
                   size=6, kind="bar", palette="muted", legend=False)
(g.despine(left=True)
  .set_ylabels('survival probability')
  .add_legend(title='Whatever you want')
)


问:
Adding shine effect to a table row
I'm trying to add a shine effect to a table row following this fiddle: http://jsfiddle.net/nqQc7/511/

```<code>.gold:after {
  animation: shine 1.5s infinite linear alternate;
  content: "";
  position: absolute;
  top: -110%;
  left: -210%;
  width: 200%;
  height: 200%;
  opacity: 0;
  transform: rotate(30deg);

  background: rgba(255, 255, 255, 0.13);
  background: linear-gradient(
    to right,
    rgba(255, 255, 255, 0.13) 0%,
    rgba(255, 255, 255, 0.13) 77%,
    rgba(255, 255, 255, 0.5) 92%,
    rgba(255, 255, 255, 0.0) 100%
  );
}

.gold:active:after {
  opacity: 0;
}

@keyframes shine{
  to {
    opacity: 1;
    top: -30%;
    left: -30%;
    transition-property: left, top, opacity;
    transition-duration: 0.7s, 0.7s, 0.15s;
    transition-timing-function: ease;
  }
}
</code>```

But I can't seem to get it right, the effect is overflowing the table: https://jsfiddle.net/uokvjaxx/2/

I added the class to just one table row and the effect goes through the whole table:

```<code><table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr class="gold">
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>
</code>```

Is there a way to limit the effect to just the table row without affecting how the row displays?

答:
Maybe something like this will get you closer to where you want. Customize as you need and don't forget vendor prefixes if you need to support different browsers.

.gold {
 background: linear-gradient(-45deg, #fff087, #eccf02, #fff087);
 background-size: 50% 100%;
 animation: linear-gradient 10s linear infinite;
}

@keyframes linear-gradient {
 0% {
  background-position: 0% 50%
 }

 100% {
  background-position: 400% 400%
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table style="width:100%">
 <tr>
  <th>Firstname</th>
  <th>Lastname</th>
  <th>Age</th>
 </tr>
 <tr class="gold">
  <td>Jill</td>
  <td>Smith</td>
  <td>50</td>
 </tr>
 <tr>
  <td>Eve</td>
  <td>Jackson</td>
  <td>94</td>
 </tr>
</table></code>```

Title: Adding shine effect to a table row

Body:
I'm trying to add a shine effect to a table row following this fiddle: http://jsfiddle.net/nqQc7/511/

.gold:after {
  animation: shine 1.5s infinite linear alternate;
  content: "";
  position: absolute;
  top: -110%;
  left: -210%;
  width: 200%;
  height: 200%;
  opacity: 0;
  transform: rotate(30deg);

  background: rgba(255, 255, 255, 0.13);
  background: linear-gradient(
    to right,
    rgba(255, 255, 255, 0.13) 0%,
    rgba(255, 255, 255, 0.13) 77%,
    rgba(255, 255, 255, 0.5) 92%,
    rgba(255, 255, 255, 0.0) 100%
  );
}

.gold:active:after {
  opacity: 0;
}

@keyframes shine{
  to {
    opacity: 1;
    top: -30%;
    left: -30%;
    transition-property: left, top, opacity;
    transition-duration: 0.7s, 0.7s, 0.15s;
    transition-timing-function: ease;
  }
}

But I can't seem to get it right, the effect is overflowing the table: https://jsfiddle.net/uokvjaxx/2/

I added the class to just one table row and the effect goes through the whole table:

    Firstname
    Lastname
    Age

    Jill
    Smith
    50

    Eve
    Jackson
    94

Is there a way to limit the effect to just the table row without affecting how the row displays?

Body:
Maybe something like this will get you closer to where you want. Customize as you need and don't forget vendor prefixes if you need to support different browsers.

.gold {
 background: linear-gradient(-45deg, #fff087, #eccf02, #fff087);
 background-size: 50% 100%;
 animation: linear-gradient 10s linear infinite;
}

@keyframes linear-gradient {
 0% {
  background-position: 0% 50%
 }

 100% {
  background-position: 400% 400%
 }
}

<table style="width:100%">
 <tr>
  <th>Firstname</th>
  <th>Lastname</th>
  <th>Age</th>
 </tr>
 <tr class="gold">
  <td>Jill</td>
  <td>Smith</td>
  <td>50</td>
 </tr>
 <tr>
  <td>Eve</td>
  <td>Jackson</td>
  <td>94</td>
 </tr>
</table>


问:
AS2 .swf loadmovie() and unloadmovie() fail when nested inside an AS3 .swf container
I have an AS2 .swf being loaded as a child of a parent AS3 .swf.  The AS2.swf calls loadmovie() and unloadmovie() to display 3 jpeg files.  The images load the first time, but after that, a call to loadmovie() to replace the image, or a call to unloadmovie() fail.  I found the following Adobe Bug report (https://bugs.adobe.com/jira/browse/ASC-3338?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel) that has said this has been resolved, and also said that child movieclips could be replaced without a problem.  Here is the code I'm calling.

```<code>_root.help_mc.scenes_image1_mc.loadMovie("first.jpg");
_root.help_mc.scenes_image2_mc.loadMovie("second.jpg");
_root.help_mc.scenes_image3_mc.loadMovie("third.jpg");

_root.help_mc.scenes_image1_mc.unloadMovie();
_root.help_mc.scenes_image2_mc.unloadMovie();
_root.help_mc.scenes_image3_mc.unloadMovie();
</code>```

I'm not well versed in ActionScript, so I'm afraid I might not be referencing the movieclip in the correct way.  The bug report said child swf's cannot replace themseleves, but if the AS2 swf is acting as the psuedo root, can I reference the movieclip through the AS2 swf?

答:
AS2 doesn't work along-side AS3. Flash Player 9 and above have two different virtual machines - one for AS1, AS2 and the other for AS3 and only one of them is loaded at once, meaning that you can execute either AS3 or AS2 but not both.

http://en.wikipedia.org/wiki/ActionScript#Timeline_by_ActionScript_version

Body:
I have an AS2 .swf being loaded as a child of a parent AS3 .swf.  The AS2.swf calls loadmovie() and unloadmovie() to display 3 jpeg files.  The images load the first time, but after that, a call to loadmovie() to replace the image, or a call to unloadmovie() fail.  I found the following Adobe Bug report (https://bugs.adobe.com/jira/browse/ASC-3338?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel) that has said this has been resolved, and also said that child movieclips could be replaced without a problem.  Here is the code I'm calling.

_root.help_mc.scenes_image1_mc.loadMovie("first.jpg");
_root.help_mc.scenes_image2_mc.loadMovie("second.jpg");
_root.help_mc.scenes_image3_mc.loadMovie("third.jpg");

_root.help_mc.scenes_image1_mc.unloadMovie();
_root.help_mc.scenes_image2_mc.unloadMovie();
_root.help_mc.scenes_image3_mc.unloadMovie();

I'm not well versed in ActionScript, so I'm afraid I might not be referencing the movieclip in the correct way.  The bug report said child swf's cannot replace themseleves, but if the AS2 swf is acting as the psuedo root, can I reference the movieclip through the AS2 swf?


问:
Load object from table with id as foreign key
i have define users with UserRole type Role as foreing key of another table. Entiti framework auto transformed name UserRole to UserRoleId with type integer (Id). Its ok. But i have UserRoleId = 2 in table User table preview
and when i trying get user by Id:

```<code>var user = await _userManager.FindByIdAsync(id);
</code>```

so parameter UserRole is null user preview from debuging.

Application user:

```<code>public class ApplicationUser : IdentityUser
{
    public int PriorityLevel { get; set; }
    public Role UserRole { get; set; }
    public string ForName { get; set; }
    public string LastName { get; set; }
    public string Mobile { get; set; }
    public string WorkPlace { get; set; }
    public string Notice { get; set; }
}
</code>```

Must i use some entity framework command for load UserRole as type Role? Or can i get UserRoleId from table?

Thanks for any advice.

答:
You tagged your question with Entity Framework, but just in case, I'll cover Entity Framework Core, as well, since they diverge slightly on this.

Entity Framework supports lazy-loading, but importantly, the property must be virtual to enable that, i.e.:

```<code>public virtual Role UserRole { get; set; }
</code>```

EF adds the logic necessary to do lazy-load the property by deriving a dynamic "proxy" class from your entity and overriding the property. Since non-virtual properties cannot be overridden, this logic is not added to properties without virtual.  Without virtual, navigation properties will not be loaded automatically, and will remain null, whether there's associations in the database or not.

Entity Framework Core does not support lazy-loading at all, so adding virtual will not help you.

In either case, you should really be eager-loading, instead. This is done by adding Include to your query. However, you have two problems there:

UserManager<TUser> doesn't support including related entities. You would need to use the DbSet, i.e. context.Users.

You cannot use Include with Find (or any of the Find-related methods), as it has logic that is incompatible with doing joins. Namely, Find attempts to pull the entity from the context cache without doing a query at all, if possible, and as such, cannot guarantee that navigation properties can be included. As a result, you will have to switch to something like SingleOrDefault.

```<code>var user = await context.Users.Include(x => x.UserRole).SingleOrDefault(x => x.Id == id);
</code>```

With that, UserRole should now actually have a value.

Alternatively, you should be able to explicitly-load UserRole:

```<code>var user = await _userManager.FindByIdAsync(id);
context.Entry(user).Reference(s => s.UserRole).Load();
</code>```

This methodology is the same in both Entity Framework and Entity Framework Core. However it was only introduced into EF Core in 1.1, so be cognizant of the version you're running. The one downside here is that this will result in (potentially) two queries. Again, since the Find methods attempt to retrieve from the context cache, it's possible you'll avoid a query there, but the entity is not in the cache, it will take two queries: one for the user and one for the related role. However, that would have been the case as well with lazy-loading. Only eagerly-loading allows the queries to be combined using JOINs.

Body:
i have define users with UserRole type Role as foreing key of another table. Entiti framework auto transformed name UserRole to UserRoleId with type integer (Id). Its ok. But i have UserRoleId = 2 in table User table preview
and when i trying get user by Id:

var user = await _userManager.FindByIdAsync(id);

so parameter UserRole is null user preview from debuging.

Application user:

public class ApplicationUser : IdentityUser
{
    public int PriorityLevel { get; set; }
    public Role UserRole { get; set; }
    public string ForName { get; set; }
    public string LastName { get; set; }
    public string Mobile { get; set; }
    public string WorkPlace { get; set; }
    public string Notice { get; set; }
}

Must i use some entity framework command for load UserRole as type Role? Or can i get UserRoleId from table?

Thanks for any advice.

Body:
You tagged your question with Entity Framework, but just in case, I'll cover Entity Framework Core, as well, since they diverge slightly on this.

Entity Framework supports lazy-loading, but importantly, the property must be virtual to enable that, i.e.:

public virtual Role UserRole { get; set; }

EF adds the logic necessary to do lazy-load the property by deriving a dynamic "proxy" class from your entity and overriding the property. Since non-virtual properties cannot be overridden, this logic is not added to properties without virtual.  Without virtual, navigation properties will not be loaded automatically, and will remain null, whether there's associations in the database or not.

Entity Framework Core does not support lazy-loading at all, so adding virtual will not help you.

In either case, you should really be eager-loading, instead. This is done by adding Include to your query. However, you have two problems there:

UserManager<TUser> doesn't support including related entities. You would need to use the DbSet, i.e. context.Users.

You cannot use Include with Find (or any of the Find-related methods), as it has logic that is incompatible with doing joins. Namely, Find attempts to pull the entity from the context cache without doing a query at all, if possible, and as such, cannot guarantee that navigation properties can be included. As a result, you will have to switch to something like SingleOrDefault.

var user = await context.Users.Include(x => x.UserRole).SingleOrDefault(x => x.Id == id);

With that, UserRole should now actually have a value.

Alternatively, you should be able to explicitly-load UserRole:

var user = await _userManager.FindByIdAsync(id);
context.Entry(user).Reference(s => s.UserRole).Load();

This methodology is the same in both Entity Framework and Entity Framework Core. However it was only introduced into EF Core in 1.1, so be cognizant of the version you're running. The one downside here is that this will result in (potentially) two queries. Again, since the Find methods attempt to retrieve from the context cache, it's possible you'll avoid a query there, but the entity is not in the cache, it will take two queries: one for the user and one for the related role. However, that would have been the case as well with lazy-loading. Only eagerly-loading allows the queries to be combined using JOINs.


问:
My favicon code isn't working.... I did the code like it said in a guide
So I'm building a website for my friend using Github hosting, and I want it to have a favicon. I have implemented this code: </p>

```<code><!--Favicon-->
    <!-- Opera Speed Dial Favicon -->
  <link rel="icon" type="image/png" href="favicon.png" />

<!-- Standard Favicon -->
  <link rel="icon" type="image/x-icon" href="favicon.ico" />

<!-- For iPhone 4 Retina display: -->
  <link rel="apple-touch-icon-precomposed" sizes="114x114" href="favicon.png">

<!-- For iPad: -->
  <link rel="apple-touch-icon-precomposed" sizes="72x72" href="favicon.png">

<!-- For iPhone: -->
  <link rel="apple-touch-icon-precomposed" href="favicon.png">
</code>```

<p>but whenever I open the page, there's no favicon. I got the code from this guide here, but alas, it's not working... If someone could help me it'd be greatly appreciated... The github pages version can be found here. </p>

答: You've put the <link> tag for the favicon inside the  tag, but it needs to be in the

Body:
So I'm building a website for my friend using Github hosting, and I want it to have a favicon. I have implemented this code:

  <link rel="icon" type="image/png" href="favicon.png" />

  <link rel="icon" type="image/x-icon" href="favicon.ico" />

  <link rel="apple-touch-icon-precomposed" sizes="114x114" href="favicon.png">

  <link rel="apple-touch-icon-precomposed" sizes="72x72" href="favicon.png">

  <link rel="apple-touch-icon-precomposed" href="favicon.png">

but whenever I open the page, there's no favicon. I got the code from this guide here, but alas, it's not working... If someone could help me it'd be greatly appreciated... The github pages version can be found here.

Body: You've put the <link> tag for the favicon inside the <body> tag, but it needs to be in the <head>