问:
Saving output (context) embeddings in word2vec (gensim implementation) as a final model
I have studied word2vec implementation in gensim, I am aware that input vectors are in syn0, output vectors are in syn1 and syn1neg if negative sampling.

I know I can access similarity between input and output embeddings like this:

```<code>outv = KeyedVectors()
outv.vocab = model.wv.vocab
outv.index2word = model.wv.index2word
outv.syn0 = model.syn1neg
inout_similars = outv.most_similar(positive=[model['cousin']])
</code>```

My question is, if it is possible to save output embeddings (from syn1 or syn1neg matrix) as final model. For example, when model.save(), so that it outputs output embeddings (or where exactly in the code of word2vec.py I could access and modify that). I need this in order to use these output embeddings as input to classifier. I have done it previously in brute-force approach, so I would like to access output embeddings easily.

答: Your object outv, as an instance of KeyedVectors, has its own save() method (inherited from the SaveLoad superclass defined in gensim/utils.py) and save_word2vec_format() method. Each would save them in a manner you could reload into Python code again later.

Body:
I have studied word2vec implementation in gensim, I am aware that input vectors are in syn0, output vectors are in syn1 and syn1neg if negative sampling.

I know I can access similarity between input and output embeddings like this:

outv = KeyedVectors()
outv.vocab = model.wv.vocab
outv.index2word = model.wv.index2word
outv.syn0 = model.syn1neg
inout_similars = outv.most_similar(positive=[model['cousin']])

My question is, if it is possible to save output embeddings (from syn1 or syn1neg matrix) as final model. For example, when model.save(), so that it outputs output embeddings (or where exactly in the code of word2vec.py I could access and modify that). I need this in order to use these output embeddings as input to classifier. I have done it previously in brute-force approach, so I would like to access output embeddings easily.


来源: stackexchange

问:
How to combine hash in PHP
I would like to ask if how to combine hash codes in PHP?

For example I have some checksums here (just sample checksums):

```<code>checksum1:b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1
checksum2:dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34
checksum3:4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345
</code>```

If I have these sample checksums of a file which will be split into 3 parts, I have to combine the first 2 checksums and then combine the last checksum after.

Edit: Combine means if I combine 2 checksums, it will generate new checksum.

I would like to achieve through the code what was stated in here:

Combine the first two hashes and take the binary hash of the result.

$ cat hash1 hash2 > hash12

$ openssl dgst -sha256 -binary hash12 > hash12hash

This is in the command line interface. The binary result was later on converted to hexadecimal.
How is it possible for PHP?

答:
I had already found the answer to my question. I used Tree hash class in the AWS SDK and add the checksums using the addChecksum function and pass the checksum of each splitted file so as to make the 2 checksums matched.
Thank you for the ideas.

ContentLicense: CC BY-SA 3.0

Title: How to combine hash in PHP

Body:
I would like to ask if how to combine hash codes in PHP?

For example I have some checksums here (just sample checksums):

checksum1:b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1
checksum2:dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34
checksum3:4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345

If I have these sample checksums of a file which will be split into 3 parts, I have to combine the first 2 checksums and then combine the last checksum after.

Edit: Combine means if I combine 2 checksums, it will generate new checksum.

I would like to achieve through the code what was stated in here:

Combine the first two hashes and take the binary hash of the result.

$ cat hash1 hash2 > hash12

$ openssl dgst -sha256 -binary hash12 > hash12hash

This is in the command line interface. The binary result was later on converted to hexadecimal.
How is it possible for PHP?


问:
Fast way for character matching in R
I'm trying to find whether vector of characters maps to another another, and looking for a fast way of doing it in R.

Specifically, my character alphabet is amino acids:

```<code>aa.LETTERS <- c('G','P','A','V','L','I','M','C','F','Y','W','H','K','R','Q','N','E','D','S','T')
</code>```

I have a vector of peptide and protein sequences:

```<code>set.seed(1)
peptides.vec <- sapply(1:100,function(p) paste(aa.LETTERS[sample(20,ceiling(runif(1,8,12)),replace=T)],collapse=""))
proteins.vec <- sapply(1:1000,function(p) paste(aa.LETTERS[sample(20,ceiling(runif(1,200,400)),replace=T)],collapse=""))
</code>```

I want to try and see if for each peptide sequence in peptides.vec if it exists in any sequence in proteins.vec.

This is one of the obvious ways of doing it:

```<code>mapping.mat <- do.call(rbind,lapply(peptides.vec,function(p){
   grepl(p,proteins.vec)
}))
</code>```

Another one is using the Biostrings Bioconductor package:

```<code>require(Biostrings)
peptides.set <- AAStringSet(x=peptides.vec)
proteins.set <- AAStringSet(x=proteins.vec)
mapping.mat <- vcountPDict(peptides.set,proteins.set)
</code>```

Both are slow for the dimensions I'm working with:

```<code>> microbenchmark(do.call(rbind,lapply(peptides.vec,function(p){
   grepl(p,proteins.vec)
 })),times=100)
Unit: milliseconds
                                                                             expr      min       lq     mean   median       uq      max neval
 do.call(rbind, lapply(peptides.vec, function(p) {     grepl(p, proteins.vec) })) 477.2509 478.8714 482.8937 480.4398 484.3076 509.8098   100
> microbenchmark(vcountPDict(peptides.set,proteins.set),times=100)
Unit: milliseconds
                                    expr    min       lq     mean   median       uq      max neval
 vcountPDict(peptides.set, proteins.set) 283.32 284.3334 285.0205 284.7867 285.2467 290.6725   100
</code>```

Any idea how to get this done faster?

答:
As mentioned in my comment, adding fixed = TRUE will lead to some performance improvement, and "stringi" is likely to give a good boost too.

Here are some tests:

```<code>N <- as.integer(length(proteins.vec))

funOP <- function() {
  do.call(rbind, lapply(peptides.vec, function(p) grepl(p, proteins.vec)))
}

funBASE_1 <- function() {
  # Just adds "fixed = TRUE"
  do.call(rbind, lapply(peptides.vec, function(p) grepl(p, proteins.vec, fixed = TRUE)))
}

funBASE_2 <- function() {
  # Does away with the `do.call` but probably won't improve performance
  vapply(peptides.vec, function(x) grepl(x, proteins.vec, fixed = TRUE), logical(N))
}

library(stringi)
funSTRINGI <- function() {
  # Should be considerably faster
  vapply(peptides.vec, function(x) stri_detect_fixed(proteins.vec, x), logical(N))
}

library(microbenchmark)
microbenchmark(funOP(), funBASE_1(), funBASE_2(), funSTRINGI())
# Unit: milliseconds
#          expr        min         lq      mean     median         uq       max neval
#       funOP() 344.500600 348.562879 352.94847 351.585206 356.508197 371.99683   100
#   funBASE_1() 128.724523 129.763464 132.55028 132.198112 135.277821 139.65782   100
#   funBASE_2() 128.564914 129.831660 132.33836 131.607216 134.380077 140.46987   100
#  funSTRINGI()   8.629728   8.825296   9.22318   9.038496   9.444376  11.28491   100
</code>```

Go "stringi"!

Title: Fast way for character matching in R

Body:
I'm trying to find whether vector of characters maps to another another, and looking for a fast way of doing it in R.

Specifically, my character alphabet is amino acids:

aa.LETTERS <- c('G','P','A','V','L','I','M','C','F','Y','W','H','K','R','Q','N','E','D','S','T')

I have a vector of peptide and protein sequences:

set.seed(1)
peptides.vec <- sapply(1:100,function(p) paste(aa.LETTERS[sample(20,ceiling(runif(1,8,12)),replace=T)],collapse=""))
proteins.vec <- sapply(1:1000,function(p) paste(aa.LETTERS[sample(20,ceiling(runif(1,200,400)),replace=T)],collapse=""))

I want to try and see if for each peptide sequence in peptides.vec if it exists in any sequence in proteins.vec.

This is one of the obvious ways of doing it:

mapping.mat <- do.call(rbind,lapply(peptides.vec,function(p){
   grepl(p,proteins.vec)
}))

Another one is using the Biostrings Bioconductor package:

require(Biostrings)
peptides.set <- AAStringSet(x=peptides.vec)
proteins.set <- AAStringSet(x=proteins.vec)
mapping.mat <- vcountPDict(peptides.set,proteins.set)

Both are slow for the dimensions I'm working with:

> microbenchmark(do.call(rbind,lapply(peptides.vec,function(p){
   grepl(p,proteins.vec)
 })),times=100)
Unit: milliseconds
                                                                             expr      min       lq     mean   median       uq      max neval
 do.call(rbind, lapply(peptides.vec, function(p) {     grepl(p, proteins.vec) })) 477.2509 478.8714 482.8937 480.4398 484.3076 509.8098   100
> microbenchmark(vcountPDict(peptides.set,proteins.set),times=100)
Unit: milliseconds
                                    expr    min       lq     mean   median       uq      max neval
 vcountPDict(peptides.set, proteins.set) 283.32 284.3334 285.0205 284.7867 285.2467 290.6725   100

Any idea how to get this done faster?

Body:
As mentioned in my comment, adding fixed = TRUE will lead to some performance improvement, and "stringi" is likely to give a good boost too.

Here are some tests:

N <- as.integer(length(proteins.vec))

funOP <- function() {
  do.call(rbind, lapply(peptides.vec, function(p) grepl(p, proteins.vec)))
}

funBASE_1 <- function() {
  # Just adds "fixed = TRUE"
  do.call(rbind, lapply(peptides.vec, function(p) grepl(p, proteins.vec, fixed = TRUE)))
}

funBASE_2 <- function() {
  # Does away with the `do.call` but probably won't improve performance
  vapply(peptides.vec, function(x) grepl(x, proteins.vec, fixed = TRUE), logical(N))
}

library(stringi)
funSTRINGI <- function() {
  # Should be considerably faster
  vapply(peptides.vec, function(x) stri_detect_fixed(proteins.vec, x), logical(N))
}

library(microbenchmark)
microbenchmark(funOP(), funBASE_1(), funBASE_2(), funSTRINGI())
# Unit: milliseconds
#          expr        min         lq      mean     median         uq       max neval
#       funOP() 344.500600 348.562879 352.94847 351.585206 356.508197 371.99683   100
#   funBASE_1() 128.724523 129.763464 132.55028 132.198112 135.277821 139.65782   100
#   funBASE_2() 128.564914 129.831660 132.33836 131.607216 134.380077 140.46987   100
#  funSTRINGI()   8.629728   8.825296   9.22318   9.038496   9.444376  11.28491   100

