答:
You might maintain factor and set size in an additional (outer) loop:

```<code>// you will need more than you calculated previously!
float twiddle_real[TWIDDLE_LIMIT * 3];
float twiddle_imag[TWIDDLE_LIMIT * 3];

// pointer arithmetic...
float* real = twiddle_real;
float* imag = twiddle_imag;

double factor = 1.0;
for(int size = TWIDDLE_LIMIT; size > 1; size /= 4)
{
    for(int j = 0; j < 64; ++j)
    {
        *real++ = (float)  cos((j % size) * factor * 2.0 * PI / N);
        *imag++ = (float) -sin((j % size) * factor * 2.0 * PI / N);
    }
    factor *= 4.0;
}
</code>```

You do not need all those casts by the way - since factor is a double, (j % size) is converted to implicitly, as well as N afterwards.

Recommendation: As re and img belong together, I would represent them as such:

```<code>struct Complex
{
    double re;
    double im;
};
</code>```

You could then have an array of these:

```<code>struct Complex twiddle[TW_size]; // no need for malloc, by the way...
</code>```

You might have noticed: I changed to double, too. There is no reason to use float (with more limited precision) unless you have limited memory available (micro controllers)...

Alternative (why re-inventing the wheel?): use complex.h.

Title: Create a twiddle table with a specific order?

Body:
I was hoping to create a twiddle table with a specific ordering for a specific purpose, here is the initial code:

#define TWIDDLE_LIMIT 64
#define PI 3.1415927

float *twiddle_real;
float *twiddle_imag;

void main()
{
  int N = 256;
  int TW_size = TWIDDLE_LIMIT + (TWIDDLE_LIMIT>>2);

  twiddle_real  = malloc(TW_size * sizeof(float));
  twiddle_imag  = malloc(TW_size * sizeof(float));

  int i;
  for(i=0; i<TWIDDLE_LIMIT; i++)
  {
    twiddle_real[i] = (float)   cos((float)i * 2.0 * PI / (float)N);
    twiddle_imag[i] = (float) - sin((float)i * 2.0 * PI / (float)N);
  }
  for(int a=0; a<TWIDDLE_LIMIT; a++)
    printf("RE = %f \t IM = %f \n",twiddle_real[a],twiddle_imag[a]);
}

And i get this kind of result:

RE = 1.000000    IM = -0.000000 //64 lines
RE = 0.999699    IM = -0.024541
RE = 0.998795    IM = -0.049068
RE = 0.997290    IM = -0.073565
RE = 0.995185    IM = -0.098017
RE = 0.992480    IM = -0.122411
RE = 0.989177    IM = -0.146730
RE = 0.985278    IM = -0.170962
RE = 0.980785    IM = -0.195090
RE = 0.975702    IM = -0.219101
RE = 0.970031    IM = -0.242980
RE = 0.963776    IM = -0.266713
RE = 0.956940    IM = -0.290285
RE = 0.949528    IM = -0.313682
RE = 0.941544    IM = -0.336890
RE = 0.932993    IM = -0.359895
RE = 0.923880    IM = -0.382683
RE = 0.914210    IM = -0.405241
RE = 0.903989    IM = -0.427555
RE = 0.893224    IM = -0.449611
RE = 0.881921    IM = -0.471397
RE = 0.870087    IM = -0.492898
RE = 0.857729    IM = -0.514103
RE = 0.844854    IM = -0.534998
RE = 0.831470    IM = -0.555570
RE = 0.817585    IM = -0.575808
RE = 0.803208    IM = -0.595699
RE = 0.788346    IM = -0.615232
RE = 0.773010    IM = -0.634393
RE = 0.757209    IM = -0.653173
RE = 0.740951    IM = -0.671559
RE = 0.724247    IM = -0.689541
RE = 0.707107    IM = -0.707107
RE = 0.689541    IM = -0.724247
RE = 0.671559    IM = -0.740951
RE = 0.653173    IM = -0.757209
RE = 0.634393    IM = -0.773010
RE = 0.615232    IM = -0.788346
RE = 0.595699    IM = -0.803208
RE = 0.575808    IM = -0.817585
RE = 0.555570    IM = -0.831470
RE = 0.534998    IM = -0.844854
RE = 0.514103    IM = -0.857729
RE = 0.492898    IM = -0.870087
RE = 0.471397    IM = -0.881921
RE = 0.449611    IM = -0.893224
RE = 0.427555    IM = -0.903989
RE = 0.405241    IM = -0.914210
RE = 0.382683    IM = -0.923880
RE = 0.359895    IM = -0.932993
RE = 0.336890    IM = -0.941544
RE = 0.313682    IM = -0.949528
RE = 0.290285    IM = -0.956940
RE = 0.266713    IM = -0.963776
RE = 0.242980    IM = -0.970031
RE = 0.219101    IM = -0.975702
RE = 0.195090    IM = -0.980785
RE = 0.170962    IM = -0.985278
RE = 0.146730    IM = -0.989177
RE = 0.122411    IM = -0.992480
RE = 0.098017    IM = -0.995185
RE = 0.073565    IM = -0.997290
RE = 0.049068    IM = -0.998795
RE = 0.024541    IM = -0.999699

And this is only a minimal exaple that I can explain you as much as possibble.

What i want and tried to create is a table that begins with the earlier set of lines and the resdt will be as following:

(earlier set of lines) expressed as following(idx:0 --- > 64)

    re[idx] = (float) cos((float)i * (2*pi)/(float)N);
    im[idx] = (float)-sin((float)i * (2*pi)/(float)N);

(2nd set of lines) expressed as following repeated 4 times consequently

    re[idx] = (float) cos(4 * (float)i * (2*pi)/(float)N);
    im[idx] = (float)-sin(4 * (float)i * (2*pi)/(float)N);

(3nd set of lines) expressed as following repeated 16 times consequently

    re[idx] = (float) cos(16 * (float)i * (2*pi)/(float)N);
    im[idx] = (float)-sin(16 * (float)i * (2*pi)/(float)N);

The result is expected to be as following:

//set 1 as above  repeated just 1 time
// ....
//set 2 repeated 4 times
RE = 1.000000    IM = -0.000000 //1st ligne of set 1
RE = 0.995185    IM = -0.098017 //4th ligne of set 1
RE = 0.980785    IM = -0.195090 //8th ligne of set 1
RE = 0.956940    IM = -0.290285 //12th ligne of set 1 ...
RE = 0.923880    IM = -0.382683
RE = 0.881921    IM = -0.471397
RE = 0.831470    IM = -0.555570
RE = 0.773010    IM = -0.634393
RE = 0.707107    IM = -0.707107
RE = 0.634393    IM = -0.773010
RE = 0.555570    IM = -0.831470
RE = 0.471397    IM = -0.881921
RE = 0.382683    IM = -0.923880
RE = 0.290285    IM = -0.956940
RE = 0.195090    IM = -0.980785
RE = 0.098017    IM = -0.995185
// set 3 repeated 16 times
RE = 1.000000    IM = -0.000000 //1st ligne of set 1
RE = 0.923880    IM = -0.382683 //16th ligne of set 1
RE = 0.707107    IM = -0.707107 //38th ligne of set 1
RE = 0.382683    IM = -0.923880 //64th ligne of set 1

I've tried several times but i keep getting wrong results I don't know if it's precison issue or sometimng else.

Body:
You might maintain factor and set size in an additional (outer) loop:

// you will need more than you calculated previously!
float twiddle_real[TWIDDLE_LIMIT * 3];
float twiddle_imag[TWIDDLE_LIMIT * 3];

// pointer arithmetic...
float* real = twiddle_real;
float* imag = twiddle_imag;

double factor = 1.0;
for(int size = TWIDDLE_LIMIT; size > 1; size /= 4)
{
    for(int j = 0; j < 64; ++j)
    {
        *real++ = (float)  cos((j % size) * factor * 2.0 * PI / N);
        *imag++ = (float) -sin((j % size) * factor * 2.0 * PI / N);
    }
    factor *= 4.0;
}

You do not need all those casts by the way - since factor is a double, (j % size) is converted to implicitly, as well as N afterwards.

Recommendation: As re and img belong together, I would represent them as such:

struct Complex
{
    double re;
    double im;
};

You could then have an array of these:

struct Complex twiddle[TW_size]; // no need for malloc, by the way...

You might have noticed: I changed to double, too. There is no reason to use float (with more limited precision) unless you have limited memory available (micro controllers)...

Alternative (why re-inventing the wheel?): use complex.h.


来源: stackexchange

问:
How can I rearrange an array in MATLAB by a specific rule?
Suppose that I have this array:

```<code>a = [1,2,3,4,5];
</code>```

The output should be something like this:

```<code>1,2,3,4,5
2,1,3,4,5
3,1,2,4,5
4,1,2,3,5
5,1,2,3,4
</code>```

how Can I do this? This function should be valid for different lengths of a.

ContentLicense: CC BY-SA 3.0

Body:
Suppose that I have this array:

a = [1,2,3,4,5];

The output should be something like this:

1,2,3,4,5
2,1,3,4,5
3,1,2,4,5
4,1,2,3,5
5,1,2,3,4

how Can I do this? This function should be valid for different lengths of a.

Body:
Another way:

a = [10 20 30 40 50];
ind = 1:numel(a);
result = a(abs(sort(bsxfun(@times, ind, 1-2*eye(numel(ind))),2)));

gives

result =
    10    20    30    40    50
    20    10    30    40    50
    30    10    20    40    50
    40    10    20    30    50
    50    10    20    30    40


问:
Make a Download Button act like an Add To Cart Button
How can I link a simple download button act like a cart button ? If I have to make a user download a 2$ song, instead of directly downloading it, it should add that song to the woo commerce cart page.  </p>

答:
Add this to your theme's functions.php to change "Add to Cart" to "Download"

```<code>add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_single_add_to_cart_text' );
add_filter( 'woocommerce_product_add_to_cart_text', 'woo_custom_product_add_to_cart_text' );

function woo_custom_single_add_to_cart_text() {
    return __( 'Download', 'woocommerce' );
}
</code>```

EDIT:
If you want a custom Add To Cart or Download button, add the following link to that button