Go "stringi"!


问:
Open Source Objective-C Syntax Highlighter?
Can anyone point me in the direction of a project / framework / tutorial, preferably in Objective-C (or C/C++ I guess), that will demonstrate / handle syntax highlighting? I'd like it to work off of, and onto, the contents of a UITextView (iPhone / iPad), and I'd like it to support minimum, PHP, but preferably also Javascript / CSS / HTML, etc. I've had absolutely no luck googling, everything seems to be blog plugins, etc, for displaying colored content on your site in
 tags. I don't need it to do any syntax checking, just the coloring.

Thanks!

答: review the source code of TexShop (http://pages.uoregon.edu/koch/texshop/) or Smultron (http://smultron.sourceforge.net/)</p>

ContentLicense: CC BY-SA 2.5


问:
Resizing images in parallel causing out of memory exception
I'm resizing heaps of images to 1000x1000 thumbnails in parallel and running out of memory very quickly.  (Performance profiler puts me at 3GB of used memory after about 3 minutes)

Originally I was using Image.FromFile() but doing some research, I found that Image.FromStream() is the way to go.  I think I have the appropriate using statements, something somewhere is still keeping stuff in memory and the GC isn't clearing resources as expected.

It seems like there's an issue with GDI+ keeping the handles open, but I can't seem to find an appropriate solution for my case.

Questions:

Am I doing something completely wrong?

If not, is there a better way to Dispose() of the stream / image / ResizedImage so I'm not eating up all the resources, while still maintaining speedy parallel operations?

If GDI+ is the problem and is keeping unmanaged resources alive, how do I correct the issue?

Code

List<FileInfo> files contains ~300 valid JPG images, each JPG ~2-4mb

Caller

```<code>    public void Execute()
    {
        Parallel.ForEach(Files, (file) =>
        {
            Resize.ResizeImage(file.FullName);
        }
        );
    }
</code>```

Execute() calls a Parallel.Foreach()..

Resize Class

```<code>public static class Resize
{
    public static void ResizeImage(string fileName)
    {
        ResizeImage(fileName, 1000, 1000, true);
    }

    public static void ResizeImage(string fileName, int newHeight, int newWidth, bool keepAspectRatio = true)
    {
        string saveto = Path.GetDirectoryName(fileName) + @"\Alternate\" + Path.GetFileName(fileName);
        try
        {
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                using (Image ImageFromStream = Image.FromStream(fs))
                {
                    var ImageSize = new Size(newHeight, newWidth);
                    if (keepAspectRatio)
                    {
                        int oWidth = ImageFromStream.Width;
                        int oHeight = ImageFromStream.Height;
                        double pWidth = ((double)ImageSize.Width / (double)oWidth);
                        double pHeight = ((double)ImageSize.Height / (double)oWidth);
                        double percent;
                        if (pHeight < pWidth)
                            percent = pHeight;
                        else
                            percent = pWidth;
                        newWidth = (int)(oWidth * percent);
                        newHeight = (int)(oHeight * percent);
                    }
                    else
                    {
                        newWidth = ImageSize.Width;
                        newHeight = ImageSize.Height;
                    }
                    var ResizedImage = new Bitmap(newWidth, newHeight);
                    using (Graphics gfxHandle = Graphics.FromImage(ResizedImage))
                    {
                        gfxHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        gfxHandle.DrawImage(ImageFromStream, 0, 0, newWidth, newHeight);
                        if (!Directory.Exists(Path.GetDirectoryName(saveto))) { Directory.CreateDirectory(Path.GetDirectoryName(saveto)); }
                        ResizedImage.Save(saveto, ImageFormat.Jpeg);
                    }
                    ResizedImage.Dispose();
                    ResizedImage = null;
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(string.Format("Exception: {0}", ex.Message));
        }
    }
</code>```

答:
This explanation of parallelism points out that my Parallel.ForEach() was basically creating an overabundance of new tasks because it was waiting on disk access. At about the 5 minute mark, and about when the exception was thrown, there were ~160 threads. Reducing the degree of parallelism limits the amount of threads created, and the number of images waiting in memory to finish loading or writing to the disk before falling out of scope and being disposed of.  Setting MaxDegreeOfParallelism = 2 seemed to be the sweet spot for networked disk access and reduced my thread count to around 25, and increased CPU utilization to about 35% (Up from 17-24%, due to GC blocking threads, and CPU overhead from too many threads)

```<code>    public void Execute()
    {
        //Parallel.ForEach(Files, (file) =>
        //{
        //    Resize.ResizeImage(file.FullName);
        //}
        //);

        Parallel.ForEach(Files, new ParallelOptions() { MaxDegreeOfParallelism = 2 }, (file) => { Resize.ResizeImage(file.FullName); } );

    }
</code>```

Thanks @ZacFaragher.

Body:
I'm resizing heaps of images to 1000x1000 thumbnails in parallel and running out of memory very quickly.  (Performance profiler puts me at 3GB of used memory after about 3 minutes)

Originally I was using Image.FromFile() but doing some research, I found that Image.FromStream() is the way to go.  I think I have the appropriate using statements, something somewhere is still keeping stuff in memory and the GC isn't clearing resources as expected.

It seems like there's an issue with GDI+ keeping the handles open, but I can't seem to find an appropriate solution for my case.

Questions:

Am I doing something completely wrong?

If not, is there a better way to Dispose() of the stream / image / ResizedImage so I'm not eating up all the resources, while still maintaining speedy parallel operations?

If GDI+ is the problem and is keeping unmanaged resources alive, how do I correct the issue?

Code

List<FileInfo> files contains ~300 valid JPG images, each JPG ~2-4mb

Caller

    public void Execute()
    {
        Parallel.ForEach(Files, (file) =>
        {
            Resize.ResizeImage(file.FullName);
        }
        );
    }

Execute() calls a Parallel.Foreach()..

Resize Class

public static class Resize
{
    public static void ResizeImage(string fileName)
    {
        ResizeImage(fileName, 1000, 1000, true);
    }

    public static void ResizeImage(string fileName, int newHeight, int newWidth, bool keepAspectRatio = true)
    {
        string saveto = Path.GetDirectoryName(fileName) + @"\Alternate\" + Path.GetFileName(fileName);
        try
        {
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                using (Image ImageFromStream = Image.FromStream(fs))
                {
                    var ImageSize = new Size(newHeight, newWidth);
                    if (keepAspectRatio)
                    {
                        int oWidth = ImageFromStream.Width;
                        int oHeight = ImageFromStream.Height;
                        double pWidth = ((double)ImageSize.Width / (double)oWidth);
                        double pHeight = ((double)ImageSize.Height / (double)oWidth);
                        double percent;
                        if (pHeight < pWidth)
                            percent = pHeight;
                        else
                            percent = pWidth;
                        newWidth = (int)(oWidth * percent);
                        newHeight = (int)(oHeight * percent);
                    }
                    else
                    {
                        newWidth = ImageSize.Width;
                        newHeight = ImageSize.Height;
                    }
                    var ResizedImage = new Bitmap(newWidth, newHeight);
                    using (Graphics gfxHandle = Graphics.FromImage(ResizedImage))
                    {
                        gfxHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        gfxHandle.DrawImage(ImageFromStream, 0, 0, newWidth, newHeight);
                        if (!Directory.Exists(Path.GetDirectoryName(saveto))) { Directory.CreateDirectory(Path.GetDirectoryName(saveto)); }
                        ResizedImage.Save(saveto, ImageFormat.Jpeg);
                    }
                    ResizedImage.Dispose();
                    ResizedImage = null;
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(string.Format("Exception: {0}", ex.Message));
        }
    }

Body:
This explanation of parallelism points out that my Parallel.ForEach() was basically creating an overabundance of new tasks because it was waiting on disk access. At about the 5 minute mark, and about when the exception was thrown, there were ~160 threads. Reducing the degree of parallelism limits the amount of threads created, and the number of images waiting in memory to finish loading or writing to the disk before falling out of scope and being disposed of.  Setting MaxDegreeOfParallelism = 2 seemed to be the sweet spot for networked disk access and reduced my thread count to around 25, and increased CPU utilization to about 35% (Up from 17-24%, due to GC blocking threads, and CPU overhead from too many threads)

    public void Execute()
    {
        //Parallel.ForEach(Files, (file) =>
        //{
        //    Resize.ResizeImage(file.FullName);
        //}
        //);

        Parallel.ForEach(Files, new ParallelOptions() { MaxDegreeOfParallelism = 2 }, (file) => { Resize.ResizeImage(file.FullName); } );

    }

Thanks @ZacFaragher.


问:
Python OS - check if file exists, if so rename, check again, then save
I have a script that takes a file from a form, renames it and uploads it to a folder and inserts record into a database. I would like to add the functionality where before the file is saved, it checks the upload folder to determine if the filename exists. If it does exist, renames the file in a loop and then saves the file.

What I have currently:

```<code>file = request.files['xx']
extension = os.path.splitext(file.filename)[1]
xx = str(uuid.uuid4()) + extension
## if xx exists .. xx = str(uuid.uuid4()) + extension.. loop endlessly.
file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx)
</code>```

答:
```<code>if not os.path.isfile(xx):
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx)
else:
    print("File does not exist")
</code>```

Body:
I have a script that takes a file from a form, renames it and uploads it to a folder and inserts record into a database. I would like to add the functionality where before the file is saved, it checks the upload folder to determine if the filename exists. If it does exist, renames the file in a loop and then saves the file.

What I have currently:

file = request.files['xx']
extension = os.path.splitext(file.filename)[1]
xx = str(uuid.uuid4()) + extension
## if xx exists .. xx = str(uuid.uuid4()) + extension.. loop endlessly.
file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx)


问:
strange for loop? C#

Possible Duplicate:

  In C# is a for(;;) safe and what does it really do?

So i recently came across something ive never seen before..

```<code>        for (; ; )
        {

        }
</code>```

What is exactly happening when the feilds are left blank like that?

答: That's an infinite for loop.</p>

Title: strange for loop? C#

Body:
Possible Duplicate:

  In C# is a for(;;) safe and what does it really do?

So i recently came across something ive never seen before..

        for (; ; )
        {

        }

What is exactly happening when the feilds are left blank like that?

Body: That's an infinite for loop.


问:
Reading different Schema in Parquet Partitioned Dir structure
I have following partitioned parquet data on hdfs written using spark:

```<code>year
 |---Month
      |----monthlydata.parquet
      |----Day
            |---dailydata.parquet
</code>```

Now when I read df from year path, spark read dailydata.parquet. How can i read monthlydata from all partitions. I tried using setting option mergeSchema = true which gives error.

答:
I would urge you stop doing the following:

```<code>year
 |---Month
      |----monthlydata.parquet
      |----Day
            |---dailydata.parquet
</code>```

When you read from year/month/ or even just year/, you won't just get monthlydata.parquet, you'll also be getting dailydata.parquet. I can't speak much to the error you're getting (please post it), but my humble suggestion would be to separate the paths in HDFS since you're already duplicating the data:

```<code>dailies
 |---year
     |---Month
          |----Day
                |---dailydata.parquet
monthlies
 |---year
     |---Month
          |----monthlydata.parquet
</code>```

Is there a reason you were keeping them in the same directories?

However, if you insist on this structure, use something like this:

```<code>schema = "dailydata1"
val dfList = dates.map { case (month, day) =>
  Try(sqlContext.read.parquet(s"/hdfs/table/month=$month/day=$day/$schema.parquet"))
}
val dfUnion = dfList.collect { case Success(v) => v }.reduce { (a, b) =>
  a.unionAll(b)
}
</code>```

Where you can toggle the schema between dailydata1, dailydata2, etc.

Body:
I have following partitioned parquet data on hdfs written using spark:

year
 |---Month
      |----monthlydata.parquet
      |----Day
            |---dailydata.parquet

Now when I read df from year path, spark read dailydata.parquet. How can i read monthlydata from all partitions. I tried using setting option mergeSchema = true which gives error.

Body:
I would urge you stop doing the following:

year
 |---Month
      |----monthlydata.parquet
      |----Day
            |---dailydata.parquet

When you read from year/month/ or even just year/, you won't just get monthlydata.parquet, you'll also be getting dailydata.parquet. I can't speak much to the error you're getting (please post it), but my humble suggestion would be to separate the paths in HDFS since you're already duplicating the data:

dailies
 |---year
     |---Month
          |----Day
                |---dailydata.parquet
monthlies
 |---year
     |---Month
          |----monthlydata.parquet

Is there a reason you were keeping them in the same directories?

However, if you insist on this structure, use something like this:

schema = "dailydata1"
val dfList = dates.map { case (month, day) =>
  Try(sqlContext.read.parquet(s"/hdfs/table/month=$month/day=$day/$schema.parquet"))
}
val dfUnion = dfList.collect { case Success(v) => v }.reduce { (a, b) =>
  a.unionAll(b)
}

Where you can toggle the schema between dailydata1, dailydata2, etc.


问:
Jump directly to certain parts of a function
I would like a hint on how to complete this puzzle. I need to be able to print what is normally printed out in reverse. Normally this prints, hello there. I need it to print there hello. I am only allowed to add code where it is commented.

Here are some of my thoughts that don't work.

I thought about using the heap to store some data but I can't because stdlib.h is not included.

Can't use goto because I can't add labels and what I would goto is all in one line

Can't use recursion because there are no input parameters and no global variables to modify.

Can't possibly think of a way assembly could help but hey maybe?

I can't do anything obvious like just calling printf's and quitting the program early.

Thoughts on something to do with function pointers? I still don't see how they would help.

```<code>#include <stdio.h>
void f1(); void f2(); void f3();

int main() { f1(); printf("\n"); return 0; }

void f1() { f2(); printf(" there "); }

void f2() { f3(); printf(" hello "); }

void f3(){
    int x;
    //Can add whatever under here
}
</code>```

答:
I think the only purpose of int x; is to get the stack pointer without using inline assembly.

The solution on how to do this exactly will depend on your platform, the compiler you use and the optimization levels you have used.

I would say first you need to analyze the call stack.

You can do this -

```<code>int i;
for (i = 0; i< 10; i++) {
     printf ("%p\n", *(void**)((char*) &x - i * 8)); // I am assumming 64 bit machines. If 32 bit replace 8 with 4
}
</code>```

This will give you the top 10 8 byte values on the stack. Now you need to find the two that look like return addresses. One way to recognize them would be to print the function pointer value of f1 and f2 and see the values close to them.

You now know the indexes where they are stored. Just go ahead and swap them.

For swapping them, say the indices are 12 and 14.

Then you can do this -

```<code>*(void**)&x = *((void**)&x + 12);
*((void**)&x + 12) = *((void**)&x + 14);
*((void**)&x + 14) = *(void**)&x;
</code>```

Also make sure you don't change the stack layout once you get the indices. This means don't remove/add any variables. Don't apply the & operator to any new variables (or remove from any) and don't remove any function calls.

Also another suggestion - Instead of using int x, you could declare another unsigned long long y and use that for the swap instead. Because it would have enough bytes to hold a pointer (on 64 bit machines). Usually there will be padding in case of int x too which should save you from the problem but rather be safe.

Body:
I would like a hint on how to complete this puzzle. I need to be able to print what is normally printed out in reverse. Normally this prints, hello there. I need it to print there hello. I am only allowed to add code where it is commented.

Here are some of my thoughts that don't work.

I thought about using the heap to store some data but I can't because stdlib.h is not included.

Can't use goto because I can't add labels and what I would goto is all in one line

Can't use recursion because there are no input parameters and no global variables to modify.

Can't possibly think of a way assembly could help but hey maybe?

I can't do anything obvious like just calling printf's and quitting the program early.

Thoughts on something to do with function pointers? I still don't see how they would help.

#include <stdio.h>
void f1(); void f2(); void f3();

int main() { f1(); printf("\n"); return 0; }

void f1() { f2(); printf(" there "); }

void f2() { f3(); printf(" hello "); }

void f3(){
    int x;
    //Can add whatever under here
}

Body:
I think the only purpose of int x; is to get the stack pointer without using inline assembly.

The solution on how to do this exactly will depend on your platform, the compiler you use and the optimization levels you have used.

I would say first you need to analyze the call stack.

You can do this -

int i;
for (i = 0; i< 10; i++) {
     printf ("%p\n", *(void**)((char*) &x - i * 8)); // I am assumming 64 bit machines. If 32 bit replace 8 with 4
}

This will give you the top 10 8 byte values on the stack. Now you need to find the two that look like return addresses. One way to recognize them would be to print the function pointer value of f1 and f2 and see the values close to them.

You now know the indexes where they are stored. Just go ahead and swap them.

For swapping them, say the indices are 12 and 14.

Then you can do this -

*(void**)&x = *((void**)&x + 12);
*((void**)&x + 12) = *((void**)&x + 14);
*((void**)&x + 14) = *(void**)&x;

Also make sure you don't change the stack layout once you get the indices. This means don't remove/add any variables. Don't apply the & operator to any new variables (or remove from any) and don't remove any function calls.

Also another suggestion - Instead of using int x, you could declare another unsigned long long y and use that for the swap instead. Because it would have enough bytes to hold a pointer (on 64 bit machines). Usually there will be padding in case of int x too which should save you from the problem but rather be safe.


问:
Inventory CD segment mask and selector
We are trying to implement an "InventoryCD" (string) field in a custom page (not an Inventory ID Int field). We need this InventoryCD field to to work just like the Stock Item InventoryCD field (field mask for segment display and selector for existing items). Currently the issue is the same aspx PXSegmentMask and DAC attributes are not working the same. We are using InventoryRawAttribute on our field the exact same way found on the InventoryItemMaint cache attached for InventoryItem.InventoryCD. The only exception is the Inventory CD field is NOT a key in our custom page.

Our problem is the display of our Inventory CD field for the segment mask only displays when we are not entering or focused on the field (user has to click move to another field). This makes it difficult for users to follow which segments they are entering values into. So my question is what are we missing?

Here is what we have done so far:

(1) DAC - InventoryCD (same as InventoryItem.InventoryCD from InventoryItemMaint cache attached - except IsKey = false):

```<code>public abstract class inventoryCD : PX.Data.IBqlField
{}

protected String _InventoryCD;

[PXDefault()]
[InventoryRaw(typeof(Where<InventoryItem.stkItem, Equal<True>>), DisplayName = "Inventory ID", Filterable = true)]
public virtual String InventoryCD
{
    get
    {
        return this._InventoryCD;
    }
    set
    {
        this._InventoryCD = value;
    }
}
</code>```

(2) Page - InventoryCD (Copied from stock items IN202500):

```<code><px:PXSegmentMask ID="edInventoryCD" runat="server" DataField="InventoryCD"
    DataSourceID="ds" AutoRefresh="true" >
    <GridProperties FastFilterFields="InventoryCD,Descr" />
</px:PXSegmentMask>
</code>```

Here is a sample of the results I am seeing (refer to the image below). Note what the fields look like when entering values or just clicking into the field. On our custom page, clicking into the Inventory CD field shows no segmented separation. Doing the same on the Stock Item page will show the segmented separation so the user can following the segments. How do we get the segmented display to work in our custom page?

EDIT: If you set ValidComboRequired = true in InventoryRawAttribute the mask displays correctly the same as stock item, however you loose the selector for all items and the selector then becomes a selector for each item segment value (making the issue worse). Just an FYI in case anyone can see some type of combination I need as it might relate to ValidComboRequired (the mask when true, and the selector when false).

EDIT2: Tried making the field a key (but not the only key in the DAC) and no difference

答:
The reported behavior of PXSegmentMask is by design. If you play with Business Accounts a little and define at least 2 segments for the BIZACCT segmented key, on the Sales Orders screen there will also be no segmented separation in the Customer ID lookup until it loses focus:

With ValidComboRequired property set True on InventoryRawAttribute, you tell PXSegmentMask to work in "per-segment" mode, which disables the selector for all items and forces it to become a selector for each item segment value.

Inventory ID is a key field on the Stock Items screen as well as Customer ID is a key on the Customers screen, and therefore on both of this screens segment separation exists along with the selector for all items. The reason I referred to the Customer lookup on the Sales Orders screen is because CustomerID is not a key field for the SOOrder DAC, which is the main reason why segmented separation is missing in the Sales Order's Customer ID lookup until it loses focus.

Title: Inventory CD segment mask and selector

Body:
We are trying to implement an "InventoryCD" (string) field in a custom page (not an Inventory ID Int field). We need this InventoryCD field to to work just like the Stock Item InventoryCD field (field mask for segment display and selector for existing items). Currently the issue is the same aspx PXSegmentMask and DAC attributes are not working the same. We are using InventoryRawAttribute on our field the exact same way found on the InventoryItemMaint cache attached for InventoryItem.InventoryCD. The only exception is the Inventory CD field is NOT a key in our custom page.

Our problem is the display of our Inventory CD field for the segment mask only displays when we are not entering or focused on the field (user has to click move to another field). This makes it difficult for users to follow which segments they are entering values into. So my question is what are we missing?

Here is what we have done so far:

(1) DAC - InventoryCD (same as InventoryItem.InventoryCD from InventoryItemMaint cache attached - except IsKey = false):

public abstract class inventoryCD : PX.Data.IBqlField
{}

protected String _InventoryCD;

[PXDefault()]
[InventoryRaw(typeof(Where<InventoryItem.stkItem, Equal<True>>), DisplayName = "Inventory ID", Filterable = true)]
public virtual String InventoryCD
{
    get
    {
        return this._InventoryCD;
    }
    set
    {
        this._InventoryCD = value;
    }
}

(2) Page - InventoryCD (Copied from stock items IN202500):

<px:PXSegmentMask ID="edInventoryCD" runat="server" DataField="InventoryCD"
    DataSourceID="ds" AutoRefresh="true" >
    <GridProperties FastFilterFields="InventoryCD,Descr" />
</px:PXSegmentMask>

Here is a sample of the results I am seeing (refer to the image below). Note what the fields look like when entering values or just clicking into the field. On our custom page, clicking into the Inventory CD field shows no segmented separation. Doing the same on the Stock Item page will show the segmented separation so the user can following the segments. How do we get the segmented display to work in our custom page?

EDIT: If you set ValidComboRequired = true in InventoryRawAttribute the mask displays correctly the same as stock item, however you loose the selector for all items and the selector then becomes a selector for each item segment value (making the issue worse). Just an FYI in case anyone can see some type of combination I need as it might relate to ValidComboRequired (the mask when true, and the selector when false).

EDIT2: Tried making the field a key (but not the only key in the DAC) and no difference


问:
reject by app store because of App Store Review Guideline 2.5.2
Your app, extension, or linked framework appears to contain code designed explicitly with the capability to change your app’s behavior or functionality after App Review approval, which is not in compliance with App Store Review Guideline 2.5.2 and section 3.3.2 of the Apple Developer Program License Agreement.

i wonder AFNetworking framework is illegal？

答:
Is that the only thing they mentioned in the rejection? I've found that if my screenshots don't look great or if everything isn't put together "well", they start calling me out on a lot of other minor things.

Remember there is an appeal option. Don't be afraid to use it - I've done it and gotten it approved within a day of submitting an appeal.


问:
What are the best wiki engine with good authorization features?
What is the best wiki engine with good authorization features?</p>

答: They use MoinMoin in some subjects at my uni.  It has really good authorisation, controlled via simple ACLs at the top of each page.  Each student submits work on pages private to them and the subject staff, so it definitely seems to work...</p>

OwnerDisplayName: Jon


问:
All the ways you can switch from arm mode to thumb mode in the ARM architecture list them and explain in detail?
I could not find an answer to this question. Can you tell me when the ARM architecture switches from arm mode to thumb mode ? Explain all the ways in which the switching works.</p>

答:
The answers are in the ARM ARM (ARM Architectural Reference Manual).  Look at BX both in the ARM instructions and Thumb instructions, for example.  There are more instructions in case this is a homework question.

Also look at the pseudo code for what happens when an exception occurs:

```
R14_ = return link
SPSR_ = CPSR
CPSR[4:0] = exception mode number
CPSR[5] = 0
if  == Reset or FIQ then
    CPSR[6] = 1
CPSR[7] = 1
if  != UNDEF or SWI then
    CPSR[8] = 1
CPSR[9] = CP15_reg1_EEbit
PC = exception vector address
```

The comments for the pseudo code above (in the ARM ARM) describe another answer to your question.

Now what is not obvious, and possibly misleading in the BX and other instruction descriptions is bx rm does not always switch states.  The thumb BX description says "branches between ARM code and Thumb code".  As if thumb using it would take you to arm code all the time.  The pseudo code paints a slightly better picture though, the lsbit of the address in the register tells you if you are branching to thumb or arm code.  The PC pseudo code in the thumb description is misleading though.  Thumb instructions are 16 bits and the pc moves forward 16 bits at a time 0x00, 0x02, 0x04, etc.  In arm mode the instructions are 32 bits and the pc goes 0x00, 0x04, 0x08, etc.  (look at the branch instructions ARM the branch is signed_immed<<2, 0,4,8, etc. thumb branch is signed_immed<<1, 0,2,4,6, etc)

Basically if you have a mixed mode program you want to use BX instead of B, in particular when returning bx lr instead of mov pc,lr.  So both thumb and arm functions would use bx lr to return.  All four cases are covered, arm calling arm, arm calling thumb, thumb calling arm and thumb calling thumb.

So look for instructions that affect the T bit of the cpsr and/or affect the program counter in a way that causes the program counter to branch somewhere.  Also be careful to limit yourself to the specific family/core you are interested in (when reading the ARM ARM), armv4t, armv6, armv6, etc.  You probably want to get the TRM (Technical Reference Manual) for the specific core you are using as well.  The ARM ARM is very generic and as the number of cores increases over time the specific differences are not clear in the ARM ARM.  You need the TRM.

I have many revs of the ARM ARM and all of them contain bugs/errors.  Intentional or not I don't know, so some hacking is always required to find out how the core you are using really works.

Edit in 2018

I am not going to make a list for every core, etc, etc.  That is what the arm documentation is for.

But, again the answer lies in the architectural reference manuals available at ARM's website.  You may have to sacrifice an email address, but well worth it.

The key word you are looking for is interwork or interworking. The old/original arm arm is now called the armv5 architectural reference manual you look for a T Flag and see what instructions change that flag. For the armv7-m and maybe armv8-m ARM you can look for interworking support or interworking address. And it shows a list of instructions that affect the PC but do or do not support interworking.

For the armv7-a/r, I am still looking for interworking branch, so far I don't see a section. Look for changing between Thumb state and ARM state and there is a section that shows a list of instructions to get from thumb state to arm state and a list to get from arm state to thumb state.

ARMv6(not -M) is straddles the armv5 and armv7 ARMs, but each instruction/encoding shows the architecture that supports it, so you may have to walk through each of the interworking branch instructions and see if they have armv6 support (armv4 and armv5 are also shown).  The armv7 manuals are not the whole story though there is a blx thumb encoding in armv4T/armv5T that is not part of armv6-m/armv7-m what used to be that blx encoding is now part of the thumb2 extensions.

The primary instruction supported across all of this is BX, other instructions vary based on architecture as to whether or not you can use them to switch states.  If you are writing an emulator, good luck, if you are programming you can try to tune for architecture, but when it doubt just use bx.  Note there is an undocumented bug in the arm11-mpcore (not the older arm11s like the one in the Raspberry Pi) that does a prefetch on data after a pop pc or ldr pc if that data resembles a branch instruction.

My recommendation is not to use those instructions on an arm11 mpcore, but to instead do an armv4t style pop or load to a volatile register and bx with that. pop {r3}; bx r3 rather than pop {pc}.  The side effects are hard to see, a read cycle can happen against a peripheral that acts on a read, reading from the data register on a uart and losing a character for example.  Just FYI, took us a while to find and confirm this.

Body:
The answers are in the ARM ARM (ARM Architectural Reference Manual).  Look at BX both in the ARM instructions and Thumb instructions, for example.  There are more instructions in case this is a homework question.

Also look at the pseudo code for what happens when an exception occurs:

R14_ = return link
SPSR_ = CPSR
CPSR[4:0] = exception mode number
CPSR[5] = 0
if  == Reset or FIQ then
    CPSR[6] = 1
CPSR[7] = 1
if  != UNDEF or SWI then
    CPSR[8] = 1
CPSR[9] = CP15_reg1_EEbit
PC = exception vector address

The comments for the pseudo code above (in the ARM ARM) describe another answer to your question.

Now what is not obvious, and possibly misleading in the BX and other instruction descriptions is bx rm does not always switch states.  The thumb BX description says "branches between ARM code and Thumb code".  As if thumb using it would take you to arm code all the time.  The pseudo code paints a slightly better picture though, the lsbit of the address in the register tells you if you are branching to thumb or arm code.  The PC pseudo code in the thumb description is misleading though.  Thumb instructions are 16 bits and the pc moves forward 16 bits at a time 0x00, 0x02, 0x04, etc.  In arm mode the instructions are 32 bits and the pc goes 0x00, 0x04, 0x08, etc.  (look at the branch instructions ARM the branch is signed_immed<<2, 0,4,8, etc. thumb branch is signed_immed<<1, 0,2,4,6, etc)

Basically if you have a mixed mode program you want to use BX instead of B, in particular when returning bx lr instead of mov pc,lr.  So both thumb and arm functions would use bx lr to return.  All four cases are covered, arm calling arm, arm calling thumb, thumb calling arm and thumb calling thumb.

So look for instructions that affect the T bit of the cpsr and/or affect the program counter in a way that causes the program counter to branch somewhere.  Also be careful to limit yourself to the specific family/core you are interested in (when reading the ARM ARM), armv4t, armv6, armv6, etc.  You probably want to get the TRM (Technical Reference Manual) for the specific core you are using as well.  The ARM ARM is very generic and as the number of cores increases over time the specific differences are not clear in the ARM ARM.  You need the TRM.

I have many revs of the ARM ARM and all of them contain bugs/errors.  Intentional or not I don't know, so some hacking is always required to find out how the core you are using really works.

Edit in 2018

I am not going to make a list for every core, etc, etc.  That is what the arm documentation is for.

But, again the answer lies in the architectural reference manuals available at ARM's website.  You may have to sacrifice an email address, but well worth it.

The key word you are looking for is interwork or interworking. The old/original arm arm is now called the armv5 architectural reference manual you look for a T Flag and see what instructions change that flag. For the armv7-m and maybe armv8-m ARM you can look for interworking support or interworking address. And it shows a list of instructions that affect the PC but do or do not support interworking.

For the armv7-a/r, I am still looking for interworking branch, so far I don't see a section. Look for changing between Thumb state and ARM state and there is a section that shows a list of instructions to get from thumb state to arm state and a list to get from arm state to thumb state.

ARMv6(not -M) is straddles the armv5 and armv7 ARMs, but each instruction/encoding shows the architecture that supports it, so you may have to walk through each of the interworking branch instructions and see if they have armv6 support (armv4 and armv5 are also shown).  The armv7 manuals are not the whole story though there is a blx thumb encoding in armv4T/armv5T that is not part of armv6-m/armv7-m what used to be that blx encoding is now part of the thumb2 extensions.

The primary instruction supported across all of this is BX, other instructions vary based on architecture as to whether or not you can use them to switch states.  If you are writing an emulator, good luck, if you are programming you can try to tune for architecture, but when it doubt just use bx.  Note there is an undocumented bug in the arm11-mpcore (not the older arm11s like the one in the Raspberry Pi) that does a prefetch on data after a pop pc or ldr pc if that data resembles a branch instruction.

My recommendation is not to use those instructions on an arm11 mpcore, but to instead do an armv4t style pop or load to a volatile register and bx with that. pop {r3}; bx r3 rather than pop {pc}.  The side effects are hard to see, a read cycle can happen against a peripheral that acts on a read, reading from the data register on a uart and losing a character for example.  Just FYI, took us a while to find and confirm this.

ContentLicense: CC BY-SA 4.0


问:
Better subsetting and counting values in a dataframe
I have a data frame with two columns and 70,000 rows.  One column serves an identifier for a household, column b in the example below.  The other column refers to the individuals in the household, numbering them from 1 to n with some error (could be 1,2,3 or 1,4,5), column a in the example below.

I'm trying to use hierarchical clustering with the number of individuals in a household as a feature.  The code I've written below counts the number of individuals in a household and puts them in the proper column and row, however takes several minutes with the actual data set I have, I assume due to its size.  Is there a better way of going about getting this information?

```<code>fake.data <- data.frame(a = c(1,1,5,6,7,1,2,3,1,2,4), b = c("a", "a", "a", "a", "a", "b", "b", "b", "c", "c", "c"))
fake.cluster <- data.frame(b = unique(fake.data$b))
fake.cluster$members <- sapply(fake.cluster$b, function(x)     length(unique(subset(fake.data, fake.data$b == x)$a)))
</code>```

答:
Here is an option using data.table

```<code>library(data.table)
setDT(fake.data)[, .(members = uniqueN(a)), b]
#   b members
#1: a       4
#2: b       3
#3: c       3
</code>```

Body:
I have a data frame with two columns and 70,000 rows.  One column serves an identifier for a household, column b in the example below.  The other column refers to the individuals in the household, numbering them from 1 to n with some error (could be 1,2,3 or 1,4,5), column a in the example below.

I'm trying to use hierarchical clustering with the number of individuals in a household as a feature.  The code I've written below counts the number of individuals in a household and puts them in the proper column and row, however takes several minutes with the actual data set I have, I assume due to its size.  Is there a better way of going about getting this information?

fake.data <- data.frame(a = c(1,1,5,6,7,1,2,3,1,2,4), b = c("a", "a", "a", "a", "a", "b", "b", "b", "c", "c", "c"))
fake.cluster <- data.frame(b = unique(fake.data$b))
fake.cluster$members <- sapply(fake.cluster$b, function(x)     length(unique(subset(fake.data, fake.data$b == x)$a)))

Body:
Here is an option using data.table

library(data.table)
setDT(fake.data)[, .(members = uniqueN(a)), b]
#   b members
#1: a       4
#2: b       3
#3: c       3


问:
electron - process.env.npm_package* variables missing
I am building an electron application using electron-boilerplate.

I have some variables that I am keeping in package.json under config.  Normally with node, you would be able to access them like process.env.npm_package_config_variableName.  However in my electron app I don't see any of the package.json var bindings in the main process.

Has anyone experienced the same issue?

答:
Experiencing a similar issue using the dotenv module.

Interestingly, when I run 'electron .' the process.env variables work as expected with require('dotenv').config();

They are only not configured properly when I package my app using electron-packager and open the the app as <appName>-darwin-x64.


问:
How do I dynamically access a property inside an angularjs directive?
I have a directive when given an array it creates check boxes for that list of items using the Name as the label for the checkbox.

Html

```<code><div>
<a style="float:right; margin-bottom: 5px;" ng-click="selectNone()" href="#">Select None</a>
<a style="float:right; margin-bottom: 5px;margin-left: 10px" ng-click="selectAll()" href="#">Select All</a>

<div class="cleared"></div>

<div class="form-input form-list">
    <label ng-repeat="item in valuelist | orderBy:'Name'">
        <input type="checkbox" checklist-model="model" checklist-value="item" /> {{item.Name}}<br />
    </label>
</div>
</code>```

JS

```<code>    'use strict';

growllApp.directive('checkboxlist', [function () {
    return {
        restrict: 'E',
        templateUrl: 'scripts/modules/checkboxlist.template.html',
        controller: 'checkboxlistController',
        scope: {
            model: "=",
            value: "=",
            valuelist: "="
        }
    }
}]);

growllApp.controller('checkboxlistController', ['$scope', '$routeParams', '$location', '$cookieStore', function ($scope, $routeParams, $location, $cookieStore) {
    $scope.selectAll = function () {
        $scope.model = angular.copy($scope.valuelist);
    };

    $scope.selectNone = function () {
        $scope.model = [];
    };
}]);
</code>```

Using the directive

```<code><checkboxlist ng-show="applyToProducts" model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>
</code>```

All this works fine in most scenarios.  However, I have a scenario where the array I'm passing in has objects in it that do not have the property "Name" but instead have the property "Title".

How do I use the attribute I have in the directive called "value" for the part that determines the label.

So in the directive html instead of saying {{item.Name}} how can I specify {{item.Title}} by passing in that the property name is title in certain cases?

答:
In addition to the answer suggesting a ternary operator you could simplify that to be something like

```<code>{{ item.Name || item.Title }}
</code>```

and you could have as many alternatives as you need.

However, a more robust approach I think would be to do like someone else suggested and say

```<code>scope : {
    ...
    key:'@'
    ...
}
</code>```

where key is the name of the property and the access it like

```<code>{{ item[key] }}
</code>```

Body:
I have a directive when given an array it creates check boxes for that list of items using the Name as the label for the checkbox.

Html

Select None
Select All

        <input type="checkbox" checklist-model="model" checklist-value="item" /> {{item.Name}}

JS

    'use strict';

growllApp.directive('checkboxlist', [function () {
    return {
        restrict: 'E',
        templateUrl: 'scripts/modules/checkboxlist.template.html',
        controller: 'checkboxlistController',
        scope: {
            model: "=",
            value: "=",
            valuelist: "="
        }
    }
}]);

growllApp.controller('checkboxlistController', ['$scope', '$routeParams', '$location', '$cookieStore', function ($scope, $routeParams, $location, $cookieStore) {
    $scope.selectAll = function () {
        $scope.model = angular.copy($scope.valuelist);
    };

    $scope.selectNone = function () {
        $scope.model = [];
    };
}]);

Using the directive

<checkboxlist ng-show="applyToProducts" model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>

All this works fine in most scenarios.  However, I have a scenario where the array I'm passing in has objects in it that do not have the property "Name" but instead have the property "Title".

How do I use the attribute I have in the directive called "value" for the part that determines the label.

So in the directive html instead of saying {{item.Name}} how can I specify {{item.Title}} by passing in that the property name is title in certain cases?

Body:
In addition to the answer suggesting a ternary operator you could simplify that to be something like

{{ item.Name || item.Title }}

and you could have as many alternatives as you need.

However, a more robust approach I think would be to do like someone else suggested and say

scope : {
    ...
    key:'@'
    ...
}

where key is the name of the property and the access it like

{{ item[key] }}


答:
quick and dirty, haven't tested this. using the check and rename function recursively to add "_1", "_2" etc to the end of the file name until it can be saved.</p>

```<code>def check_and_rename(file, add=0):
    original_file = file
    if add != 0:
        split = file.split(".")
        part_1 = split[0] + "_" + str(add)
        file = ".".join([part1, split[1]])
    if not os.path.isfile(file):
        # save here
    else:
        check_and_rename(original_file, add+=1)
</code>```

Title: Python OS - check if file exists, if so rename, check again, then save

Body:
quick and dirty, haven't tested this. using the check and rename function recursively to add "_1", "_2" etc to the end of the file name until it can be saved.

def check_and_rename(file, add=0):
    original_file = file
    if add != 0:
        split = file.split(".")
        part_1 = split[0] + "_" + str(add)
        file = ".".join([part1, split[1]])
    if not os.path.isfile(file):
        # save here
    else:
        check_and_rename(original_file, add+=1)


问:
Questions of 'Designing for Performance' document at Android Developer site
In the Avoid Creating Objects section of the page Designing for Performance in the Android Developer documentation I read some paragraphs for which I am not able to visualize a code representation:

An array of ints is a much better than an array of Integers, but this also generalizes to the fact that two parallel arrays of ints are also a lot more efficient than an array of (int,int) objects. The same goes for any combination of primitive types.

How would these 'parallel arrays of ints' look like? Would it be something like instead of having a method with a signature such as getData():int[][] returning
```
   [a][b]
   [c][d]
   [e][f]
```

... it would be better to have two methods, each returning one of the 'columns' of data? as in:
getFirstDimensionData():int[]
```
   [a]
   [c]
   [e]
```
and a second one getSecondDimensionData():int[]
```
   [b]
   [d]
   [f]
```

What is an 'array of (int,int) objects? ... something like an array of objects of a-type-not-yet-defined that has two int member instances defining its state?

The immediate next paragraph:

If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[] and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects.

... makes me think that the author is making up some sort of notation. I guess my key question is: is the author of the page using this (somethingX, somethingY) notation to refer to an arbitrary class that 'wraps' the elements inside the parentheses?

Finally, is this a standard notation or just something the author of the page created by himself and omitted to explain?

Can anyone, please, shed some light? :)

Thanks in advance,

Y

答:
The author of that document is using a sort of loose mathematical notation. (x, y, z) is the way tuples are represented in mathematics. (It also happens to be the case that Python uses this notation, and given that this document came out of Google there is a reasonably high chance that the authors are fluent in Python. Python didn't invent the notation, however.)

The approach EboMike mentions is probably equally efficient, but it's not exactly what that doc is talking about. The doc is talking about parallel arrays, which is an approach where you use n arrays in place of a single array of records/structs/tuples/objects that have n fields.

More concretely, it's saying that if you want "a container that stores tuples of (Foo,Bar) objects", like this:

```<code>class FooBar {
  Foo foo;
  Bar bar;
}
...
FooBar[] array = new FooBar[n];
</code>```

you could instead use "two parallel Foo[] and Bar[] arrays", like this:

```<code>  Foo[] foos = new Foo[n];
  Bar[] bars = new Foo[n];
</code>```

This means that wherever you would have said array[x].foo you'd now say foos[x].

With parallel arrays the garbage collector only has to deal with 2 + 2 * n objects (2 arrays, n Foos and n Bars) rather than 1 + 3 * n objects (1 array, n FooBars, n Foos and n Bars). So the bigger n is, the more significant the difference.

The downside is that you can't easily pass around the Foo and Bar together and it potentially makes the intent of your code less clear.

Body:
In the Avoid Creating Objects section of the page Designing for Performance in the Android Developer documentation I read some paragraphs for which I am not able to visualize a code representation:

An array of ints is a much better than an array of Integers, but this also generalizes to the fact that two parallel arrays of ints are also a lot more efficient than an array of (int,int) objects. The same goes for any combination of primitive types.

How would these 'parallel arrays of ints' look like? Would it be something like instead of having a method with a signature such as getData():int[][] returning

   [a][b]
   [c][d]
   [e][f]

... it would be better to have two methods, each returning one of the 'columns' of data? as in:
getFirstDimensionData():int[]

   [a]
   [c]
   [e]

and a second one getSecondDimensionData():int[]

   [b]
   [d]
   [f]

What is an 'array of (int,int) objects? ... something like an array of objects of a-type-not-yet-defined that has two int member instances defining its state?

The immediate next paragraph:

If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[] and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects.

... makes me think that the author is making up some sort of notation. I guess my key question is: is the author of the page using this (somethingX, somethingY) notation to refer to an arbitrary class that 'wraps' the elements inside the parentheses?

Finally, is this a standard notation or just something the author of the page created by himself and omitted to explain?

Can anyone, please, shed some light? :)

Thanks in advance,

Y

Body:
The author of that document is using a sort of loose mathematical notation. (x, y, z) is the way tuples are represented in mathematics. (It also happens to be the case that Python uses this notation, and given that this document came out of Google there is a reasonably high chance that the authors are fluent in Python. Python didn't invent the notation, however.)

The approach EboMike mentions is probably equally efficient, but it's not exactly what that doc is talking about. The doc is talking about parallel arrays, which is an approach where you use n arrays in place of a single array of records/structs/tuples/objects that have n fields.

More concretely, it's saying that if you want "a container that stores tuples of (Foo,Bar) objects", like this:

class FooBar {
  Foo foo;
  Bar bar;
}
...
FooBar[] array = new FooBar[n];

you could instead use "two parallel Foo[] and Bar[] arrays", like this:

  Foo[] foos = new Foo[n];
  Bar[] bars = new Foo[n];

This means that wherever you would have said array[x].foo you'd now say foos[x].

With parallel arrays the garbage collector only has to deal with 2 + 2 * n objects (2 arrays, n Foos and n Bars) rather than 1 + 3 * n objects (1 array, n FooBars, n Foos and n Bars). So the bigger n is, the more significant the difference.

The downside is that you can't easily pass around the Foo and Bar together and it potentially makes the intent of your code less clear.


问:
How to get specific currency symbol(rupee symbol in my case) in angular js instead of the default one (dollar $ symbol)
When i use 'currency' in angular js, I am getting a dollar symbol. How to get required currency symbols based on the requirements. As if now i need to know how to display a rupee symbol using currency. It will be of great use if anyone could explain how to make use of this currency for different symbols at the times of different requirements.

sample :

```<code>Item Price<span style="font-weight:bold;">{{item.price | currency}}</span>
</code>```

If my item.price is 200. Here it shows 200$. I need to display rupee symbol instead of dollar.

Body:
When i use 'currency' in angular js, I am getting a dollar symbol. How to get required currency symbols based on the requirements. As if now i need to know how to display a rupee symbol using currency. It will be of great use if anyone could explain how to make use of this currency for different symbols at the times of different requirements.

sample :

Item Price{{item.price | currency}}

If my item.price is 200. Here it shows 200$. I need to display rupee symbol instead of dollar.

Body: <h2>{{8.99 | currency:'INR':true}}</h2>


问:
Javascript - create text file on website
So I have a web page, and I would like to programaticly create a text file (lets say it has the words 'hello, I am a text file' in it) on a new directory on my website. The program will be in another directory on the website.

e.g.
https://www.example.com/txtbuild.html is trying to programaticly make https://www.example.com/texts/hi.txt

Is there a way to do this with HTML/Javascript?

EDIT:
I am on Github

答: You can't do it with HTML/Javascript alone, you need a functional language on the backend (nodejs, php, python)</p>


问:
Execute Java main method from within a Java desktop app in a different JVM
I have a desktop app and when someone presses a button I want it to kick off another JVM that executes a class' main method.  My desktop app already depends on the jar that contains the class with the main method that I want to execute.

Currently I've got the following code, however, I was hoping their was a more elegant way of doing this:

```<code>Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("java -jar another.jar");
</code>```

I know I can use ProcessBuilder too.

Is there no way such as (excuse the pseudo code):

```<code>Jvm.execute(Main.class);
</code>```

Since the Main class that I want to call already exists in my classpath, it just feels weird to have to run the java command via Runtime.

答:
Very good question. Try to search into management API: http://cupi2.uniandes.edu.co/javadoc/j2se/1.5.0/docs/api/javax/management/package-frame.html

Good luck.

I am not sure that this API exists, but if it is it should be there.
I'd personally used ProcessBuilder as you but specify explicit path to java by retrieving system properties of current process.

Body:
I have a desktop app and when someone presses a button I want it to kick off another JVM that executes a class' main method.  My desktop app already depends on the jar that contains the class with the main method that I want to execute.

Currently I've got the following code, however, I was hoping their was a more elegant way of doing this:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("java -jar another.jar");

I know I can use ProcessBuilder too.

Is there no way such as (excuse the pseudo code):

Jvm.execute(Main.class);

Since the Main class that I want to call already exists in my classpath, it just feels weird to have to run the java command via Runtime.


问:
kendojs template data-bind click event not working
Well, I am using KendoJS grid and I have this code here in my .js file:

```<code>var viewModel = kendo.observable({

    people: new kendo.data.DataSource(...),

    isActive:true,
    friends: new kendo.data.DataSource(...),
    selectionChanged: function(){...
    }
});

$(document).ready(function () {
    kendo.bind($("#sampleGridContainer"), viewModel);
});
</code>```

In my .html file, I have a kendo grid:

```<code><div id="sampleGridContainer">
    <div data-role="grid"
         data-columns="[...]"
         data-editable="{ 'mode': 'popup', 'template': kendo.template($('#sampleTemplate').html()) }"
         data-bind="source: people"></div>
</div>

<script id="sampleTemplate" type="text/x-kendo-template">
    <form id="sampleForm">
       ...

       <div data-container-for="somedropdown" class="k-edit-field">
            <input name="somedropdown" id="somedropdown"
                 data-role="dropdownlist"
                 data-type="text"
                 data-text-field="name"
                 data-value-field="value"
                 data-bind="value: someValue, visible: isActive, source: friends, click: selectionChanged" />
       </div>

       ...
    </form>
</script>
</code>```

Now, in my dropdown input element, someValue, isActive and friends variables are properly working - infact the drop down list shows up fine. But the problem is click event selectionChanged is not called. If I remove this from template, the event starts working, but my question is when all the other variables on the same scope are accessible in template, why does event selectionChanged not get called?

Any help is highly appreciated.

答:
I have also encountered this problem, my workaround for this is that I initialize my kendoDropDownList on the edit event of grid.

```<code>edit: function (e){
   e.container.find("input[name='somedropdown']").kendoDropDownList({
      dataTextField: "name",
      dataValueField: "value",
      data-bind="value: viewModel.someValue, visible: viewModel.isActive, source: viewModel.friends, click: viewModel.selectionChanged"
   });
}
</code>```

Then the html would look something like this:

```<code><div data-role="grid"
   data-columns="[...]"
   data-editable="{ 'mode': 'popup', 'template': kendo.template($('#sampleTemplate').html()) }"
   data-bind="source: people, events: { edit: onEdit }">
</div>

<script id="sampleTemplate" type="text/x-kendo-template">
    <form id="sampleForm">
       <div data-container-for="somedropdown" class="k-edit-field">
            <input name="somedropdown"/>
       </div>
    </form>
</script>
</code>```

Hope this works for you.

Body:
Well, I am using KendoJS grid and I have this code here in my .js file:

var viewModel = kendo.observable({

    people: new kendo.data.DataSource(...),

    isActive:true,
    friends: new kendo.data.DataSource(...),
    selectionChanged: function(){...
    }
});

$(document).ready(function () {
    kendo.bind($("#sampleGridContainer"), viewModel);
});

In my .html file, I have a kendo grid:

Now, in my dropdown input element, someValue, isActive and friends variables are properly working - infact the drop down list shows up fine. But the problem is click event selectionChanged is not called. If I remove this from template, the event starts working, but my question is when all the other variables on the same scope are accessible in template, why does event selectionChanged not get called?

Any help is highly appreciated.

Body:
I have also encountered this problem, my workaround for this is that I initialize my kendoDropDownList on the edit event of grid.

edit: function (e){
   e.container.find("input[name='somedropdown']").kendoDropDownList({
      dataTextField: "name",
      dataValueField: "value",
      data-bind="value: viewModel.someValue, visible: viewModel.isActive, source: viewModel.friends, click: viewModel.selectionChanged"
   });
}

Then the html would look something like this:

<div data-role="grid"
   data-columns="[...]"
   data-editable="{ 'mode': 'popup', 'template': kendo.template($('#sampleTemplate').html()) }"
   data-bind="source: people, events: { edit: onEdit }">
</div>

<script id="sampleTemplate" type="text/x-kendo-template">
    <form id="sampleForm">
       <div data-container-for="somedropdown" class="k-edit-field">
            <input name="somedropdown"/>
       </div>
    </form>
</script>

Hope this works for you.


问:
Converting .ui to .py with Python 3.6 on PyQt5
I can't convert ui to py

it's giving this:

答:
you are using the correct syntax: pyuic5 -x file.ui -o file.py

but you have to make sure that the file.ui is in the same location of your pyuic5.bat


问:
inserting jtextbox value and jradiobutton value to database
I am trying to insert values from textboxes into the database but getting error com.microsoft.sqlserver.jdbc.SQLServerException: String or binary data would be truncated. I thought the problem was with radio button but when I tried to insert value in the database removing radio button and gender from the query, I am getting the same error.

I tried inserting values Name: a, Username:a ,Contact:a , radio button [male], still getting the same error.
I can not find out how I am getting this error.

```<code>create table temp (
  id int IDENTITY(1,1) PRIMARY KEY,
  name varchar(32) not null,
  username varchar(32) not null,
  contact varchar(32) not null,
  gender int
);

btnSubmit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try
                {
                    int gender = 0;
                    Connection sqlCon = DB_con.getSQLConnection();
                    PreparedStatement ps = sqlCon.prepareStatement(
                            "insert into temp (name, username, contact, gender) values ( ?, ?, ?, ?)"
                            );
                    ps.setString(1, txtName.toString());
                    ps.setString(2, txtUserName.toString());
                    ps.setString(3, txtContact.toString());

                    gender = (rbtnMale.isSelected()) ? 1 :2;
                    System.out.println("value of gender " + gender );
                    ps.setInt(4, gender);
                    int i = ps.executeUpdate();
                    System.out.println("records inserted: "+i);
                    sqlCon.close();
                }
                catch(Exception e)
                {
                    System.out.println(e.toString());
                }
            }
        });
</code>```

答:
It's likely that one of these:

txtName.toString()

txtUserName.toString()

txtContact.toString()

...is longer then 32 characters. Why not log them somewhere before you do the insert so you can see?

It's not clear what class these objects are from your code snippet. Is it possible that they're the default toString() method implementation of JTextField? If so, use getText(), not toString().

Body:
I am trying to insert values from textboxes into the database but getting error com.microsoft.sqlserver.jdbc.SQLServerException: String or binary data would be truncated. I thought the problem was with radio button but when I tried to insert value in the database removing radio button and gender from the query, I am getting the same error.

I tried inserting values Name: a, Username:a ,Contact:a , radio button [male], still getting the same error.
I can not find out how I am getting this error.

create table temp (
  id int IDENTITY(1,1) PRIMARY KEY,
  name varchar(32) not null,
  username varchar(32) not null,
  contact varchar(32) not null,
  gender int
);

btnSubmit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try
                {
                    int gender = 0;
                    Connection sqlCon = DB_con.getSQLConnection();
                    PreparedStatement ps = sqlCon.prepareStatement(
                            "insert into temp (name, username, contact, gender) values ( ?, ?, ?, ?)"
                            );
                    ps.setString(1, txtName.toString());
                    ps.setString(2, txtUserName.toString());
                    ps.setString(3, txtContact.toString());

                    gender = (rbtnMale.isSelected()) ? 1 :2;
                    System.out.println("value of gender " + gender );
                    ps.setInt(4, gender);
                    int i = ps.executeUpdate();
                    System.out.println("records inserted: "+i);
                    sqlCon.close();
                }
                catch(Exception e)
                {
                    System.out.println(e.toString());
                }
            }
        });


问:
Why does Vim Automatically Change Comma Delimited CSV to Pipes?
I open a comma separated CSV file with text wrangler and textedit and it shows comma , separated values.

However, opening with MacVim gives me a pipe | delimited file.

How can I disable this behavior?

答:
Add this snippet to your .vimrc file

let g:csv_delim = ','

It overrides any plugins changing the delimiter on a csv file.


问:
How can I make this python function run O(log n) time instead of O(n) time?
```<code>def findMax(f,c):
    n=1
    while f(n) <= c:
        n += 1
   return n
</code>```

This is a higher-order python function that given function f and a maximal count,
c returns the largest n such that f(n) ≤ c. This works but not when n gets too large for e.g f(10**6). How can I make this algorithm run O(log n) time so it can facilitate f(10**6) using the function below?

```<code>def f(n):
    return math.log(n, 2)
</code>```

答:
Change n += 1 to n *= 2 for logarithmic outcome.

Logarithmic sequences increment in multiples of 2, and are non-linear, thus logarithmic sequences don't increment by 1.

Body:
def findMax(f,c):
    n=1
    while f(n) <= c:
        n += 1
   return n

This is a higher-order python function that given function f and a maximal count,
c returns the largest n such that f(n) ≤ c. This works but not when n gets too large for e.g f(10**6). How can I make this algorithm run O(log n) time so it can facilitate f(10**6) using the function below?