```<code>http://your-domain.com/?add_to_cart=5
</code>```

Where your-domain is your site domain and 5 is your product/audio ID.

Body:
Add this to your theme's functions.php to change "Add to Cart" to "Download"

add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_single_add_to_cart_text' );
add_filter( 'woocommerce_product_add_to_cart_text', 'woo_custom_product_add_to_cart_text' );

function woo_custom_single_add_to_cart_text() {
    return __( 'Download', 'woocommerce' );
}

EDIT:
If you want a custom Add To Cart or Download button, add the following link to that button

http://your-domain.com/?add_to_cart=5

Where your-domain is your site domain and 5 is your product/audio ID.


问:
Is it bad practice to return from within a try catch finally block?
So I came across some code this morning that looked like this:

```<code>try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}
</code>```

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

答: The finally will be executed no matter what, so it doesn't matter.</p>

OwnerDisplayName: lomaxx

Body:
So I came across some code this morning that looked like this:

try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

OwnerDisplayName: Ed Swangren


问:
How to get indirect groups of an AD user? - C#
I'm using DirectorySearcher to get the groups of an AD user in which he is a member of using the 'memberof' property. But according to this msdn page the 'memberof' property only returns the direct groups in which the user is a member. How can I get the indirect groups of the user too.

For ex.

```<code>Group A -> User X, User Y, Group B
Group B -> User Z
Group C -> User Z
</code>```

I want to get the result as Group A, Group B, Group C for the user Z since he is an indirect user of Group A.

Update

Okie. I've followed this codeproject article to get the groups recursively. But still the builtin group 'Domain Users' is missing from the list. So does that mean Built in groups wont appear in the directory searcher?

答: Sounds to me like a simple recursive approach. Find the groups, the user is member of and for each group, find the groups, the group is member of. Repeat until no more memberships are found.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm using DirectorySearcher to get the groups of an AD user in which he is a member of using the 'memberof' property. But according to this msdn page the 'memberof' property only returns the direct groups in which the user is a member. How can I get the indirect groups of the user too.

For ex.

Group A -> User X, User Y, Group B
Group B -> User Z
Group C -> User Z

I want to get the result as Group A, Group B, Group C for the user Z since he is an indirect user of Group A.

Update

Okie. I've followed this codeproject article to get the groups recursively. But still the builtin group 'Domain Users' is missing from the list. So does that mean Built in groups wont appear in the directory searcher?


问:
How to check if a file is being actively managed by chef
I have a few files in /etc/apt/sources.list.d that I wish to clean up if they are not managed by chef (or no longer, i.e. were added by a recipe that is no longer in the node's run_list).

I would like to have some way to go over all the files in this directory at the end of each chef run, and delete those that didn't have a resource maintaining them (such as apt_repository or template), even if it was (skipped due to action :nothing) or (up to date)

答: Delete all the files and then let chef run. It will recreate everything that it "manages".</p>


问:
Using lapply with more than one item that differs between function calls
I have a frequency cross-tabulation dataset, so columns A01-A04 in the example are counts of CAGs e.g. A01 has 6485 counts of 13 CAGs, 35 counts of 14 CAGs. Each column is a sample. The mode of each sample is the CAG value for which the count is the highest (e.g. 13 for A01).

With the help of stack overflow I've written a function with lapply ('prop') that sums the values in each column above and below the mode, and works out the proportion that are greater than the mode.

However, each sample has a control, as defined in 'settings' e.g. the control for A02 is A01. I would now like to adapt 'prop' so that for each sample it uses its control mode, rather than the sample's own mode. For this it will need to look up which sample it should use in 'settings', then look up the control sample's mode in 'sample mode', then use that value in 'prop'. Unfortunately I believe only one item can vary in each iteration of lapply. I'd be very grateful for help in adapting.

```<code>#Data set
data <- data.frame(CAG = c(13, 14, 15, 17),
               A01 = c(6485,35,132, 12),
               A02 = c(0,42,56, 4),
               A03 = c(33,5014,2221, 18),
               A04 = c(106,89,436, 11))

#Define controls for each sample
settings <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                   control = c('A01', 'A01', 'A03', 'A03'))

#Mode
samplemode <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                     samplemode = (data[sapply(data[2:ncol(data)], which.max), ]$CAG))

#Proportion of values > mode ##I NEED TO ADAPT THIS FUNCTION TO CALCULATE     'ctrlprop' USING THE CONTROL MODE OF EACH SAMPLE RATHER THAN 'mod'##
prop <- lapply(data[, 2:ncol(data)], function(x) {
  mod <- data$CAG[which.max(x)] #Calculate mode for each column
  B <- sum(x[data$CAG >= mod]) #Sum heights > mode
  A <- sum(x[data$CAG <= mod]) #Sum heights < mode
  B/(A+B)
})

prop <- as.data.frame(prop) #Convert output from list to data frame
prop <- t(prop) #Transpose so samples in rows and result in columnrm
results <- prop

#Expected results
expected <- data.frame(samples = settings$samples,
                   prop = c(0.5068066, 0.3797468, 0.5896748, 0.4146568),
                   ctrlprop = c(0.5068066, 1.0000000, 0.58967480, 0.73324213))
</code>```

答:
I think you need to check mapply. It allows us to pass multiple vectors as parameters to a function provided the length of vectors are same. Your function could be modified like this:

```<code>prop <- mapply(FUN = function(x,mod) {
    B <- sum(x[data$CAG >= mod]) #Sum heights > mode
    A <- sum(x[data$CAG <= mod]) #Sum heights < mode
    B/(A+B)
},data[, 2:ncol(data)], setting$control)
</code>```

A simple example how 'mapply' works:

```<code>d=data.frame(a=c(1,2,3),b=c(4,5,6))
#>d
#  a b
#1 1 4
#2 2 5
#3 3 6

mapply(function(x,y){x+y},d$a,d$b)
#[1] 5 7 9
</code>```

Body:
I have a frequency cross-tabulation dataset, so columns A01-A04 in the example are counts of CAGs e.g. A01 has 6485 counts of 13 CAGs, 35 counts of 14 CAGs. Each column is a sample. The mode of each sample is the CAG value for which the count is the highest (e.g. 13 for A01).

With the help of stack overflow I've written a function with lapply ('prop') that sums the values in each column above and below the mode, and works out the proportion that are greater than the mode.

However, each sample has a control, as defined in 'settings' e.g. the control for A02 is A01. I would now like to adapt 'prop' so that for each sample it uses its control mode, rather than the sample's own mode. For this it will need to look up which sample it should use in 'settings', then look up the control sample's mode in 'sample mode', then use that value in 'prop'. Unfortunately I believe only one item can vary in each iteration of lapply. I'd be very grateful for help in adapting.

#Data set
data <- data.frame(CAG = c(13, 14, 15, 17),
               A01 = c(6485,35,132, 12),
               A02 = c(0,42,56, 4),
               A03 = c(33,5014,2221, 18),
               A04 = c(106,89,436, 11))

#Define controls for each sample
settings <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                   control = c('A01', 'A01', 'A03', 'A03'))

#Mode
samplemode <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                     samplemode = (data[sapply(data[2:ncol(data)], which.max), ]$CAG))

#Proportion of values > mode ##I NEED TO ADAPT THIS FUNCTION TO CALCULATE     'ctrlprop' USING THE CONTROL MODE OF EACH SAMPLE RATHER THAN 'mod'##
prop <- lapply(data[, 2:ncol(data)], function(x) {
  mod <- data$CAG[which.max(x)] #Calculate mode for each column
  B <- sum(x[data$CAG >= mod]) #Sum heights > mode
  A <- sum(x[data$CAG <= mod]) #Sum heights < mode
  B/(A+B)
})

prop <- as.data.frame(prop) #Convert output from list to data frame
prop <- t(prop) #Transpose so samples in rows and result in columnrm
results <- prop

#Expected results
expected <- data.frame(samples = settings$samples,
                   prop = c(0.5068066, 0.3797468, 0.5896748, 0.4146568),
                   ctrlprop = c(0.5068066, 1.0000000, 0.58967480, 0.73324213))

Body:
I think you need to check mapply. It allows us to pass multiple vectors as parameters to a function provided the length of vectors are same. Your function could be modified like this:

prop <- mapply(FUN = function(x,mod) {
    B <- sum(x[data$CAG >= mod]) #Sum heights > mode
    A <- sum(x[data$CAG <= mod]) #Sum heights < mode
    B/(A+B)
},data[, 2:ncol(data)], setting$control)

A simple example how 'mapply' works:

d=data.frame(a=c(1,2,3),b=c(4,5,6))
#>d
#  a b
#1 1 4
#2 2 5
#3 3 6

mapply(function(x,y){x+y},d$a,d$b)
#[1] 5 7 9


问:
How do I pass data between Activities in Android application?
I have a scenario where, after logging in through a login page, there will be a sign-out button on each activity.

On clicking sign-out, I will be passing the session id of the signed in user to sign-out. Can anyone guide me on how to keep session id available to all activities?

Any alternative to this case

答:
If you use kotlin:

In MainActivity1:

```<code>var intent=Intent(this,MainActivity2::class.java)
intent.putExtra("EXTRA_SESSION_ID",sessionId)
startActivity(intent)
</code>```

In MainActivity2:

```<code>if (intent.hasExtra("EXTRA_SESSION_ID")){
    var name:String=intent.extras.getString("sessionId")
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you use kotlin:

In MainActivity1:

var intent=Intent(this,MainActivity2::class.java)
intent.putExtra("EXTRA_SESSION_ID",sessionId)
startActivity(intent)

In MainActivity2:

if (intent.hasExtra("EXTRA_SESSION_ID")){
    var name:String=intent.extras.getString("sessionId")
}


问:
Run real "Bios Setup" in virtual machine
Normally if we want to change Bios Setting, we need to restart the PC and when system boot up we press the hot key (F2 or F10) to go "Bios Setup", then change the setting.

However, I would want to do real Bios Setup from Window Environment...Is it possible to copy the image of Bios (of my computer) to a binary file? then setup a virtual machine to run it and do all the changes? If it is impossible with existing tool (VirtualBox, Qemu,VMWARE)...is it possible to write a special virtualization software to do that?

Thanks

答:
Go to your settings of the virtual machine go to system > motherboard click EFI on

Boot your machine and type in the shell (you need to wait a bit)

"exit" then you will go into the BIOS EFI if you want to quit hard power it off and to turn off the bios for boot again reverse the settings...

(For virtualbox)


问:
Using personas in software development
We are using personas at work. However, is the use of quotes from the imaginary user a good thing to add?</p>

答:
Personas are archetypes intended to model a class of users as a single, specific person. They're intended to communicate user needs clearly, and "engage the empathy of the design and development towards the human target of the design" [Alan Cooper, "About Face"].

You can convey the persona in multiple ways. I've usually seen third-party narrative. Cooper suggests a photographic collage as one way of multiple.

So the question is whether the quotes help convey the persona, and make a team feel driven to meet the needs of this archetype user and the actual users represented. If they do, then yes, using them is a good thing.

Title: Using personas in software development


问:
Change album names using mp3agic
I wanted to loop through a folder containig .mp3 files and changing their album names (if they don't have one) to their title (e.g. Remix.mp3 with Title "Remix" gets the Album "Remix") using mp3agic.

This is my code so far:

```<code>if (mp3file.hasId3v1Tag()) {
    ID3v1 id3v1Tag = mp3file.getId3v1Tag();

    try {
        if (id3v1Tag.getAlbum().equals("")) {
            id3v1Tag.setAlbum(id3v1Tag.getTitle());
            mp3file.save(SAVE_DIR + "\\" + child.getName());
            System.out.println(SAVE_DIR + "/" + child.getName());
        } else {
            mp3file.save(SAVE_DIR + "/" + child.getName());
        }
    } catch (Exception e) {
        mp3file.save(SAVE_DIR + "/" + child.getName());
    }
}
</code>```

I get the following error:

Exception in thread "main" com.mpatric.mp3agic.NotSupportedException: Packing Obselete frames is not supported
      at com.mpatric.mp3agic.ID3v2ObseleteFrame.packFrame(ID3v2ObseleteFrame.java:32)
      at com.mpatric.mp3agic.ID3v2Frame.toBytes(ID3v2Frame.java:83)
      at com.mpatric.mp3agic.AbstractID3v2Tag.packSpecifiedFrames(AbstractID3v2Tag.java:275)
      at com.mpatric.mp3agic.AbstractID3v2Tag.packFrames(AbstractID3v2Tag.java:261)
      at com.mpatric.mp3agic.AbstractID3v2Tag.packTag(AbstractID3v2Tag.java:227)
      at com.mpatric.mp3agic.AbstractID3v2Tag.toBytes(AbstractID3v2Tag.java:218)
      at com.mpatric.mp3agic.Mp3File.save(Mp3File.java:450)
      at de.thejetstream.main.Iterator.(Iterator.java:57)
      at de.thejetstream.main.Main.main(Main.java:12)

at this file:

name: Feel Good in Black and Yellow.mp3

title: Feel Good in Black and Yellow (feat. Gorillaz & De La Soul)

album: Black and Yellow - Single

It crashes at line 57, which equals to the last save (in the catch).

What is the problem with this code? Is it just because the file uses an old kind of codec or something like this?

答:
I found the solution:

The problem was that these files used ip3v2 tags instead of ip3v1. Simply checking which on it is and adjusting the code accordingly solved everything.

Title: Change album names using mp3agic

Body:
I wanted to loop through a folder containig .mp3 files and changing their album names (if they don't have one) to their title (e.g. Remix.mp3 with Title "Remix" gets the Album "Remix") using mp3agic.

This is my code so far:

if (mp3file.hasId3v1Tag()) {
    ID3v1 id3v1Tag = mp3file.getId3v1Tag();

    try {
        if (id3v1Tag.getAlbum().equals("")) {
            id3v1Tag.setAlbum(id3v1Tag.getTitle());
            mp3file.save(SAVE_DIR + "\\" + child.getName());
            System.out.println(SAVE_DIR + "/" + child.getName());
        } else {
            mp3file.save(SAVE_DIR + "/" + child.getName());
        }
    } catch (Exception e) {
        mp3file.save(SAVE_DIR + "/" + child.getName());
    }
}

I get the following error:

Exception in thread "main" com.mpatric.mp3agic.NotSupportedException: Packing Obselete frames is not supported
      at com.mpatric.mp3agic.ID3v2ObseleteFrame.packFrame(ID3v2ObseleteFrame.java:32)
      at com.mpatric.mp3agic.ID3v2Frame.toBytes(ID3v2Frame.java:83)
      at com.mpatric.mp3agic.AbstractID3v2Tag.packSpecifiedFrames(AbstractID3v2Tag.java:275)
      at com.mpatric.mp3agic.AbstractID3v2Tag.packFrames(AbstractID3v2Tag.java:261)
      at com.mpatric.mp3agic.AbstractID3v2Tag.packTag(AbstractID3v2Tag.java:227)
      at com.mpatric.mp3agic.AbstractID3v2Tag.toBytes(AbstractID3v2Tag.java:218)
      at com.mpatric.mp3agic.Mp3File.save(Mp3File.java:450)
      at de.thejetstream.main.Iterator.(Iterator.java:57)
      at de.thejetstream.main.Main.main(Main.java:12)

at this file:

name: Feel Good in Black and Yellow.mp3

title: Feel Good in Black and Yellow (feat. Gorillaz & De La Soul)

album: Black and Yellow - Single

It crashes at line 57, which equals to the last save (in the catch).

What is the problem with this code? Is it just because the file uses an old kind of codec or something like this?


问:
How can I limit the refresh rate on a website?
I know, that it's possible to define a time after which a html website is automatically refreshed. But is there a way to limit this rate, so that for example one can not hold the F5 key pressed in order to refresh the website "continuously"? Either in the html file itself or maybe on the server with some settings especially for that file? </p>

答:
If you be able to prevent to reload the page, you can prevent user for always to close your web site unless he/she close browser and this will be so bothering.

Almost all you can do is to before reload page ask him are you sure? but you can't completely stop user to do that

```<code><script type="text/javascript">
    window.onbeforeunload = function() {
        return "are you sure you want to leave?";
    }