def f(n):
    return math.log(n, 2)


问:
Will android/bitmap.h increase performance in image processing
I am making an image processing APP in Android. Originally, I use Java to do the pixel computing, it is extremely slow. Then I change to C++ native code, it's much faster, but not enough.

I just pass the pixels integer array to C++, and do the computing. Recently, I noticed the android/bitmap.h library, but I am not sure whether it will increase performance. It seems like the difference is just passing an integer array or a bitmap. If I still need to do the same computations, how could it be faster?

答:
I should preface that I have never written code using the NDK or the Bitmap library, but I did take a look at the documentation for it.

The Bitmap.h documentation looks like it's only used for meta information about the Java Bitmap object. It only provides a single struct that tells you basic information about the bitmap (width, height, etc), its format, and other similar data. The library also only contains functions for performing locks on the data or getting the aforementioned information.

Therefore, I would conclude that using the Bitmap library in the NDK is only useful if you are writing Java and C++ code in parallel and you use Bitmap objects in the Java code, in which case you might want to use the library to interact with them easily. There will be no performance gains, and it might not even make sense, to use the bitmap library otherwise.

Take a look here for an example on the usage of the Bitmap library: https://github.com/googlesamples/android-ndk/tree/master/bitmap-plasma.
Notice how the Bitmaps are created in the Java code and then only processed in the C++ code.


问:
Proxy servers with Scrapy-Splash
I am trying to get proxy servers to work on my local splash instance. I have read several documents, but have not found any workable examples. It was brought to my attention that this https://github.com/scrapy-plugins/scrapy-splash/issues/107 was the cause. I am no longer getting that traceback, but still can't use Splash with proxies. New error message below. Thanks in advance if anybody can help me solve this. None of my requests are even making it through to Splash. </p>

```<code>  def parse_json(self, response):
    json_data = response.body
    load = json.loads(json_data.decode('utf-8'))
    dump = json.dumps(load,sort_keys=True,indent=2)
    LUA_SOURCE = """
    function main(splash)
        local host = "proxy.crawlera.com"
        local port = 8010
        local user = "APIKEY"
        local password = ""
        local session_header = "X-Crawlera-Session"
        local session_id = "create"

        splash:on_request(function (request)
            request:set_header("X-Crawlera-UA", "desktop")
            request:set_header(session_header, session_id)
            request:set_proxy{host, port, username=user, password=password}
        end)

        splash:on_response_headers(function (response)
            if response.headers[session_header] ~= nil then
                session_id = response.headers[session_header]
            end
        end)

        splash:go(splash.args.url)
        return splash:html()
    end
    """
    for link in load['d']['blogtopics']:
        link = link['Uri']
        yield SplashRequest(link, self.parse_blog, endpoint='execute',  args={'wait': 3, 'lua_source': LUA_SOURCE})

2017-03-29 09:26:37 [scrapy.core.engine] DEBUG: Crawled (503) <GET http://community.martindale.com/legal-blogs/Practice_Areas/b/corporate__securities_law/archive/2011/08/11/sec-adopts-new-rules-replacing-credit-ratings-as-a-criterion-for-the-use-of-short-form-shelf-registration.aspx via http://localhost:8050/execute> (referer: None)
</code>```