</script>
</code>```

or you can disable F5 on keyDown event e occured

```<code>if ((e.which || e.keyCode) == 82 || (e.which || e.keyCode) == 116) e.preventDefault(); };
</code>```

but If you want just limit the user from exceeding rate you can handle it by programming languages like PHP and ASP and save count of the visit in the user session and if exceed that number redirect him to some warning

Body:
If you be able to prevent to reload the page, you can prevent user for always to close your web site unless he/she close browser and this will be so bothering.

Almost all you can do is to before reload page ask him are you sure? but you can't completely stop user to do that

<script type="text/javascript">
    window.onbeforeunload = function() {
        return "are you sure you want to leave?";
    }
</script>

or you can disable F5 on keyDown event e occured

if ((e.which || e.keyCode) == 82 || (e.which || e.keyCode) == 116) e.preventDefault(); };

but If you want just limit the user from exceeding rate you can handle it by programming languages like PHP and ASP and save count of the visit in the user session and if exceed that number redirect him to some warning


问:
deploying es2015 nodejs site to azure
I am building a site with node.js express
and this is my file structure:
local file structure

the dist folder holds the packed version of the site and the src the dev
also I have 2 server file once for each version.
I went with that style after doing a pluralsight course with the same style.

my npm start script is:

```<code>"scripts": {
    "start": "node node_modules/babel-cli/bin/babel-node.js tools/distServer.
},
</code>```

locally it works great.
I hooked my azure webapp to my github repo for this project and each time it tells me the the build was successfully even that at first it looked for a server.js file at the root, I added it later as a copy of the distServer file.
and then I noticed another error:

```<code>"Start script "./node_modules/babel-cli/bin/babel-node.js server.js" from package.json is not found."
</code>```

as the built was successful I didn't pay too much attention to it, but when I try to access the site it returns only 500 errors
once I checked the logs they were full of:

```<code>import express from 'express';
^^^^^^
SyntaxError: Unexpected token import
</code>```

I have no idea how to make it work on azure, like it does locally and would appreciate any help.

答:
It seems like your local node js version does not match you node js version on azure .

Compare your node js version by doing (node -v or nodejs -v ) on both environnement .

Title: deploying es2015 nodejs site to azure

Body:
I am building a site with node.js express
and this is my file structure:
local file structure

the dist folder holds the packed version of the site and the src the dev
also I have 2 server file once for each version.
I went with that style after doing a pluralsight course with the same style.

my npm start script is:

"scripts": {
    "start": "node node_modules/babel-cli/bin/babel-node.js tools/distServer.
},

locally it works great.
I hooked my azure webapp to my github repo for this project and each time it tells me the the build was successfully even that at first it looked for a server.js file at the root, I added it later as a copy of the distServer file.
and then I noticed another error:

"Start script "./node_modules/babel-cli/bin/babel-node.js server.js" from package.json is not found."

as the built was successful I didn't pay too much attention to it, but when I try to access the site it returns only 500 errors
once I checked the logs they were full of:

import express from 'express';
^^^^^^
SyntaxError: Unexpected token import

I have no idea how to make it work on azure, like it does locally and would appreciate any help.


问:
Git rebase local vs git pull --rebase origin
I have a local (never pushed to a remote) feature branch F1 made from master with a few commits. I don't seem to understand a difference between these two actions (F1 is the current branch):

```<code>git fetch origin
git rebase master
</code>```

and

```<code>git pull --rebase origin master
</code>```

My expectation is that they should be equivalent but they aren't - different results are produced.

What's wrong with my thinking?

答:
```<code>git fetch origin
</code>```

only download remote files from a remote repository into your local branch.

```<code>git rebase master
</code>```

takes the whole branch (the commits that are in your branch), and put on the top of your local repository. It changes the history of your project.

```<code>git pull --rebase origin master
</code>```

git pull by default, performs a merge, but you can force it with a rebase option.

check this link

Body:
I have a local (never pushed to a remote) feature branch F1 made from master with a few commits. I don't seem to understand a difference between these two actions (F1 is the current branch):

git fetch origin
git rebase master

and

git pull --rebase origin master

My expectation is that they should be equivalent but they aren't - different results are produced.

What's wrong with my thinking?

Body:
git fetch origin

only download remote files from a remote repository into your local branch.

git rebase master

takes the whole branch (the commits that are in your branch), and put on the top of your local repository. It changes the history of your project.

git pull --rebase origin master

git pull by default, performs a merge, but you can force it with a rebase option.

check this link


问:
Generating a long string in AutoFixture
I want to generate a random string of - say length 80.

I'm thinking something like Fixture.Create<string>(length: 80);
or Fixture.Create<string>(minimumLength: 60, maximumLenth: 100);. Both would work perfectly fine.

Creating a Customization seems overkill, but maybe that's the correct approach. There are plenty of questions regarding getting a shorter string than the default, which can be achieved with substring, but I need a longer one.

答:
Try this:

```<code>string.Join(string.Empty,Fixture.CreateMany<char>(stringLength))
</code>```

stringLength is how long you wanted your generated string to be.

or

By default Fixture.Create<string>() creates a string of length 36.

So if you want a string length more than 36, this code will generate a string of length 72:

```<code>string.Join(string.Empty,Fixture.CreateMany<string>(2))
</code>```

Title: Generating a long string in AutoFixture

Body:
Try this:

string.Join(string.Empty,Fixture.CreateMany<char>(stringLength))

stringLength is how long you wanted your generated string to be.

or

By default Fixture.Create<string>() creates a string of length 36.

So if you want a string length more than 36, this code will generate a string of length 72:

string.Join(string.Empty,Fixture.CreateMany<string>(2))


问:
Performance of Java enums
I was thinking about using enum type to manage i18n in a Java game I'm developing but I was curious about performance issues that can occur when working with enums that have lots of elements (thousands I think).

Actually I'm trying something like:

```<code>public enum Text {
  STRING1,
  STRING2,
  STRING3;

  public String text() {
    return text;
  }

  public String setText() {
    this.text = text;
  }
}
</code>```

Then to load them I can just fill the fields:

```<code>static
{
  Text.STRING1.setText("My localized string1");
  Text.STRING2.setText("My localized string2");
  Text.STRING3.setText("My localized string3");
}
</code>```

Of course when I'll have to manage many languages I'll load them from a file.

What I'm asking is

is an obect allocated (in addition to the string) for every element? (I guess yes, since enums are implemented with objects)

how is the right element retrieved from the enum? is it static at compile time? (I mean when somewhere I use Text.STRING1.text()). So it should be constant complexity or maybe they are just replaced during the compiling phase..

in general, is it a good approach or should I look forward something else?

Thanks

答:
although java has i18n support using ResourceBundle I do not think that idea to use enum for this purpose is so bad. I believe that these 2 approaches can be merged. You can create enum Texts that contains all your text identifiers. You can create resource bundles for each supported language and use the same identifiers in this bundle.

Then implement getText() method in the enum as following:

```<code>return ResourceBundle.getBundle("texts").getString(name());
</code>```

So, you do not have to care about the initialization of texts for each language. The standard mechanism cares about this.

Now you use in code the enums and enjoy all features of bundles. You can also create unit test that verifies that all enum members have appropriate lines in bundle and vice versa to avoid garbage in your bundles.

I will probably use this approach in my next project. Thank you for the idea!

Title: Performance of Java enums

Body:
I was thinking about using enum type to manage i18n in a Java game I'm developing but I was curious about performance issues that can occur when working with enums that have lots of elements (thousands I think).

Actually I'm trying something like:

public enum Text {
  STRING1,
  STRING2,
  STRING3;

  public String text() {
    return text;
  }

  public String setText() {
    this.text = text;
  }
}

Then to load them I can just fill the fields:

static
{
  Text.STRING1.setText("My localized string1");
  Text.STRING2.setText("My localized string2");
  Text.STRING3.setText("My localized string3");
}

Of course when I'll have to manage many languages I'll load them from a file.

What I'm asking is

is an obect allocated (in addition to the string) for every element? (I guess yes, since enums are implemented with objects)

how is the right element retrieved from the enum? is it static at compile time? (I mean when somewhere I use Text.STRING1.text()). So it should be constant complexity or maybe they are just replaced during the compiling phase..

in general, is it a good approach or should I look forward something else?

Thanks

Body:
although java has i18n support using ResourceBundle I do not think that idea to use enum for this purpose is so bad. I believe that these 2 approaches can be merged. You can create enum Texts that contains all your text identifiers. You can create resource bundles for each supported language and use the same identifiers in this bundle.

Then implement getText() method in the enum as following:

return ResourceBundle.getBundle("texts").getString(name());

So, you do not have to care about the initialization of texts for each language. The standard mechanism cares about this.

Now you use in code the enums and enjoy all features of bundles. You can also create unit test that verifies that all enum members have appropriate lines in bundle and vice versa to avoid garbage in your bundles.

I will probably use this approach in my next project. Thank you for the idea!


问:
Springboot client unable register with Eureka using Docker container id
I have several microservices running in Docker Data Center. I have the same Eureka configuration across the services/applications. But some of the applications are registering with their eth0 IP address instead of the container ID.

I have tried setting the preferIpAddress as false but it is not enforcing all the time.

There is no pattern. The same service which registers with container ID during the previous deployment gets registered with IP the other time. I want my services to register always with its container id. Is there a way to enforce it or am I missing something?

Note: I have also cleared all the old docker images from the registry, deployment nodes and tried from the scratch as well.

Eureka Server Config:

```<code>eureka:
  instance:
    hostname: discovery
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:8761/eureka/
</code>```

Microservices client config (It is same across all the microservices)

```<code>eureka:
  client:
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://discovery:8761/eureka/
  instance:
    preferIpAddress: false
    metadataMap:
      instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${random.value}}}
</code>```

Eureka Dashboard Snapshot:

答: Try setting eureka.instance.hostname in your client config.

Body:
I have several microservices running in Docker Data Center. I have the same Eureka configuration across the services/applications. But some of the applications are registering with their eth0 IP address instead of the container ID.

I have tried setting the preferIpAddress as false but it is not enforcing all the time.

There is no pattern. The same service which registers with container ID during the previous deployment gets registered with IP the other time. I want my services to register always with its container id. Is there a way to enforce it or am I missing something?

Note: I have also cleared all the old docker images from the registry, deployment nodes and tried from the scratch as well.

Eureka Server Config:

eureka:
  instance:
    hostname: discovery
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:8761/eureka/

Microservices client config (It is same across all the microservices)

eureka:
  client:
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://discovery:8761/eureka/
  instance:
    preferIpAddress: false
    metadataMap:
      instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${random.value}}}

Eureka Dashboard Snapshot:


问:
Can we verify (or have ) same domain in Amazon SES from different AWS account?
I have two different AWS account and only one domain server like example.com
Now, I cannot share smtp keys with different account, so how can I configure SES with same domain.</p>

答:
To answer your main question.
Yes you can use the verify the same domain (example.com) from multiple AWS Accounts. (If you have your DNS hosted in R53 then its even easier)

See the following excerpt from Amazon Docs

You want to verify the same domain multiple times and you can't have multiple TXT records with the same name—You might need to verify
  your domain more than once because you're sending in different regions
  or you're sending from multiple AWS accounts from the same domain in
  the same region. If your DNS provider does not allow you to have
  multiple TXT records with the same name, there are two workarounds.
  The first workaround, if your DNS provider allows it, is to assign
  multiple values to the TXT record. For example, if your DNS is managed
  by Amazon Route 53, you can set up multiple values for the same TXT
  record as follows:

In the Amazon Route 53 console, choose the
  _amazonses TXT record you added when you verified your domain in the first region.

In the Value box, press Enter after the first value.

Add the value for the additional region, and save the record set.

The
  other workaround is that if you only need to verify your domain twice,
  you can verify it once with _amazonses in the TXT record name and the
  other time you can omit _amazonses from the record name entirely. We
  recommend the previous solution as a best practice, however.

Reference: http://docs.aws.amazon.com/ses/latest/DeveloperGuide/domain-verification-problems.html#domain-verification-common-problems

Also for best practice refer the below Doc
https://aws.amazon.com/blogs/ses/can-i-use-multiple-aws-accounts-with-ses/


问:
react-native: creating image from base64 string for iOS and Android (in react-native-elements list)
I'm trying to display icons in a dynamic (react-native-elements) list from a DB via REST call which delivers the icon as base64 encoded string (i.e. here done with jHipster/swagger).

It has to work for both iOS and Android.

I thought this should be a quite common use case, but it turns out somewhat challenging...

What I tried so far:

using static addImageFromBase64(base64ImageData, success, failure) see here

works for iOS only (@platform ios)

using 'data:' uri scheme like this example (as discussed here):

var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANS ...
<Image source={{uri: base64Icon}} ... />```

the PR mentioned in that discussion was closed later, but somehow it seems that 'data:' scheme still was introduced, see RCTConvert.m, although it is not documented in Image

but again it seems it was implemented only for iOS (only in the .m file)

Looking at Image for Android, it seems that rendering is delegated to the native side and this could be the reason why it was not implemented for Android (at least it does not work for me in Android).

So is there any good way to get a base64 image string into an Android react-native app?

Or is there a good practice or library to solve this (getting icons dynamically from a DB via REST API into a react-native app) in a complete different way?

答:
In fact it works, I was just always combining some different flaws and also added React native elements to increase confusion...

Thanks to martwetzels for leading me in the right direction with the height/width hint.

If someone else has problems with images and the 'data:' scheme, these are the main obstacles I was stumbling over:

For React Native <Image>:

if you use 'data:' in an <Image>, at least you have to provide width and height in style

this is mentioned for Network images in the Guide for Images:

Unlike with static resources, you will need to manually specify the dimensions of your image.

but unfortunately it is not in the reference for Image component nor the 'data:' scheme is mentioned anywhere

So this is a working example for a React Native <Image>:

```<code>var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANS ...
<Image style={{width: 50, height: 50}} source={{uri: base64Icon}}/>
</code>```

For images in a react-native-elements <List>

only the avatar prop will take an url - the leftIcon prop is for icons from an included library like material-icons only - OR for a separate React Native element

the avatar prop can have an optional separate avatarStyle, but will by default scale the image automatically

the leftIcon prop with a nested <Image> will again need a style for the picture to appear, with at least width & height

A working example for React Native Elements <List> with leftIcon prop with an <Image> as element (style mandatory!):

<List>
    {
        myItems.map((item, i) => (
        <ListItem
            key={i}
            title={item.name}
            leftIcon={<Image style={{width: 35, height: 35}} source={{uri: item.base64Icon}}/>}
        />
        ))
    }
</List>
```

<p>A working example for React Native Elements <code><List></code> with <code>avatar</code> prop (no <code>style</code>, but <em>optional</em> <code>avatarStyle</code>):</p>

<pre class="lang-js prettyprint-override"><code><List>
    {
        myItems.map((item, i) => (
        <ListItem
            key={i}
            title={item.name}
            avatar={{uri: item.base64Icon}}
            // optional: avatarStyle={{width: 50, height: 50}}
        />
        ))
    }
</List>
</code>```

So far this is all pretty ovious, once understood... Sorry for asking this dumb question ;-)

As a result, because all my confusion was related to documentation, I will propose some PRs for both React Native and Elements docs.

Edit: PR is now merged and doc changes regarding images with "data:" uri schema and the need to specify size are public meanwhile! Search for "data:" in:

http://facebook.github.io/react-native/docs/images.html

http://facebook.github.io/react-native/docs/image.html

Body:
I'm trying to display icons in a dynamic (react-native-elements) list from a DB via REST call which delivers the icon as base64 encoded string (i.e. here done with jHipster/swagger).

It has to work for both iOS and Android.

I thought this should be a quite common use case, but it turns out somewhat challenging...

What I tried so far:

using static addImageFromBase64(base64ImageData, success, failure) see here

works for iOS only (@platform ios)

using 'data:' uri scheme like this example (as discussed here):

var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANS ...
<Image source={{uri: base64Icon}} ... />

the PR mentioned in that discussion was closed later, but somehow it seems that 'data:' scheme still was introduced, see RCTConvert.m, although it is not documented in Image

but again it seems it was implemented only for iOS (only in the .m file)

Looking at Image for Android, it seems that rendering is delegated to the native side and this could be the reason why it was not implemented for Android (at least it does not work for me in Android).

So is there any good way to get a base64 image string into an Android react-native app?

Or is there a good practice or library to solve this (getting icons dynamically from a DB via REST API into a react-native app) in a complete different way?

Body:
In fact it works, I was just always combining some different flaws and also added React native elements to increase confusion...

Thanks to martwetzels for leading me in the right direction with the height/width hint.

If someone else has problems with images and the 'data:' scheme, these are the main obstacles I was stumbling over:

For React Native <Image>:

if you use 'data:' in an <Image>, at least you have to provide width and height in style

this is mentioned for Network images in the Guide for Images:

Unlike with static resources, you will need to manually specify the dimensions of your image.

but unfortunately it is not in the reference for Image component nor the 'data:' scheme is mentioned anywhere

So this is a working example for a React Native <Image>:

var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANS ...
<Image style={{width: 50, height: 50}} source={{uri: base64Icon}}/>

For images in a react-native-elements <List>

only the avatar prop will take an url - the leftIcon prop is for icons from an included library like material-icons only - OR for a separate React Native element

the avatar prop can have an optional separate avatarStyle, but will by default scale the image automatically

the leftIcon prop with a nested <Image> will again need a style for the picture to appear, with at least width & height

A working example for React Native Elements <List> with leftIcon prop with an <Image> as element (style mandatory!):

<List>
    {
        myItems.map((item, i) => (
        <ListItem
            key={i}
            title={item.name}
            leftIcon={<Image style={{width: 35, height: 35}} source={{uri: item.base64Icon}}/>}
        />
        ))
    }
</List>

A working example for React Native Elements <List> with avatar prop (no style, but optional avatarStyle):

<List>
    {
        myItems.map((item, i) => (
        <ListItem
            key={i}
            title={item.name}
            avatar={{uri: item.base64Icon}}
            // optional: avatarStyle={{width: 50, height: 50}}
        />
        ))
    }
</List>

So far this is all pretty ovious, once understood... Sorry for asking this dumb question ;-)

As a result, because all my confusion was related to documentation, I will propose some PRs for both React Native and Elements docs.

Edit: PR is now merged and doc changes regarding images with "data:" uri schema and the need to specify size are public meanwhile! Search for "data:" in:

http://facebook.github.io/react-native/docs/images.html

http://facebook.github.io/react-native/docs/image.html


问:
Simple python script. Input and output do not match
Short version:
The number of lines in the input and output files are not equal. I don't understand why as I am not adding or subtracting any lines i.e. input file has 12327 lines but output only has 11903.

I can't seem to find any fault with my code. I was hoping someone with more experience could? Thank you.

Detailed version:
I have a simple python script made up of 3 functions.

Function 1 takes a list of numbers from a .txt file (infile), converts all of them into floats, and changes any negative numbers to 0. It then adds them to a list (orginal list). Each element of this list is then printed to an output file. It also tells you the number of lines in the input file.

Function 2 essentially checks the number of lines in the output file.

Function 3 is just runs functions 1 and 2.

The input file has 12327 lines whilst the output file only has 11903.

I made another input file to test the script. This .txt input file has 10 lines a few of which are negative numbers. However the output file is completely empty.

I don't understand why the input and output number of lines are different? I have included the code below.

I would appreciate any advice. Thank you.

```<code>def thelist():  #FUNCTION 1
    original_list = []
    for line in infile:
        newline = float(line)
        if newline < 0:
            newline = 0
        original_list.append(newline)
    print('The input file has', len(original_list), 'lines.')
    for element in original_list:
        print(element, file = outfile)

def outfilelinenumber():    #FUNCTION 2
    outfile = open('outfile.txt')
    improved_list = []
    for line in outfile:
        improved_list.append(line)
    if not improved_list:
        print('Output file is empty.')
    else:
        print('The output file has', len(improved_list), 'lines.')

def main(): #FUNCTION 3
    thelist()
    outfilelinenumber()
    print('\n', '*** Finished ***')

infile = open('infile.txt')
outfile = open('outfile.txt', 'w')

main()
</code>```

答:
One problem is that you never close your output file, so nothing is properly sent to it. You need to take care of your files: if you open it, close it properly. You also do not close your input file, though you do not see the problems that can result from that.

Replace your function with

```<code>def thelist():  #FUNCTION 1
    original_list = []
    for line in infile:
        newline = float(line)
        if newline < 0:
            newline = 0
        original_list.append(newline)
    print('The input file has', len(original_list), 'lines.')
    for element in original_list:
        print(element, file = outfile)
    infile.close()
    outfile.close()
</code>```

Note the two close functions at the end. This takes care of your problem in my tests, though you do have other problems with your file handling that could cause problems. I suggest you look at the tutorial on file handling to learn better file-handling.

Body:
Short version:
The number of lines in the input and output files are not equal. I don't understand why as I am not adding or subtracting any lines i.e. input file has 12327 lines but output only has 11903.

I can't seem to find any fault with my code. I was hoping someone with more experience could? Thank you.

Detailed version:
I have a simple python script made up of 3 functions.

Function 1 takes a list of numbers from a .txt file (infile), converts all of them into floats, and changes any negative numbers to 0. It then adds them to a list (orginal list). Each element of this list is then printed to an output file. It also tells you the number of lines in the input file.

Function 2 essentially checks the number of lines in the output file.

Function 3 is just runs functions 1 and 2.

The input file has 12327 lines whilst the output file only has 11903.

I made another input file to test the script. This .txt input file has 10 lines a few of which are negative numbers. However the output file is completely empty.

I don't understand why the input and output number of lines are different? I have included the code below.

I would appreciate any advice. Thank you.

def thelist():  #FUNCTION 1
    original_list = []
    for line in infile:
        newline = float(line)
        if newline < 0:
            newline = 0
        original_list.append(newline)
    print('The input file has', len(original_list), 'lines.')
    for element in original_list:
        print(element, file = outfile)

def outfilelinenumber():    #FUNCTION 2
    outfile = open('outfile.txt')
    improved_list = []
    for line in outfile:
        improved_list.append(line)
    if not improved_list:
        print('Output file is empty.')
    else:
        print('The output file has', len(improved_list), 'lines.')

def main(): #FUNCTION 3
    thelist()
    outfilelinenumber()
    print('\n', '*** Finished ***')

infile = open('infile.txt')
outfile = open('outfile.txt', 'w')

main()

Body:
One problem is that you never close your output file, so nothing is properly sent to it. You need to take care of your files: if you open it, close it properly. You also do not close your input file, though you do not see the problems that can result from that.

Replace your function with

def thelist():  #FUNCTION 1
    original_list = []
    for line in infile:
        newline = float(line)
        if newline < 0:
            newline = 0
        original_list.append(newline)
    print('The input file has', len(original_list), 'lines.')
    for element in original_list:
        print(element, file = outfile)
    infile.close()
    outfile.close()

Note the two close functions at the end. This takes care of your problem in my tests, though you do have other problems with your file handling that could cause problems. I suggest you look at the tutorial on file handling to learn better file-handling.


问:
How to export schema for the existing table through WebUI in BigQuery?
I want to take the export schema for the existing table through WebUI and recreate a new table with the same structure in BigQuery.

I could not find ways to export schema in WebUI.

答:
The way I'd do it is first create a query with the data that you want, for instance:

```<code>SELECT
  fullvisitorid,
  visitid
FROM `dataset.ga_sessions_20170703`
LIMIT 1
</code>```

And bring just one result. In the Show Options button, you can choose the destination of the results to be another table:

After that, you can remove the 1 row you have in your new table using DML syntax:

```<code>DELETE FROM `new_table`
WHERE fullvisitorid = '1'
</code>```

The result is a new empty table with the desired schema from other table.

Body:
The way I'd do it is first create a query with the data that you want, for instance:

SELECT
  fullvisitorid,
  visitid
FROM `dataset.ga_sessions_20170703`
LIMIT 1

And bring just one result. In the Show Options button, you can choose the destination of the results to be another table:

After that, you can remove the 1 row you have in your new table using DML syntax:

DELETE FROM `new_table`
WHERE fullvisitorid = '1'

The result is a new empty table with the desired schema from other table.


问:
Edit and Continue: "Changes are not allowed when..."
Even if I create a clean WinForms project, Edit and Continue doesn't work and gives me the error:

Changes are not allowed when the debugger has been attached to an already running process or the code being debugged was optimized at build or run time.

Edit and Continue option is checked in Tools → Options → Debugging.

Optimization is not enabled.

Seems like there is no any managed profiler set up.

I am running in Debug mode

I am running on x64 CPU and Windows XP 32-bit, but setting platform target to x86 rather than AnyCpu doesn't help.

Repairing Visual Studio installation doesn't help.

I also found this article on MSDN website:

Unsupported Scenarios

Edit and Continue is not available in the following debugging scenarios:

Debugging on Windows 98.

Mixed-mode (native/managed) debugging.

SQL debugging.

Debugging a Dr. Watson dump.

Editing code after an unhandled exception, when the "Unwind the call stack on unhandled exceptions" option is not selected.

Debugging an embedded runtime application.

Debugging an application with Attach to rather than running the application with Start from the Debug menu.

Debugging optimized code.

Debugging managed code when the target is a 64-bit application. If you want to use Edit and Continue, you must set the target to x86. (Project Properties, Compile tab, Advanced Compiler setting.).

Debugging an old version of your code after a new version failed to build due to build errors.

But I can answer "No" to every item in this list.

It worked before, but several days ago it stopped working, and I don't know what could be the reason.

答: In my case just reseting to default debugger settings and setting IntelliTrace-> only intellytrace events helps</p>


问:
SSIS 2008 R2: Export "0.0000" to Flat File Destination
I have a column called as item_price with data type DECIMAL(12,4).

Records:

```<code>item_price
--------
0.0000
0.1201
0.0001
0.1000
1.0230
</code>```

I want to export the same values into the flat file using SSIS package:

My try:

Added tool Derived Column with the following expression:

item_price == 0.0000 ? "0" : (DT_WSTR,50)item_price

Output:

```<code>item_price
-----------
.0000
</code>```

Added tool Data Conversion and converted to DT_WSTR 50

Output:

```<code>item_price
-----------
.0000
</code>```

答:
Change your source data from table to query,</p>

```<code>SELECT CAST([item_price] AS VARCHAR(12)) AS [item_price]
FROM yourtable;
</code>```

Body:
I have a column called as item_price with data type DECIMAL(12,4).

Records:

item_price
--------
0.0000
0.1201
0.0001
0.1000
1.0230

I want to export the same values into the flat file using SSIS package:

My try:

Added tool Derived Column with the following expression:

item_price == 0.0000 ? "0" : (DT_WSTR,50)item_price

Output:

item_price
-----------
.0000

Added tool Data Conversion and converted to DT_WSTR 50

Output:

item_price
-----------
.0000

Body:
Change your source data from table to query,

SELECT CAST([item_price] AS VARCHAR(12)) AS [item_price]
FROM yourtable;


问:
In which method or event handler if I would to customize in Application tab Menu in screen Bills And Adjustments of Acumatica
I need to customize business logic of screen Bills and Adjustments (AP301000) of Acumatica ERP. Please refer to this screenshot below.

I just need to know, in which method or event handlers of APInvoiceEntry should I check if I need to customize of Application Tab Menu from this screen. ?

I need to know the filter condition while system showing all records, regarding of current vendor in application tab menu.

Maybe if anyone know about my questions.

答:
The information is shown from the following PXSelectJoin object:

```<code>public PXSelectJoin<
        APAdjust,
            InnerJoin<APPayment,
                On<APPayment.docType, Equal<APAdjust.adjgDocType>,
                And<APPayment.refNbr, Equal<APAdjust.adjgRefNbr>>>>>
        Adjustments;
</code>```

So if you want to change filter conditions you will have to define your own select statement with that additional filtering and set the DataMember of that Grid to your defined Select Statement.

Body:
The information is shown from the following PXSelectJoin object:

public PXSelectJoin<
        APAdjust,
            InnerJoin<APPayment,
                On<APPayment.docType, Equal<APAdjust.adjgDocType>,
                And<APPayment.refNbr, Equal<APAdjust.adjgRefNbr>>>>>
        Adjustments;

So if you want to change filter conditions you will have to define your own select statement with that additional filtering and set the DataMember of that Grid to your defined Select Statement.


问:
javascript determining if a day is beyond 2 days
i have a requirement where i only get the name of the day. like what i am doing on friday.

i want to determine if the asked day is beyond 2 days. for example, like today is tuesday. and if someone ask what i am doing on friday. then friday is the 3rd day from today.

in javascript i could see i can do data operation like

```<code>var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
schDate = tomorrow.toDateString();
</code>```

but how do i find if the asked by just day name is beyond 2 days or not?

答:
If you only get day name:

    let days = {
        'sunday' : 0,
        'monday' : 1,
        'tuesday' : 2,
        'wednesday' : 3,
        'thursday' : 4,
        'friday' : 5,
        'saturday' : 6,
    }

    function distanceDays(from, to){
        let date = to;
        if(date < from) date += 7;
        return Math.abs(today - date);
    }

    let date = days['sunday'];
    let today = (new Date).getDay();

    console.log(distanceDays(today, date));```

Body:
i have a requirement where i only get the name of the day. like what i am doing on friday.

i want to determine if the asked day is beyond 2 days. for example, like today is tuesday. and if someone ask what i am doing on friday. then friday is the 3rd day from today.

in javascript i could see i can do data operation like

var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
schDate = tomorrow.toDateString();

but how do i find if the asked by just day name is beyond 2 days or not?


问:
scatter chart formula
I am trying to create a scatter chart on my web page with CSS and few dots images. I have created the design successfully, but now I can't figure out how a scatter chart  actually works.  Can anyone provide me any idea how I can arrange them?  My chart width is 968 and height 432.
like this chart

http://chart.apis.google.com/chart?cht=s&chd=t:12,16,16,24,26,28,41,51,66,68,13,45,81|16,14,22,34,22,31,31,48,71,64,15,38,84&chs=250x100&chl=Hello|World

i cannot use this but i want to know how it works

Thanks for any help.

```<code><?php
$w = 968; $h = 432;
$xmin = 0; $xmax = 968;
$ymin = 10; $ymax = 100;
$x = 10; $y = 10;
$xc = 20;
$yc = 20;
$r = (20)/ 2;
 $xc = $w * (($x - $xmin)/($xmax - $xmin)) - $r . "<br>";
$yc = $h * (($ymax - $y)/($ymax - $ymin)) -$r;
$tr ='';
$data = array("120|90","345|456","45|66","45|45");
foreach($data as $value){
    $new =  explode("|",$value);
    $tr .='<a href="#" style="top:'.$new[0].'px; left:'.$new[1].'px;" class="dot"></a>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

    <style type="text/css">
#most_engaged_graph{
width:968px;
height:432px;
background-color:#CCCCCC;
}
a.dot {
 height:20px;
 width:20px;
 position:absolute;
 background-color:#0033FF;
}
</style>
</head>
<body>
<div id="most_engaged_graph">
<?=$tr?>
</div>
</body>
</html>
</code>```

答:
Well your dot pitch is 20px square, and you need to position them on the graph with the bottom left corner as the origin (0,0).

You need to know the scale of the axis, which you have not stated.  Decide how many pixels per distance upon your axis.

Then you need to convert the position you desire of each point P(x,y), to a position on the screen.  You want the centre pixel of your .dot to be at that location.

As the screen coordinate run from top-left, not bottom-left, you will need to reverse the vertical pixels, so maximum is zero, and zero (or full negative) is the height of the graph, plus/minus half the size of your dot in both cases.

Given:

W = graph width (px), H = graph height (px)

Xmin = minimum x axis, Xmax = maximum x axis

Ymin = minimum y axis, Ymax = maximum y axis

x = x value on graph (Xmin <= x <= Xmax), y = y value on graph (Ymin <= y <= Ymax)

Xc = x-center of dot, Yc = y-center of dot

r = dot radius = (dot width) / 2

Then:

Xc = W * [(x - Xmin)/(Xmax - Xmin)], Yc = H * [(Ymax - y)/(Ymax - Ymin)]

left = Xc - r, top = Yc - r

Untested, I think that is right - might need adjustment.  In particular, subtract 2r from W and H if you need the dots to appear fully within the area (that applies to the whole of the graph, axis et al).

Example code:

```<code><div id="most_engaged_graph">
<?php
$dataPoints = array(
                    array('x' => 5, 'y' => 20),
                    array('x' => 80, 'y' => 50),
                    array('x' => 45, 'y' => 5),
                    array('x' => 68, 'y' => 89),
                    array('x' => 22, 'y' => 43)
              );