答: Problem appears to be caused by Crawlera middleware. There is no handling for SplashRequest. It tries to go through proxy to my local host.</p>

Title: Proxy servers with Scrapy-Splash

Body:
I am trying to get proxy servers to work on my local splash instance. I have read several documents, but have not found any workable examples. It was brought to my attention that this https://github.com/scrapy-plugins/scrapy-splash/issues/107 was the cause. I am no longer getting that traceback, but still can't use Splash with proxies. New error message below. Thanks in advance if anybody can help me solve this. None of my requests are even making it through to Splash.

  def parse_json(self, response):
    json_data = response.body
    load = json.loads(json_data.decode('utf-8'))
    dump = json.dumps(load,sort_keys=True,indent=2)
    LUA_SOURCE = """
    function main(splash)
        local host = "proxy.crawlera.com"
        local port = 8010
        local user = "APIKEY"
        local password = ""
        local session_header = "X-Crawlera-Session"
        local session_id = "create"

        splash:on_request(function (request)
            request:set_header("X-Crawlera-UA", "desktop")
            request:set_header(session_header, session_id)
            request:set_proxy{host, port, username=user, password=password}
        end)

        splash:on_response_headers(function (response)
            if response.headers[session_header] ~= nil then
                session_id = response.headers[session_header]
            end
        end)

        splash:go(splash.args.url)
        return splash:html()
    end
    """
    for link in load['d']['blogtopics']:
        link = link['Uri']
        yield SplashRequest(link, self.parse_blog, endpoint='execute',  args={'wait': 3, 'lua_source': LUA_SOURCE})