foreach ($dataPoints as $cPoint) {
    // Assuming $w, $h, $xmin, $ymin, $xmax, $ymax, $r are defined above
    $xc = $w * (($cPoint['x'] - $xmin) / ($xmax - $xmin));
    $yc = $h * (($ymax - $cPoint['y']) / ($ymax - $ymin));

    $cLeft = $xc - $r;
    $cTop  = $yc - $r;
?>
    <a href="#" style="top: <?php echo $cTop; ?>px; left: <?php echo $cLeft; ?>px;" class="dot"></a>
<?php
}
?>
</div>
</code>```

jQuery version Demo: http://jsfiddle.net/75Mz5/1/

Title: scatter chart formula

Body:
I am trying to create a scatter chart on my web page with CSS and few dots images. I have created the design successfully, but now I can't figure out how a scatter chart  actually works.  Can anyone provide me any idea how I can arrange them?  My chart width is 968 and height 432.
like this chart

http://chart.apis.google.com/chart?cht=s&chd=t:12,16,16,24,26,28,41,51,66,68,13,45,81|16,14,22,34,22,31,31,48,71,64,15,38,84&chs=250x100&chl=Hello|World

i cannot use this but i want to know how it works

Thanks for any help.

<?php
$w = 968; $h = 432;
$xmin = 0; $xmax = 968;
$ymin = 10; $ymax = 100;
$x = 10; $y = 10;
$xc = 20;
$yc = 20;
$r = (20)/ 2;
 $xc = $w * (($x - $xmin)/($xmax - $xmin)) - $r . "
";
$yc = $h * (($ymax - $y)/($ymax - $ymin)) -$r;
$tr ='';
$data = array("120|90","345|456","45|66","45|45");
foreach($data as $value){
    $new =  explode("|",$value);
    $tr .='';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<?=$tr?>

Body:
Well your dot pitch is 20px square, and you need to position them on the graph with the bottom left corner as the origin (0,0).

You need to know the scale of the axis, which you have not stated.  Decide how many pixels per distance upon your axis.

Then you need to convert the position you desire of each point P(x,y), to a position on the screen.  You want the centre pixel of your .dot to be at that location.

As the screen coordinate run from top-left, not bottom-left, you will need to reverse the vertical pixels, so maximum is zero, and zero (or full negative) is the height of the graph, plus/minus half the size of your dot in both cases.

Given:

W = graph width (px), H = graph height (px)

Xmin = minimum x axis, Xmax = maximum x axis

Ymin = minimum y axis, Ymax = maximum y axis

x = x value on graph (Xmin <= x <= Xmax), y = y value on graph (Ymin <= y <= Ymax)

Xc = x-center of dot, Yc = y-center of dot

r = dot radius = (dot width) / 2

Then:

Xc = W * [(x - Xmin)/(Xmax - Xmin)], Yc = H * [(Ymax - y)/(Ymax - Ymin)]

left = Xc - r, top = Yc - r

Untested, I think that is right - might need adjustment.  In particular, subtract 2r from W and H if you need the dots to appear fully within the area (that applies to the whole of the graph, axis et al).

Example code:

<div id="most_engaged_graph">
<?php
$dataPoints = array(
                    array('x' => 5, 'y' => 20),
                    array('x' => 80, 'y' => 50),
                    array('x' => 45, 'y' => 5),
                    array('x' => 68, 'y' => 89),
                    array('x' => 22, 'y' => 43)
              );

foreach ($dataPoints as $cPoint) {
    // Assuming $w, $h, $xmin, $ymin, $xmax, $ymax, $r are defined above
    $xc = $w * (($cPoint['x'] - $xmin) / ($xmax - $xmin));
    $yc = $h * (($ymax - $cPoint['y']) / ($ymax - $ymin));

    $cLeft = $xc - $r;
    $cTop  = $yc - $r;
?>
    <a href="#" style="top: <?php echo $cTop; ?>px; left: <?php echo $cLeft; ?>px;" class="dot"></a>
<?php
}
?>
</div>

jQuery version Demo: http://jsfiddle.net/75Mz5/1/


问:
Select one column header same name and display data horizontal
I have 2 tables :

1-contracts

```<code>    contracts_id  |  subject_contract
    001           |  name
    002           |  name
</code>```

2-contracts_files

```<code>    contracts_id  |  file_data
    001           |  1image <varbinary(MAX)>
    002           |  1image <varbinary(MAX)>
    001           |  2image <varbinary(MAX)>
    002           |  2image <varbinary(MAX)>
</code>```

Need SQL output like this result :

```<code>contracts_id  |  subject_contract  |  file_data   |  file_data
001           |  name              |  1image      |  2image
002           |  name              |  1image      |  2image
</code>```

I try this

```<code>SELECT Contracts.[contracts_id]
      ,Contracts.[subject_contract]
      ,contracts_files.[filedata]

  FROM Contracts , contracts_files

  where contracts_files.contracts_id = Contracts.contracts_id

  AND Contracts.contracts_id=' 001 '
</code>```

but the result was :

```<code>contracts_id  |  subject_contract  |  file_data
    001       |  name              |  1image
    001       |  name              |  2image
</code>```

So how can i create it with 'FOR LOOP' or with 'CASE' ?

答:
You can use pivot as below:</p>

```<code>Select * from (
    SELECT c.[contracts_id]
          ,c.[subject_contract]
          ,cf.[filedata]
          ,RN = Row_Number() over (partition by c.[Contracts_id] order by c.[contracts_id])
      FROM Contracts c join contracts_files cf
      ON cf.contracts_id = c.contracts_id
      ) a
      pivot (max(filedata) for RN in ([1],[2]) ) p
</code>```

Body:
I have 2 tables :

1-contracts

    contracts_id  |  subject_contract
    001           |  name
    002           |  name

2-contracts_files

    contracts_id  |  file_data
    001           |  1image <varbinary(MAX)>
    002           |  1image <varbinary(MAX)>
    001           |  2image <varbinary(MAX)>
    002           |  2image <varbinary(MAX)>

Need SQL output like this result :

contracts_id  |  subject_contract  |  file_data   |  file_data
001           |  name              |  1image      |  2image
002           |  name              |  1image      |  2image

I try this

SELECT Contracts.[contracts_id]
      ,Contracts.[subject_contract]
      ,contracts_files.[filedata]

  FROM Contracts , contracts_files

  where contracts_files.contracts_id = Contracts.contracts_id

  AND Contracts.contracts_id=' 001 '

but the result was :

contracts_id  |  subject_contract  |  file_data
    001       |  name              |  1image
    001       |  name              |  2image

So how can i create it with 'FOR LOOP' or with 'CASE' ?

Body:
You can use pivot as below:

Select * from (
    SELECT c.[contracts_id]
          ,c.[subject_contract]
          ,cf.[filedata]
          ,RN = Row_Number() over (partition by c.[Contracts_id] order by c.[contracts_id])
      FROM Contracts c join contracts_files cf
      ON cf.contracts_id = c.contracts_id
      ) a
      pivot (max(filedata) for RN in ([1],[2]) ) p


问:
Setting dynamics IDs using Jade/Pug
I'm struggling to set dynamic Ids using Jade/Pug.

I got a table with a checkbox column, and I'm trying to set an dynamic/random id in those checkboxes. I'm using #item$index, but it doesn't work.

That's my code:

```<code>tbody(table-select='ms.tableSelectConfig', ng-model='ms.selected')
    tr(ng-repeat='item in ms.items', table-select-item='item')
        td
            table-select-checkbox#item$index
        td {{item.code}}
        td {{item.name}}
        td {{item.component|const:'components'}}
    tr(ng-if='ms.items.length<1')
        td(colspan='4') Nothing found.
</code>```

答:
You are confusing it with Angular template syntax. It could be written in Pug as:  </p>

```<code>table-select-checkbox(id= "item"+index)
</code>```

Title: Setting dynamics IDs using Jade/Pug

Body:
I'm struggling to set dynamic Ids using Jade/Pug.

I got a table with a checkbox column, and I'm trying to set an dynamic/random id in those checkboxes. I'm using #item$index, but it doesn't work.

That's my code:

tbody(table-select='ms.tableSelectConfig', ng-model='ms.selected')
    tr(ng-repeat='item in ms.items', table-select-item='item')
        td
            table-select-checkbox#item$index
        td {{item.code}}
        td {{item.name}}
        td {{item.component|const:'components'}}
    tr(ng-if='ms.items.length<1')
        td(colspan='4') Nothing found.

Body:
You are confusing it with Angular template syntax. It could be written in Pug as:

table-select-checkbox(id= "item"+index)


问:
PostgreSQL: Column does not exist after table creation
I am trying to import a postgresql database through sql code.
I am creating all the tables with their constraints but when reaching the following code:

```<code>COPY "Customers" (Id, "Name") FROM stdin;
</code>```

psql throws an

ERROR:  column "id" of relation "Customers" does not exist.

Here is my Customers table

```<code>CREATE TABLE "Customers" (
"Id" serial NOT NULL,
"Name" varchar(30) NOT NULL UNIQUE
);

ALTER TABLE "Customers" OWNER TO postgres;

ALTER TABLE ONLY "Customers"
    ADD CONSTRAINT "Customers_pkey" PRIMARY KEY ("Id");
</code>```

I've just started working with postgre and im totally lost, any help will be much appreciated.

答:
As commented:

```<code>COPY "Customers" ("Id", "Name") FROM stdin;
</code>```

Bad idea to create identifiers wrapped in double quotes. Only do it if they are otherwise illegal.

Body:
I am trying to import a postgresql database through sql code.
I am creating all the tables with their constraints but when reaching the following code:

COPY "Customers" (Id, "Name") FROM stdin;

psql throws an

ERROR:  column "id" of relation "Customers" does not exist.

Here is my Customers table

CREATE TABLE "Customers" (
"Id" serial NOT NULL,
"Name" varchar(30) NOT NULL UNIQUE
);

ALTER TABLE "Customers" OWNER TO postgres;

ALTER TABLE ONLY "Customers"
    ADD CONSTRAINT "Customers_pkey" PRIMARY KEY ("Id");

I've just started working with postgre and im totally lost, any help will be much appreciated.

Body:
As commented:

COPY "Customers" ("Id", "Name") FROM stdin;

Bad idea to create identifiers wrapped in double quotes. Only do it if they are otherwise illegal.


问:
ASP.NET validators validate on mouse up
I have a compare validator on a Password field compared it to a password repeat field.  If there is a validation error the error doesn't disappear until the lost focus event is fired.  The client wants this changed to be the key up event.

What is the best way of going about this?

答:
It does not seem like there is likely to even be a mouse click in this case. After the field is filled out the user would either tab or click to the next box..in either case the previous box would lose focus and fire the validator...unless i am missing something.

Other than that i'd say javascript is your answer.

Title: ASP.NET validators validate on mouse up


问:
Go back to app after user sets Notification Listener permission
I need the user to enable the Notification Listener permission for my app. For now i just start a new activity as below, but would like that when then user allows the permission, it goes back to my activity by itself?</p>

```<code>startActivity(new Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
</code>```

答:
I figured it out by creating a handler that check every half second if the notification listener contains my package and when true opens my activity again.</p>

```<code>final Handler handler = new Handler();
final int delay = 500; //milliseconds

mRunnable = new Runnable() {
  @Override
  public void run() {
    if((!NotificationManagerCompat.getEnabledListenerPackages(getActivity()).contains(BuildConfig.APPLICATION_ID))){
           handler.postDelayed(mRunnable, delay);
    }else{
           Intent LaunchIntent = getActivity().getIntent();
           startActivity(LaunchIntent);
           //LaunchIntent.finish();
           handler.removeCallbacks(mRunnable);
    }

  }
};
handler.postDelayed(mRunnable, delay);*/
</code>```

Body:
I need the user to enable the Notification Listener permission for my app. For now i just start a new activity as below, but would like that when then user allows the permission, it goes back to my activity by itself?

startActivity(new Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));

Body:
I figured it out by creating a handler that check every half second if the notification listener contains my package and when true opens my activity again.

final Handler handler = new Handler();
final int delay = 500; //milliseconds

mRunnable = new Runnable() {
  @Override
  public void run() {
    if((!NotificationManagerCompat.getEnabledListenerPackages(getActivity()).contains(BuildConfig.APPLICATION_ID))){
           handler.postDelayed(mRunnable, delay);
    }else{
           Intent LaunchIntent = getActivity().getIntent();
           startActivity(LaunchIntent);
           //LaunchIntent.finish();
           handler.removeCallbacks(mRunnable);
    }

  }
};
handler.postDelayed(mRunnable, delay);*/


问:
Why Java doesn't recognize net.sf.jasperreports.engine.util.JRLoader class?
Good afternoon.
I am working on JDK 1.6.

I am trying to integrate JasperReports to the Java Web Application of company where I work. First, I created an simple Java Application for to test the reports generation, and I used the next libraries (jars):

Commons collections 3.2.1

Commons beanutils 1.9.0

Commons digester 2.1

Commons logging 1.2

Groovy all 1.8.0

Joda time 2.0

JasperReports 6.0.0

With these I was able to create a report but, when I transfered this libraries to the Java Web Application,happened the next exception:

```<code>javax.faces.FacesException: #{bean.functionCalled}: java.lang.reflect.InvocationTargetException
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at org.primefaces.application.CleanupActionListener.processAction(CleanupActionListener.java:42)
    ...
Caused by: javax.faces.el.EvaluationException: java.lang.reflect.InvocationTargetException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 51 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    ... 52 more
Caused by: java.lang.NoClassDefFoundError: net/sf/jasperreports/engine/util/JRLoader
    ... 85 more
Caused by: java.lang.ClassNotFoundException: net.sf.jasperreports.engine.util.JRLoader
    at java.net.URLClassLoader$1.run(Unknown Source)
    ...
    ... 86 more
</code>```

I found out that the cause of the problem is the commons loggin version, or the libraries combination.
By default, this Java Web Application has the next libraries:

Commons collections 3.2

Commons beanutils 1.6

Commons digester 1.8.1

Commons logging 1.1.1

Groovy all 1.5.4

Joda time 1.6

I'm making differents versions combinations but not working, the problem persist.

What you recommend me?

Thank you so much.

答:
This is a missing jars in the class path issue.

I had this issue and found that with by adding the missing jars to the class path it resolved the issue.

From the below article java.dzone.com article here I found that the minimal jars necessary are...Now The versions numbers have changed but with these libraries only I managed to get it working.

jasperreports-3.5.3.jar and above version

commons-digester-2.1.jar

commons-collections-3.2.jar (commons-collections.jar)

commons-logging-1.2.jar

commons-beanutils.jar

iText-5.0.jar (used infor PDF exporting)

Body:
Good afternoon.
I am working on JDK 1.6.

I am trying to integrate JasperReports to the Java Web Application of company where I work. First, I created an simple Java Application for to test the reports generation, and I used the next libraries (jars):

Commons collections 3.2.1

Commons beanutils 1.9.0

Commons digester 2.1

Commons logging 1.2

Groovy all 1.8.0

Joda time 2.0

JasperReports 6.0.0

With these I was able to create a report but, when I transfered this libraries to the Java Web Application,happened the next exception:

javax.faces.FacesException: #{bean.functionCalled}: java.lang.reflect.InvocationTargetException
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at org.primefaces.application.CleanupActionListener.processAction(CleanupActionListener.java:42)
    ...
Caused by: javax.faces.el.EvaluationException: java.lang.reflect.InvocationTargetException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 51 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    ... 52 more
Caused by: java.lang.NoClassDefFoundError: net/sf/jasperreports/engine/util/JRLoader
    ... 85 more
Caused by: java.lang.ClassNotFoundException: net.sf.jasperreports.engine.util.JRLoader
    at java.net.URLClassLoader$1.run(Unknown Source)
    ...
    ... 86 more

I found out that the cause of the problem is the commons loggin version, or the libraries combination.
By default, this Java Web Application has the next libraries:

Commons collections 3.2

Commons beanutils 1.6

Commons digester 1.8.1

Commons logging 1.1.1

Groovy all 1.5.4

Joda time 1.6

I'm making differents versions combinations but not working, the problem persist.

What you recommend me?

Thank you so much.


问:
Conditionally replace elements of a vector based on an index
It's best explained with an example.

I have a vector, or column from data.frame named vec:

```<code>vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

```<code>c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)
</code>```

If we had:

```<code>vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

The end vector would look like:

```<code>c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)
</code>```

A very badly written solution is:

```<code>vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}
</code>```

答:
Another fast solution:

```<code>vec[rep(which(vec == 1), each = 3) + c(1:3)] <- 1
</code>```

which gives:

```<code>> vec
 [1] NA NA  1  1  1  1 NA  1  1  1  1 NA NA NA
</code>```

Benchmarking is only really useful when done on larger datasets. A benchmark with a 10k larger vector and the several posted solutions:

```<code>library(microbenchmark)

microbenchmark(ans.jaap = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                           vec[rep(which(vec == 1), each = 3) + c(1:3)] <- 1},
               ans.989 = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                          r <- which(vec==1);
                          vec[c(mapply(seq, r, r+3))] <- 1},
               ans.sotos = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                            vec[unique(as.vector(t(sapply(which(vec == 1), function(i) seq(i+1, length.out = 3)))))] <- 1},
               ans.gregor = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                             vec[is.na(vec)] <- 0;
                             n <- length(vec);
                             vec <- vec + c(0, vec[1:(n-1)]) + c(0, 0, vec[1:(n-2)]) + c(0, 0, 0, vec[1:(n-3)]);
                             vec[vec == 0] <- NA},
               ans.moody = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                            output <- sapply(1:length(vec),function(i){any(!is.na(vec[max(0,i-3):i]))});
                            output[output] <- 1;
                            output[output==0] <- NA},
               ans.nicola = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                             `[<-`(vec,c(outer(which(vec==1),1:3,"+")),1)})
</code>```

which gives the following benchmark:

```<code>Unit: microseconds
       expr        min         lq       mean     median         uq        max neval   cld
   ans.jaap   1778.905   1937.414   3064.686   2100.595   2257.695  86233.593   100 a
    ans.989  87688.166  89638.133  96992.231  90986.269  93326.393 182431.366   100   c
  ans.sotos 125344.157 127968.113 132386.664 130117.438 132951.380 214460.174   100    d
 ans.gregor   4036.642   5824.474  10861.373   6533.791   7654.587  87806.955   100  b
  ans.moody 173146.810 178369.220 183698.670 180318.799 184000.062 264892.878   100     e
 ans.nicola    966.927   1390.486   1723.395   1604.037   1904.695   3310.203   100 a
</code>```

Body:
It's best explained with an example.

I have a vector, or column from data.frame named vec:

vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)

If we had:

vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)

The end vector would look like:

c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)

A very badly written solution is:

vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}

Body:
Another fast solution:

vec[rep(which(vec == 1), each = 3) + c(1:3)] <- 1

which gives:

> vec
 [1] NA NA  1  1  1  1 NA  1  1  1  1 NA NA NA

Benchmarking is only really useful when done on larger datasets. A benchmark with a 10k larger vector and the several posted solutions:

library(microbenchmark)

microbenchmark(ans.jaap = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                           vec[rep(which(vec == 1), each = 3) + c(1:3)] <- 1},
               ans.989 = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                          r <- which(vec==1);
                          vec[c(mapply(seq, r, r+3))] <- 1},
               ans.sotos = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                            vec[unique(as.vector(t(sapply(which(vec == 1), function(i) seq(i+1, length.out = 3)))))] <- 1},
               ans.gregor = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                             vec[is.na(vec)] <- 0;
                             n <- length(vec);
                             vec <- vec + c(0, vec[1:(n-1)]) + c(0, 0, vec[1:(n-2)]) + c(0, 0, 0, vec[1:(n-3)]);
                             vec[vec == 0] <- NA},
               ans.moody = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                            output <- sapply(1:length(vec),function(i){any(!is.na(vec[max(0,i-3):i]))});
                            output[output] <- 1;
                            output[output==0] <- NA},
               ans.nicola = {vec <- rep(c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA),1e4);
                             `[<-`(vec,c(outer(which(vec==1),1:3,"+")),1)})

which gives the following benchmark:

Unit: microseconds
       expr        min         lq       mean     median         uq        max neval   cld
   ans.jaap   1778.905   1937.414   3064.686   2100.595   2257.695  86233.593   100 a
    ans.989  87688.166  89638.133  96992.231  90986.269  93326.393 182431.366   100   c
  ans.sotos 125344.157 127968.113 132386.664 130117.438 132951.380 214460.174   100    d
 ans.gregor   4036.642   5824.474  10861.373   6533.791   7654.587  87806.955   100  b
  ans.moody 173146.810 178369.220 183698.670 180318.799 184000.062 264892.878   100     e
 ans.nicola    966.927   1390.486   1723.395   1604.037   1904.695   3310.203   100 a


问:
TFS Build Agent Use Multiple Configurations
I'm trying to use the TFS Build Agent to replace my old Build.bat file that builds all of my projects.  I have C# and C++ projects that need to be compiled.  All of the C# projects have the configuration Release|Any CPU and all of the C++ projects have the Release|Win32 configuration.  I've created a MSBuild project that includes all of my projects.  How do I specify that the C++ projects should use the Release|Win32 configuration and the C# projects should use the Release|Any CPU configuration.

thanks
John.

答: Are your projects contained in a single solution? If so, you can create a solution configuration that maps the appropriate project-level configurations for each project.</p>