2017-03-29 09:26:37 [scrapy.core.engine] DEBUG: Crawled (503) <GET http://community.martindale.com/legal-blogs/Practice_Areas/b/corporate__securities_law/archive/2011/08/11/sec-adopts-new-rules-replacing-credit-ratings-as-a-criterion-for-the-use-of-short-form-shelf-registration.aspx via http://localhost:8050/execute> (referer: None)


答:
Change

```<code>ps.setString(1, txtName.toString());
ps.setString(2, txtUserName.toString());
ps.setString(3, txtContact.toString());
</code>```

to

```<code>ps.setString(1, txtName.getText());
ps.setString(2, txtUserName.getText());
ps.setString(3, txtContact.getText());
</code>```

toString is doing a debug dump of the controls, which definitely longer than 32 characters and doesn't represent the text typed into the field (or at least not in a format you want ;))

Title: inserting jtextbox value and jradiobutton value to database

Body:
Change

ps.setString(1, txtName.toString());
ps.setString(2, txtUserName.toString());
ps.setString(3, txtContact.toString());

to

ps.setString(1, txtName.getText());
ps.setString(2, txtUserName.getText());
ps.setString(3, txtContact.getText());

toString is doing a debug dump of the controls, which definitely longer than 32 characters and doesn't represent the text typed into the field (or at least not in a format you want ;))


问:
Reading and maintaining a stack of input streams
So I'm trying to create a loop that reads lines through a file and do stuff based on the line, except that some lines can be another file name which I need to open and start reading from that file, while keeping the original file on a stack, this can happen multiple times and when a new file is EOF, I need to pop back the previous file from the stack.

```<code>    std::ifstream* currentStream = fileStream;
    // this is within a class where I pass through fileStream in its initialization
    stack<std::ifstream*> fileStack = stack<std::ifstream*>();

    while(!fileStack.empty() || !currentStream->eof()){
      while (!currentStream->eof()) {
        getline(*currentStream, lineBuf);
        string line = trim(lineBuf);
        if (line = blahblah) {
          //do stuff
        }
        else if (words[0] == "file") {
          auto params = extractParameters(line);
          std::ifstream simpFileStream;
          simpFileStream.open(params[1][0].substr(1, params[1][0].length()-2) + ".simp");
          currentStream->swap(simpFileStream);
          fileStack.push(&simpFileStream);
        }
        if(!fileStack.empty() && currentStream->eof()){
          // what to do here?
          fileStack.pop();
        }
      }
    }
</code>```

In my code I've tried a couple ways, but this is what I have last saved, I basically create a new ifstream and swap the current one and attempt to push the old one on the stack, I'm not sure if that's even working properly.

In my if statement, I've tried a few things, but nothing seems to work so that's where I am having trouble. Basically when I test my code, opening a new stream works and it starts reading into the new files, but I'm not entirely sure how to pop back into the old ifstream.

答:
It seems to me from your comments that ou may be looking for a structure something a bit like this:</p>

```<code>void method(std::string const& filename)
{
    // use smart pointers to avoid memory leaks
    std::stack<std::unique_ptr<std::ifstream>> files;

    // open initial file and push it to the top of the stack
    // to use as the 'current' file
    files.push(std::make_unique<std::ifstream>(filename));

    // use the top() of the stack as your 'current' file stream

    // as long as we have open files, keep going
    while(!files.empty())
    {
        // read the line in the loop control block
        for(std::string line; std::getline(*files.top(), line);)
        {
            if(line == "some stuff")
            {
                // start a new file on the top of the stack
                files.push(std::make_unique<std::ifstream>("new file name"));
            }
            else if(line == "some other stuff")
            {
                // do other stuff
            }
            // yet more stuff
        }

        // end of file reached here - pop
        // delete the current file stream off the top
        // of the stack (automatically closing the file)
        files.pop();
        // Now the top of the stack contains the previous current file stream
    }
}
</code>```

Body:
So I'm trying to create a loop that reads lines through a file and do stuff based on the line, except that some lines can be another file name which I need to open and start reading from that file, while keeping the original file on a stack, this can happen multiple times and when a new file is EOF, I need to pop back the previous file from the stack.

    std::ifstream* currentStream = fileStream;
    // this is within a class where I pass through fileStream in its initialization
    stack<std::ifstream*> fileStack = stack<std::ifstream*>();

    while(!fileStack.empty() || !currentStream->eof()){
      while (!currentStream->eof()) {
        getline(*currentStream, lineBuf);
        string line = trim(lineBuf);
        if (line = blahblah) {
          //do stuff
        }
        else if (words[0] == "file") {
          auto params = extractParameters(line);
          std::ifstream simpFileStream;
          simpFileStream.open(params[1][0].substr(1, params[1][0].length()-2) + ".simp");
          currentStream->swap(simpFileStream);
          fileStack.push(&simpFileStream);
        }
        if(!fileStack.empty() && currentStream->eof()){
          // what to do here?
          fileStack.pop();
        }
      }
    }

In my code I've tried a couple ways, but this is what I have last saved, I basically create a new ifstream and swap the current one and attempt to push the old one on the stack, I'm not sure if that's even working properly.

In my if statement, I've tried a few things, but nothing seems to work so that's where I am having trouble. Basically when I test my code, opening a new stream works and it starts reading into the new files, but I'm not entirely sure how to pop back into the old ifstream.

Body:
It seems to me from your comments that ou may be looking for a structure something a bit like this:

void method(std::string const& filename)
{
    // use smart pointers to avoid memory leaks
    std::stack<std::unique_ptr<std::ifstream>> files;

    // open initial file and push it to the top of the stack
    // to use as the 'current' file
    files.push(std::make_unique<std::ifstream>(filename));

    // use the top() of the stack as your 'current' file stream

    // as long as we have open files, keep going
    while(!files.empty())
    {
        // read the line in the loop control block
        for(std::string line; std::getline(*files.top(), line);)
        {
            if(line == "some stuff")
            {
                // start a new file on the top of the stack
                files.push(std::make_unique<std::ifstream>("new file name"));
            }
            else if(line == "some other stuff")
            {
                // do other stuff
            }
            // yet more stuff
        }

        // end of file reached here - pop
        // delete the current file stream off the top
        // of the stack (automatically closing the file)
        files.pop();
        // Now the top of the stack contains the previous current file stream
    }
}


问:
SQL Server & C# : not returning any results
```<code>private void searchMulti(string searchType, string searchTerm)
    {
        {
            {
                var query = "";
                cb_Surname.Items.Clear();
                txt_patient_search.Clear();
                if (patient_NHSID.Equals(null) != true)
                {
                    pbar_search.Value = 2;
                    var connectionString = Settings.Default.CMTA_DBConnectionString;
                    using (var con = new SqlConnection(connectionString))
                    {
                        if (searchType != "NHSID")
                        {
                            query = @"SELECT * FROM Patient WHERE @p2 = '@p1' ";
                        }
                        else
                        {
                            query = @"SELECT * FROM Patient WHERE @p2 = @p1";
                        }

                        using (var qry_search = new SqlCommand(query))
                        {
                            qry_search.Connection = con;
                            qry_search.Parameters.Add("@p1", SqlDbType.VarChar).Value = searchTerm;
                            qry_search.Parameters.Add("@p2", SqlDbType.VarChar).Value = searchType;

                            con.Open();
                            qry_search.ExecuteNonQuery();
                            int firstIteration = 0;

                            using (var rdr = qry_search.ExecuteReader())
                            {
                                if (rdr.HasRows)
                                {
                                    //Found Valid Patient Event
                                    pbar_search.Value = 6;
                                    pbox_tick.Show();
                                    foundValidPatient = true;
                                    ////////////////////////////

                                    while (rdr.Read())
                                    {
                                        if (firstIteration == 0)
                                        {
                                            pbar_search.Value = 8;
                                            cb_Surname.Text = rdr.GetInt64(0) + " - " + rdr.GetString(1) + " - " +
                                                              rdr.GetString(2);
                                            firstIteration = 1;
                                        }
                                        cb_Surname.Items.Add(rdr.GetInt64(0) + " - " + rdr.GetString(1) + " - " +
                                                             rdr.GetString(2));
                                    }
                                }
                                else
                                {
                                    //Patient Not Found
                                    pbox_cross.Show();
                                    patientSelected = false;
                                    foundValidPatient = false;
                                }
                                con.Close();
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Please Enter Valid Text");
                    pbar_search.Value = 0;
                    pbox_cross.Show();
                }
            }
        }
    }
</code>```

The method above isn't working. It should query the SQL Server database for a user entered term (such as textbox value) and query it for a searchtype (firstname) however when debugging the SQL query is executed but no rows are returned.

If I run the command without the parameters and insert actual values i.e (WHERE FirstName = 'Alan') it works perfectly.

What have I done incorrectly with this SQL query?

```<code>query = @"SELECT * FROM Patient WHERE @p2 = '@p1' ";
</code>```

Many thanks!

答:
Wrong: query = @"SELECT * FROM Patient WHERE @p2 = '@p1' ";

(Answer) Right: query = @"SELECT * FROM Patient WHERE " + searchType +" = @p1";

Answered by :  – Tetsuya Yamamoto

Body:
private void searchMulti(string searchType, string searchTerm)
    {
        {
            {
                var query = "";
                cb_Surname.Items.Clear();
                txt_patient_search.Clear();
                if (patient_NHSID.Equals(null) != true)
                {
                    pbar_search.Value = 2;
                    var connectionString = Settings.Default.CMTA_DBConnectionString;
                    using (var con = new SqlConnection(connectionString))
                    {
                        if (searchType != "NHSID")
                        {
                            query = @"SELECT * FROM Patient WHERE @p2 = '@p1' ";
                        }
                        else
                        {
                            query = @"SELECT * FROM Patient WHERE @p2 = @p1";
                        }

                        using (var qry_search = new SqlCommand(query))
                        {
                            qry_search.Connection = con;
                            qry_search.Parameters.Add("@p1", SqlDbType.VarChar).Value = searchTerm;
                            qry_search.Parameters.Add("@p2", SqlDbType.VarChar).Value = searchType;

                            con.Open();
                            qry_search.ExecuteNonQuery();
                            int firstIteration = 0;

                            using (var rdr = qry_search.ExecuteReader())
                            {
                                if (rdr.HasRows)
                                {
                                    //Found Valid Patient Event
                                    pbar_search.Value = 6;
                                    pbox_tick.Show();
                                    foundValidPatient = true;
                                    ////////////////////////////

                                    while (rdr.Read())
                                    {
                                        if (firstIteration == 0)
                                        {
                                            pbar_search.Value = 8;
                                            cb_Surname.Text = rdr.GetInt64(0) + " - " + rdr.GetString(1) + " - " +
                                                              rdr.GetString(2);
                                            firstIteration = 1;
                                        }
                                        cb_Surname.Items.Add(rdr.GetInt64(0) + " - " + rdr.GetString(1) + " - " +
                                                             rdr.GetString(2));
                                    }
                                }
                                else
                                {
                                    //Patient Not Found
                                    pbox_cross.Show();
                                    patientSelected = false;
                                    foundValidPatient = false;
                                }
                                con.Close();
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Please Enter Valid Text");
                    pbar_search.Value = 0;
                    pbox_cross.Show();
                }
            }
        }
    }

The method above isn't working. It should query the SQL Server database for a user entered term (such as textbox value) and query it for a searchtype (firstname) however when debugging the SQL query is executed but no rows are returned.

If I run the command without the parameters and insert actual values i.e (WHERE FirstName = 'Alan') it works perfectly.

What have I done incorrectly with this SQL query?

query = @"SELECT * FROM Patient WHERE @p2 = '@p1' ";

Many thanks!