问:
random numbers after a ? on an image is this for far expires headers?
I was pooking around a random site on the internet and noticed that on the images they have numbers prefixing it: icons-16.png?1292032550

I've heard of people optimising websites with far expires headers. If someone changes the content that doesn't change very often, the cache won't get refreshed. Ergo this new image won't get re-downloaded to someones cache. Because the filename has to change.

答: This is a way to compensate for your web server e.g. not generating the correct ETag headers when your content changes. Using ETag with a value like the file's hash will be a better approach for telling the browser that some content has changed and it must be reloaded.</p>


来源: stackexchange

问:
converting seconds to hours,minutes, and seconds?
so Im trying to make a program that can convert s from input into h, m and s. my code so far looks like this:

```<code>import java.util.Scanner;

class q2_5{
  public static void main(String args[]){

    Scanner input = new Scanner(System.in);
    int s=0;//seconds
    int m=0;//minutes
    int h=0;//hour
    System.out.println("how many seconds?");
    s=input.nextInt();
    if(s >= 60){
      m=s/60;
    } if(m>=60){
      h=m/60;
    }
    System.out.println(s + "s = " + h + " h " + m + " m " + s + "s ");
  }
}
</code>```

ok so I had to initialize s,m,h to 0 cuz if not I was getting problems in the if statement, so I just put it to 0, since I can change it later :) ok. so the problem with this program right now is that if I type in 3603 I get this output: 3603s = 1 h 60 m 3603s, if I type in 3600 I get this:
3600s = 1 h 60 m 3600s, but the output should have been 3603s = 1h 0m 3s and 3600s = 1h 0m 0s respectively. any tips/advice/solutions on how to solve this problem? :D thanks in advance!

答:
```<code>import java.util.Scanner;

public class Prg2 {

    public static void main(String[] args) {
        int seconds = 0;
        int hours = 0;
        int minutes = 0;
        int secondsDisp = 0;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of seconds: ");
        seconds = in.nextInt();
        hours = seconds/3600;
        minutes = (seconds - (hours*3600))/60;
        secondsDisp = ((seconds - (hours*3600)) - (minutes * 60));
        System.out.println(seconds + " seconds equals " + hours + " hours, " + minutes + " minutes and " + secondsDisp + " seconds");
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
so Im trying to make a program that can convert s from input into h, m and s. my code so far looks like this:

import java.util.Scanner;

class q2_5{
  public static void main(String args[]){

    Scanner input = new Scanner(System.in);
    int s=0;//seconds
    int m=0;//minutes
    int h=0;//hour
    System.out.println("how many seconds?");
    s=input.nextInt();
    if(s >= 60){
      m=s/60;
    } if(m>=60){
      h=m/60;
    }
    System.out.println(s + "s = " + h + " h " + m + " m " + s + "s ");
  }
}

ok so I had to initialize s,m,h to 0 cuz if not I was getting problems in the if statement, so I just put it to 0, since I can change it later :) ok. so the problem with this program right now is that if I type in 3603 I get this output: 3603s = 1 h 60 m 3603s, if I type in 3600 I get this:
3600s = 1 h 60 m 3600s, but the output should have been 3603s = 1h 0m 3s and 3600s = 1h 0m 0s respectively. any tips/advice/solutions on how to solve this problem? :D thanks in advance!


问:
Android Async Problems?
I have a function which returns a list after doing an operation on 700 images.
The function takes some time and hence the app freezes. How to overcome this problem?
I am returning a list of all the images to be displayed so I am stuck now.
Any suggestions with a code will be helpful.</p>

答:
The best option to process those amount of data is to use IntentService. Here is good tutorial https://code.tutsplus.com/tutorials/android-fundamentals-intentservice-basics--mobile-6183
You can trigger the intent service onCreate Activity or on Button press. You will have to register BroadcastReceiver on your Activity and after the task is done UI will be updated  onReceive BroadcastReceiver.

Title: Android Async Problems?


问:
How to join two mysql tables in my Django application
I have two tables in my MySQL database:

First Table: For Subscribers (id, name, area, subscriberNumber, phoneNumber)

Second Table: For Monthly Payment (id, subscriberNumber, month, year, amount, discount, fine, billNumber)

I have a HTML page where the list of the Subscriber. Whenever the admin clicks on one of the subscriber the detail of the user is shown.But currently I can only show the user detail(from the first table). I want the page to show the list of payments he/she has done throughout the year(from the second table). I want to join the tables and show the details of both the table in one HTML page.

This is the code to display the data of the first table in views.py

```<code>@login_required
def userDetail(request, id=None):
    instance = get_object_or_404(Subscribers.objects.using('db2'), id=id)
    context = {
        "Name": instance.name,
        "instance": instance,
    }
    return render(request, 'userDetail.html', context)
</code>```

How do I show the payments done by the user on the same page as their details are in?

Models.py

```<code>from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse

class Subscribers(models.Model):
    name = models.CharField(max_length=120)
    area = models.CharField(max_length=30)
    phoneNumber = models.CharField(max_length=10)
    installationCost = models.CharField(max_length=10)
    subsNumber = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("userDetail", kwargs={"id": self.id})

class Payments(models.Model):
    month = models.CharField(max_length=120)
    year = models.CharField(max_length=4)
    amount = models.CharField(max_length=10)
    discount = models.CharField(max_length=10)
    fine = models.CharField(max_length=10)
    billNumber = models.CharField(max_length=100)
    subsNumber = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("userDetail", kwargs={"id": self.id})
</code>```

答:
why to use to much of confusion??

do this instead

```<code>instance = Subscribers.objects.using('db2').get(id=id)
payment_info = Payments.objects.using('db2').get(subsNumber=instance.subsNumber)
context = {
    "Name": instance.name,
    "instance": instance,
    "payment": payment_info
}
</code>```

Body:
I have two tables in my MySQL database:

First Table: For Subscribers (id, name, area, subscriberNumber, phoneNumber)

Second Table: For Monthly Payment (id, subscriberNumber, month, year, amount, discount, fine, billNumber)

I have a HTML page where the list of the Subscriber. Whenever the admin clicks on one of the subscriber the detail of the user is shown.But currently I can only show the user detail(from the first table). I want the page to show the list of payments he/she has done throughout the year(from the second table). I want to join the tables and show the details of both the table in one HTML page.

This is the code to display the data of the first table in views.py

@login_required
def userDetail(request, id=None):
    instance = get_object_or_404(Subscribers.objects.using('db2'), id=id)
    context = {
        "Name": instance.name,
        "instance": instance,
    }
    return render(request, 'userDetail.html', context)

How do I show the payments done by the user on the same page as their details are in?

Models.py

from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse

class Subscribers(models.Model):
    name = models.CharField(max_length=120)
    area = models.CharField(max_length=30)
    phoneNumber = models.CharField(max_length=10)
    installationCost = models.CharField(max_length=10)
    subsNumber = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("userDetail", kwargs={"id": self.id})

class Payments(models.Model):
    month = models.CharField(max_length=120)
    year = models.CharField(max_length=4)
    amount = models.CharField(max_length=10)
    discount = models.CharField(max_length=10)
    fine = models.CharField(max_length=10)
    billNumber = models.CharField(max_length=100)
    subsNumber = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("userDetail", kwargs={"id": self.id})

Body:
why to use to much of confusion??

do this instead

instance = Subscribers.objects.using('db2').get(id=id)
payment_info = Payments.objects.using('db2').get(subsNumber=instance.subsNumber)
context = {
    "Name": instance.name,
    "instance": instance,
    "payment": payment_info
}


问:
Back button issue in login module
Let say I have 2 forms in my app. let say loginForm and mainForm. In loginForm allows the user to enter his/her username and password then goes to mainForm. From mainForm is I click the back button it will go back to loginForm and now my issue is from loginForm if I will click back button it goes again to mainForm without logging in.

What is the best to make this correct?

loginForm

```<code>EditText edtU = (EditText) findViewById (R.id.txtU);
EditText edtP = (EditText) findViewById (R.id.txtP);
Button btnLogin = (Button) findViewById (R.id.btLog);
btnLogin.setOnclickListener(new OnclickListener).......{
    if(u.matches("ryan") && p.matches("biugos"){
      Intent i = new Intent(getApplicationContext(),mainForm.class);
      startActivity(i);
    }
}
</code>```

答:
After passing the intent use finish like

```<code>startActivity(new Intent(context, ActivityName.class));
finish();
</code>```

and use on back pressed to close the system.

```<code>  @Override
public void onBackPressed() {
    super.onBackPressed();
    System.exit(1);
}
</code>```

Title: Back button issue in login module

Body:
Let say I have 2 forms in my app. let say loginForm and mainForm. In loginForm allows the user to enter his/her username and password then goes to mainForm. From mainForm is I click the back button it will go back to loginForm and now my issue is from loginForm if I will click back button it goes again to mainForm without logging in.

What is the best to make this correct?

loginForm

EditText edtU = (EditText) findViewById (R.id.txtU);
EditText edtP = (EditText) findViewById (R.id.txtP);
Button btnLogin = (Button) findViewById (R.id.btLog);
btnLogin.setOnclickListener(new OnclickListener).......{
    if(u.matches("ryan") && p.matches("biugos"){
      Intent i = new Intent(getApplicationContext(),mainForm.class);
      startActivity(i);
    }
}

Body:
After passing the intent use finish like

startActivity(new Intent(context, ActivityName.class));
finish();

and use on back pressed to close the system.

  @Override
public void onBackPressed() {
    super.onBackPressed();
    System.exit(1);
}


问:
cannot write(2) file larger than 2GB (up to 2TB)
I have a program written by C. It computes something and writes the output into a file. My problem is that it does not write more than 2GB. Let me put a simplified code.

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <malloc.h>
#include <errno.h>
int main() {
    size_t size = 3221225472LL;
    char *map = malloc(size);
    size_t allocated = malloc_usable_size(map);
    int fd = open("myfile", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0644);
    ssize_t written = write(fd, map, size);
    return 0;
}
</code>```

Although the output file "myfile" is being created, the size is always 2GB (2147479552 Bytes) for whatever size greater than 2GB I requested.The malloc() successfully allocated memory of the requested size (in this case, "allocated" is 3GB). The errno after write() is 0.

The environment is the following

OS:  Ubuntu 16.04.1 x86_64

Physical memory size: 32GB

File system: ext4

Compilation:

```<code>gcc code.c -D_FILE_OFFSET_BITS=64 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE
</code>```

What could be the reason for this?

Addition:
After getting two responses, I added retry code as following:

```<code>int main() {
    size_t size = 3221225472LL;
    char *map = malloc(size);
    size_t allocated = malloc_usable_size(map);
    int fd = open("myfile", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0644);
    ssize_t written = write(fd, map, size);
    while (written < size) {
        written += write(fd, &map[written], size-written);
    }
    return 0;
}
</code>```

答:
Some file systems have strong limitations on file size, notably FAT32. And both disk quotas and resource limits (see setrlimit(2) with RLIMIT_FSIZE) are limiting the file size (and of course the available space on the file system itself).

BTW, your written is very probably (after your call to write(2)...) only 231. You should check it.

And write(2) documents:

On Linux, write() (and similar system calls) will transfer at most
         0x7ffff000 (2,147,479,552) bytes, returning the number of bytes
         actually transferred.  (This is true on both 32-bit and 64-bit
         systems.)

Of course, a given call to write(2) should never be expected to have written all the required bytes (and this is true on all POSIX systems, and was true on Unix systems of the 1980s). For example, a write to some pipe(7) surely won't be able to write that many bytes.

BTW, a huge single call to write(2) is probably (or at least could well be) less efficient than several of them with a smaller buffer. The optimal buffer size is implementation specific (and related also to the page cache and to the hardware) but might be several dozen of kilobytes, or at most a megabyte.

You may prefer to use <stdio.h> buffered fwrite(3) but you should check the returned count.

At last, you might consider using mmap(2) in your case. See also msync(2)

Notice that for large files, the real bottleneck is the hardware (the disk itself). So it does not matter much to use buffered fwrite for performance.

(you mention a terabyte file in a comment)

BTW, for large terabyte datasets, using some higher-level approach (notably a database, perhaps with sqlite, or an indexed file à la GDBM) could actually be more efficient, because you are then able to write only a portion of the data (or because the RDBMS runs on a remote database server, e.g. using MariaDB or PostGreSQL). YMMV. But the hardware bandwidth is less than a Gbyte/sec so writing a terabyte might take a few hours. And even with a huge swap size you won't be able to malloc a terabyte without thrashing on a 32 Gbyte machine.

You might also use cleverly posix_fadvise(2) to slightly improve performance (but not much: for terabyte files the bottleneck is the hardware)

Body:
I have a program written by C. It computes something and writes the output into a file. My problem is that it does not write more than 2GB. Let me put a simplified code.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <malloc.h>
#include <errno.h>
int main() {
    size_t size = 3221225472LL;
    char *map = malloc(size);
    size_t allocated = malloc_usable_size(map);
    int fd = open("myfile", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0644);
    ssize_t written = write(fd, map, size);
    return 0;
}

Although the output file "myfile" is being created, the size is always 2GB (2147479552 Bytes) for whatever size greater than 2GB I requested.The malloc() successfully allocated memory of the requested size (in this case, "allocated" is 3GB). The errno after write() is 0.

The environment is the following

OS:  Ubuntu 16.04.1 x86_64

Physical memory size: 32GB

File system: ext4

Compilation:

gcc code.c -D_FILE_OFFSET_BITS=64 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE

What could be the reason for this?

Addition:
After getting two responses, I added retry code as following:

int main() {
    size_t size = 3221225472LL;
    char *map = malloc(size);
    size_t allocated = malloc_usable_size(map);
    int fd = open("myfile", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0644);
    ssize_t written = write(fd, map, size);
    while (written < size) {
        written += write(fd, &map[written], size-written);
    }
    return 0;
}


问:
Bi grams creating and counting of the probability of the word occurrence
I am trying to build a bigram model and to calculate the probability of word occurence. I should
•Select an appropriate data structure to store bigrams.
• increment counts for a combination of word and previous word. This means I need to keep track of what the previous word was.
• compute the probability of the current word based on the previous word count.

Prob  of  curr  word  = count(prev  word,  curr  word)/ count(previous word)

Consider we observed the following word sequences:
finger remarked
finger on
finger on
finger in
finger . Notice that "finger on " was observed twice. Also, notice that the period is treated as a separate word.Given the  information in  this data  structure,  we  can compute  the probability (on|finger) as   2/5   =   0.4.

Here is what I got so far:

```<code>filename = 'blah-blah.txt'
bigrams ={}
prev_word = "START"

# opening the filename in read mode
with open(filename, "r") as fp:
    for line in fp:

        words = line.split()

        for word in words:
            word = word.lower()
            bigram = prev_word + ' ' + word

            if bigram in bigrams:
                bigrams[bigram] += 1

            else:
                bigrams[bigram] = 1
                prev_word = word
                #print(bigram)

for k, v in bigrams.items():
    probability = v/1

    print(k + ':' + str(probability))
</code>```

But I stuck at the moment how I can keep track the previous word to count the probability. I just put 1 here "probability = v/1" just to figure out what exactly I have to do next.
Thanks a lot for any help!

答:
with this formula:

Prob of curr word = count(prev word, curr word)/ count(previous word)..

and if the "previous word" is the total occurrence of the previous word in the document then you might want to just create another dictionary for your vocab where the occurrences of the words that you have is stored. :)

like

```<code>vocab = {'my_word' : num_occurences}
</code>```

Body:
I am trying to build a bigram model and to calculate the probability of word occurence. I should
•Select an appropriate data structure to store bigrams.
• increment counts for a combination of word and previous word. This means I need to keep track of what the previous word was.
• compute the probability of the current word based on the previous word count.

Prob  of  curr  word  = count(prev  word,  curr  word)/ count(previous word)

Consider we observed the following word sequences:
finger remarked
finger on
finger on
finger in
finger . Notice that "finger on " was observed twice. Also, notice that the period is treated as a separate word.Given the  information in  this data  structure,  we  can compute  the probability (on|finger) as   2/5   =   0.4.

Here is what I got so far:

filename = 'blah-blah.txt'
bigrams ={}
prev_word = "START"

# opening the filename in read mode
with open(filename, "r") as fp:
    for line in fp:

        words = line.split()

        for word in words:
            word = word.lower()
            bigram = prev_word + ' ' + word

            if bigram in bigrams:
                bigrams[bigram] += 1

            else:
                bigrams[bigram] = 1
                prev_word = word
                #print(bigram)

for k, v in bigrams.items():
    probability = v/1

    print(k + ':' + str(probability))

But I stuck at the moment how I can keep track the previous word to count the probability. I just put 1 here "probability = v/1" just to figure out what exactly I have to do next.
Thanks a lot for any help!

Body:
with this formula:

Prob of curr word = count(prev word, curr word)/ count(previous word)..

and if the "previous word" is the total occurrence of the previous word in the document then you might want to just create another dictionary for your vocab where the occurrences of the words that you have is stored. :)

like

vocab = {'my_word' : num_occurences}


问:
Is there any way to display a Windows form BEFORE the "Startup" form is loaded in VB.NET?
My company's main software package includes a hefty configuration library which loads on startup. This config library includes some mandatory settings which, if not supplied (via command line arguments), cause the entire application to exit.

This has never been an issue for our users, who launch the software via scripts which have the needed command line arguments supplied automatically. But sometimes when debugging our software we developers forget to specify the necessary arguments in Visual Studio's debug options; it's then very annoying to be greeted with the message Config specification invalid -- missing required parameters X, Y, and Z -- shutting down (I'm paraphrasing, of course).

It's not really a big deal, just an annoyance. Still, I felt it worthwhile to throw together a little form to make this process a little less painful; it notifies the user which parameters are missing and allows him/her to specify values for those parameters directly on the form, without having to restart the application.

My intentions were good (I think?), but it seems I can't get this solution to actually work. The problem is that after I've launched our software with missing settings, the form pops up and prompts me as expected; but after I've entered the required parameters and it's time for the application to "really" start, I get this InvalidOperationException:

SetCompatibleTextRenderingDefault must
  be called before the first
  IWin32Window object is created in the
  application.

I think I understand what's going on here: the VB.NET project I'm working on is doing something like this "behind the scenes"*:

```<code>Sub Main()
    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault(False)
    Application.Run(New MainForm)
End Sub
</code>```

That call to SetCompatibleTextRenderingDefault is, apparently, throwing an exception because a form was already created and displayed prior to its execution.

Is there any way around this? Is there perhaps a more "proper" solution to this problem that I'm not thinking of (i.e., should I not be trying to collect user input via a form at all)?

*This is a best guess based on what I've seen in C# WinForms projects. Strangely, unless I'm missing something, it seems that VB.NET WinForms projects completely hide this from the developer.

答: Perhaps you could use the static Debugger.IsAttached (or even a #DEBUG directive) in your program's "main" function that feeds in some input file (say an XML file) into your parsed args collection instead?

ContentLicense: CC BY-SA 2.5

Body:
My company's main software package includes a hefty configuration library which loads on startup. This config library includes some mandatory settings which, if not supplied (via command line arguments), cause the entire application to exit.

This has never been an issue for our users, who launch the software via scripts which have the needed command line arguments supplied automatically. But sometimes when debugging our software we developers forget to specify the necessary arguments in Visual Studio's debug options; it's then very annoying to be greeted with the message Config specification invalid -- missing required parameters X, Y, and Z -- shutting down (I'm paraphrasing, of course).

It's not really a big deal, just an annoyance. Still, I felt it worthwhile to throw together a little form to make this process a little less painful; it notifies the user which parameters are missing and allows him/her to specify values for those parameters directly on the form, without having to restart the application.

My intentions were good (I think?), but it seems I can't get this solution to actually work. The problem is that after I've launched our software with missing settings, the form pops up and prompts me as expected; but after I've entered the required parameters and it's time for the application to "really" start, I get this InvalidOperationException:

SetCompatibleTextRenderingDefault must
  be called before the first
  IWin32Window object is created in the
  application.

I think I understand what's going on here: the VB.NET project I'm working on is doing something like this "behind the scenes"*:

Sub Main()
    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault(False)
    Application.Run(New MainForm)
End Sub

That call to SetCompatibleTextRenderingDefault is, apparently, throwing an exception because a form was already created and displayed prior to its execution.

Is there any way around this? Is there perhaps a more "proper" solution to this problem that I'm not thinking of (i.e., should I not be trying to collect user input via a form at all)?

*This is a best guess based on what I've seen in C# WinForms projects. Strangely, unless I'm missing something, it seems that VB.NET WinForms projects completely hide this from the developer.


问:
How to get back to the latest commit after checking out a previous commit?
I sometimes check out some previous version of the code to examine or test.  I have seen instructions on what to do if I wish to modify previous commits -- but suppose I make no changes.  After I've done e.g. git checkout HEAD^, how do I get back to the tip of the branch?.. git log no longer shows me the SHA of the latest commit.

答:
If your latest commit is on the master branch, you can simply use</p>

```<code>git checkout master
</code>```

Body:
If your latest commit is on the master branch, you can simply use

git checkout master


问:
Why is Bitmap Scan0 still valid after unlocking?
As far as I know, there is no concept of pointer in managed environment where garbage collector is in charge of memory management. Like if someone wants to manipulate the pixel values in a bitmap, she/he has to first lock it like the following code does.

```<code>Bitmap Image = new Bitmap(width, height,
                   System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
Rectangle rect = new Rectangle(0, 0, width, height);
BitmapData bmpData = Image.LockBits(rect, ImageLockMode.ReadWrite,
PixelFormat.Format8bppIndexed);
IntPtr imageScan0 = bmpData.Scan0;
unsafe
{
    byte* ptr = (byte*)imageScan0;
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            *ptr++ = 128;
        }
            }
        }
Image.UnlockBits(bmpData);
</code>```

My main problem is that:
If I store the imageScan0 information and then unlock the bitmap, I can still use the imageScan0 to manipulate its values just like I manipulate it between lock and unlock operations.

I have tested it and I am surprised to see that imageScan0 is still valid to manipulate.
My guess is that the underlying bitmap resides on unmanaged memory.

答:
My main problem is that: If I store the imageScan0 information and then unlock the bitmap, I can still use the imageScan0 to manipulate its values just like I manipulate it between lock and unlock operations.

You can. But that does not mean you may.

The system just isn't designed to immediately invalidate the memory 100% of the time when you unlock it. The lock gave you a pointer, and promised that for the duration until you unlock, that pointer will remain valid.

But the converse isn't true. The system doesn't guarantee the pointer will immediately become invalid after you unlock.

But that also doesn't mean you can go around using it. You've told the system you're done with the pointer. It's now free to move it, invalidate it, whatever it wants at any time. You're playing with fire if you continue to use it.

It is not a problem per se for the pointer to remain valid after being unlocked. It is a problem for you to use it; it's your job to make sure you don't, not the system's.

Body:
As far as I know, there is no concept of pointer in managed environment where garbage collector is in charge of memory management. Like if someone wants to manipulate the pixel values in a bitmap, she/he has to first lock it like the following code does.

Bitmap Image = new Bitmap(width, height,
                   System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
Rectangle rect = new Rectangle(0, 0, width, height);
BitmapData bmpData = Image.LockBits(rect, ImageLockMode.ReadWrite,
PixelFormat.Format8bppIndexed);
IntPtr imageScan0 = bmpData.Scan0;
unsafe
{
    byte* ptr = (byte*)imageScan0;
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            *ptr++ = 128;
        }
            }
        }
Image.UnlockBits(bmpData);

My main problem is that:
If I store the imageScan0 information and then unlock the bitmap, I can still use the imageScan0 to manipulate its values just like I manipulate it between lock and unlock operations.

I have tested it and I am surprised to see that imageScan0 is still valid to manipulate.
My guess is that the underlying bitmap resides on unmanaged memory.


问:
MySQL UTF8/ASCII/ISO Encoding Issue
I'm having an issue with encoding of a MySQL table.

What I've Done

The table is set to be utf8_unicode_ci

The columns are also set to be utf8_unicode_ci where needed

Setting "SET NAMES utf8" and the meta before viewing

The Data/Problem

The column in question (review) is copied and pasted from MS word.

Have strings such as Ã¢â‚¬â„¢ instead of '

PrÃªt Ã  Manger which should read Pret a Manger

other similar issues

Ive Tried:

```<code>UPDATE table_name SET col_name = CONVERT(CONVERT(CONVERT(col_name USING latin1) USING binary) USING utf8);
</code>```

This cut's off the data. E.g "a nice review costing £10 and more". After running the above query, it gets turned into "a ncie review costing".

Any help/advice would be appreciated greatly.
Thanks,
Matt

答:
To double check you have the correct utf8 settings try this:

Login to mysql and run  mysql> show variables like 'char%';

The output should look like:

```

     +--------------------------+---------------------------------+
     | Variable_name            | Value                           |
     +--------------------------+---------------------------------+
     | character_set_client     | utf8                            |
     | character_set_connection | utf8                            |
     | character_set_database   | utf8                            |
     | character_set_filesystem | binary                          |
     | character_set_results    | utf8                            |
     | character_set_server     | utf8                            |
     | character_set_system     | utf8                            |
     | character_sets_dir       | /usr/local/mysql/share/charsets/|
     +--------------------------+---------------------------------+

```

Then run mysql> show variables like 'collation%';

This should give you:

```

     +----------------------+-----------------+
     | Variable_name        | Value           |
     +----------------------+-----------------+
     | collation_connection | utf8_general_ci |
     | collation_database   | utf8_unicode_ci |
     | collation_server     | utf8_unicode_ci |
     +----------------------+-----------------+

```

If not edit your /etc/my.cnf or /etc/mysql/my.cnf if you an not find it just run sudo find / -name my.cnf

After you do find it do vim /etc/my.cnf press i to insert text and add

```

    [mysqld]
    collation-server = utf8_unicode_ci
    init-connect='SET NAMES utf8'
    character-set-server = utf8

```

Feel free to comment out the previous/old [mysqld] block or lines.

Save the file by pressing esc then type :wq and press enter

Restart mysql service mysql restart or service mysqld restart

Hope that helps.

Title: MySQL UTF8/ASCII/ISO Encoding Issue

Body:
I'm having an issue with encoding of a MySQL table.

What I've Done

The table is set to be utf8_unicode_ci

The columns are also set to be utf8_unicode_ci where needed

Setting "SET NAMES utf8" and the meta before viewing

The Data/Problem

The column in question (review) is copied and pasted from MS word.

Have strings such as Ã¢â‚¬â„¢ instead of '

PrÃªt Ã  Manger which should read Pret a Manger

other similar issues

Ive Tried:

UPDATE table_name SET col_name = CONVERT(CONVERT(CONVERT(col_name USING latin1) USING binary) USING utf8);

This cut's off the data. E.g "a nice review costing £10 and more". After running the above query, it gets turned into "a ncie review costing".

Any help/advice would be appreciated greatly.
Thanks,
Matt

Body:
To double check you have the correct utf8 settings try this:

Login to mysql and run  mysql> show variables like 'char%';

The output should look like:

     +--------------------------+---------------------------------+
     | Variable_name            | Value                           |
     +--------------------------+---------------------------------+
     | character_set_client     | utf8                            |
     | character_set_connection | utf8                            |
     | character_set_database   | utf8                            |
     | character_set_filesystem | binary                          |
     | character_set_results    | utf8                            |
     | character_set_server     | utf8                            |
     | character_set_system     | utf8                            |
     | character_sets_dir       | /usr/local/mysql/share/charsets/|
     +--------------------------+---------------------------------+

Then run mysql> show variables like 'collation%';

This should give you:

     +----------------------+-----------------+
     | Variable_name        | Value           |
     +----------------------+-----------------+
     | collation_connection | utf8_general_ci |
     | collation_database   | utf8_unicode_ci |
     | collation_server     | utf8_unicode_ci |
     +----------------------+-----------------+

If not edit your /etc/my.cnf or /etc/mysql/my.cnf if you an not find it just run sudo find / -name my.cnf

After you do find it do vim /etc/my.cnf press i to insert text and add

    [mysqld]
    collation-server = utf8_unicode_ci
    init-connect='SET NAMES utf8'
    character-set-server = utf8

Feel free to comment out the previous/old [mysqld] block or lines.

Save the file by pressing esc then type :wq and press enter

Restart mysql service mysql restart or service mysqld restart

Hope that helps.


问:
"hadoop namenode -format" formats wrong directory
I'm trying to install Hadoop 1.1.2.21 on CentOS 6.3

I've configured dfs.name.dir in /etc/hadoop/conf/hdfs-site.xml file

```<code><name>dfs.name.dir</name>
<value>/mnt/ext/hadoop/hdfs/namenode</value>
</code>```

But when I run "hadoop namenode -format" command, it formats /tmp/hadoop-hadoop/dfs/name instead.

What am I missing?

答: Please don't set HADOOP_CONF_DIR. You can check .bashrc file and remove it.</p>

Body:
I'm trying to install Hadoop 1.1.2.21 on CentOS 6.3

I've configured dfs.name.dir in /etc/hadoop/conf/hdfs-site.xml file

<name>dfs.name.dir</name>
<value>/mnt/ext/hadoop/hdfs/namenode</value>

But when I run "hadoop namenode -format" command, it formats /tmp/hadoop-hadoop/dfs/name instead.

What am I missing?


问:
Bash: all of array except last element
Bash has a neat way of giving all elements in an array except the first:

```<code>"${a[@]:1}"
</code>```

To get all except the last I have found:

```<code>"${a[@]:0:$((${#a[@]}-1))}"
</code>```

But, man, that is ugly.

Is there an elegant alternative?

答:
I am not sure how much improvement it would be, but you can drop the arithmetic operator ($(())) and starting index (0 here):

```<code>${a[@]::${#a[@]}-1}
</code>```

So:

```<code>$ foo=( 1 2 3 )

$ echo "${foo[@]::${#foo[@]}-1}"
1 2
</code>```

As you can see, the improvement is purely syntactical; the idea remains the same.

Title: Bash: all of array except last element

Body:
Bash has a neat way of giving all elements in an array except the first:

"${a[@]:1}"

To get all except the last I have found:

"${a[@]:0:$((${#a[@]}-1))}"

But, man, that is ugly.

Is there an elegant alternative?

Body:
I am not sure how much improvement it would be, but you can drop the arithmetic operator ($(())) and starting index (0 here):

${a[@]::${#a[@]}-1}

So:

$ foo=( 1 2 3 )

$ echo "${foo[@]::${#foo[@]}-1}"
1 2

As you can see, the improvement is purely syntactical; the idea remains the same.


问:
JetBrains dotCover: Coverage session finished with errors: Out of allowed iteration to generate unique temp name
I generate a coverage report using dotCover.exe from the command line, but it randomly fails with this error:

```<code>[JetBrains dotCover] Coverage session finished with errors: Out of allowed iteration to generate unique temp name
  [location] = C:\Build Agent\work\f532b5455ffc19e9\Profiler\Kernel\Windows\Native\Solution\core\src\Util\temp_util.cpp(44)
  [function] = class boost::filesystem::path __cdecl jetbrains::profiler::temp::`anonymous-namespace'::create_temp<class jetbrains::profiler::temp::create_temp_file::<lambda_91d5f1a5933e4e60038be7ca777762a9>,0x010>(const class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> > &,class jetbrains::profiler::temp::create_temp_file::<lambda_91d5f1a5933e4e60038be7ca777762a9> &&)
  [file name] = C:\Temp\ft.EC76593C.tmp
  [WIN32 error] = 80, The file exists.
</code>```

My command line looks like this:

```<code>dotCover.exe analyse /TargetExecutable=nunit3-console.exe /TargetArguments="unittest1.dll unittest2.dll ... unittest10.dll" /ReportType="html" /Output=CodeCoverage.html /Filters="+:*;-:*.*Tests;-:*.*.Tests;-:*.Tests;-:*.Tests*" /TempDir=C:\Temp\
</code>```

It seems the more DLLs I try to cover the more likely it is to fail with this error. From the error message it seems dotCover is written in C++ and it's using boost::filesystem::path to create a temp file but there is some race condition and it tries to create a new temp file where it already exists. My dotCover version is JetBrains dotCover Console Runner 2017.1.2. Build 108.0.20170428.80910.

Does anyone have any idea what's how to fix that error?

Edit: There is another error with which it fails - Access is denied:

```<code>  [function] = class boost::filesystem::path __cdecl jetbrains::profiler::temp::`anonymous-namespace'::create_temp<class jetbrains::profiler::temp::create_temp_file::<lambda_91d5f1a5933e4e60038be7ca777762a9>,0x010>(const class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> > &,class jetbrains::profiler::temp::create_temp_file::<lambda_91d5f1a5933e4e60038be7ca777762a9> &&)
  [file name] = C:\Temp2\ft.0A96C261.tmp
  [WIN32 error] = 5, Access is denied.
</code>```

Again, this happens randomly - usually it will fail 3 times and then run successfully on the 4th.

答:
was running into this issue at times, using the early access version(JetBrains.dotCover.CommandLineTools.2017.2.20170630.95316-eap06) made it  disappear the issue till now.

Looks like a bug in the dotcover tool opened here .You can
  download the latest version of dotcover commandline tools from
  here

Edit:

Get the latest version of dotcover from here as it has the issue resolved

Body:
I generate a coverage report using dotCover.exe from the command line, but it randomly fails with this error:

[JetBrains dotCover] Coverage session finished with errors: Out of allowed iteration to generate unique temp name
  [location] = C:\Build Agent\work\f532b5455ffc19e9\Profiler\Kernel\Windows\Native\Solution\core\src\Util\temp_util.cpp(44)
  [function] = class boost::filesystem::path __cdecl jetbrains::profiler::temp::`anonymous-namespace'::create_temp<class jetbrains::profiler::temp::create_temp_file::<lambda_91d5f1a5933e4e60038be7ca777762a9>,0x010>(const class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> > &,class jetbrains::profiler::temp::create_temp_file::<lambda_91d5f1a5933e4e60038be7ca777762a9> &&)
  [file name] = C:\Temp\ft.EC76593C.tmp
  [WIN32 error] = 80, The file exists.

My command line looks like this:

dotCover.exe analyse /TargetExecutable=nunit3-console.exe /TargetArguments="unittest1.dll unittest2.dll ... unittest10.dll" /ReportType="html" /Output=CodeCoverage.html /Filters="+:*;-:*.*Tests;-:*.*.Tests;-:*.Tests;-:*.Tests*" /TempDir=C:\Temp\

It seems the more DLLs I try to cover the more likely it is to fail with this error. From the error message it seems dotCover is written in C++ and it's using boost::filesystem::path to create a temp file but there is some race condition and it tries to create a new temp file where it already exists. My dotCover version is JetBrains dotCover Console Runner 2017.1.2. Build 108.0.20170428.80910.

Does anyone have any idea what's how to fix that error?

Edit: There is another error with which it fails - Access is denied:

  [function] = class boost::filesystem::path __cdecl jetbrains::profiler::temp::`anonymous-namespace'::create_temp<class jetbrains::profiler::temp::create_temp_file::<lambda_91d5f1a5933e4e60038be7ca777762a9>,0x010>(const class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> > &,class jetbrains::profiler::temp::create_temp_file::<lambda_91d5f1a5933e4e60038be7ca777762a9> &&)
  [file name] = C:\Temp2\ft.0A96C261.tmp
  [WIN32 error] = 5, Access is denied.

Again, this happens randomly - usually it will fail 3 times and then run successfully on the 4th.


问:
Cannot import PyQt4.QtGui
I have a working Python 2.6 install and just installed the PyQt4 built for Python 2.6 (available at http://www.riverbankcomputing.co.uk/software/pyqt/download). When I try to import PyQt4.QtGui I get the following error:

```<code>ImportError: DLL load failed: The specified procedure could not be found.
</code>```

I'm on Windows 2k8 64-bit, but my Python install is 32-bit.

答: Did you verify that PyQt4 is for 32 or 64 bits?, I had the same problem I was using python 2.7.13  32 bit in Windows 10 and PyQt4 4.11 64 Bit, and changed PyQt4 for a 32 bit and it work immediately.</p>

Title: Cannot import PyQt4.QtGui

Body:
I have a working Python 2.6 install and just installed the PyQt4 built for Python 2.6 (available at http://www.riverbankcomputing.co.uk/software/pyqt/download). When I try to import PyQt4.QtGui I get the following error:

ImportError: DLL load failed: The specified procedure could not be found.

I'm on Windows 2k8 64-bit, but my Python install is 32-bit.


问:
Apply function to each cell in DataFrame in place in pandas
Is it possible to apply function to each cell in a DataFrame in place in pandas?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow in place application:

```<code>import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)
</code>```

returns:

```<code>               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06
</code>```

frame = frame.applymap(format) will temporarily hold 2 copies of frame in
memory, which I don't want.

I know one can apply a function to each cell in place with a NumPy array: Mapping a NumPy array in place.

答:
If it matters a lot to you, you can try making your own cpython function

I found the applymap function in pandas

```<code>def applymap(self, func):
      # ...
      def infer(x):
            if x.empty:
                return lib.map_infer(x, func)
            return lib.map_infer(x.asobject, func)

      return self.apply(infer)
</code>```

which shows that lib.map_infer is doing the work behind the scenes

lib.map_infer is a cython method defined here, you can clearly see them allocating space for a new result: result = np.empty(n, dtype=object), found below

```<code>def map_infer(ndarray arr, object f, bint convert=1):
    """
    Substitute for np.vectorize with pandas-friendly dtype inference
    Parameters
    ----------
    arr : ndarray
    f : function
    Returns
    -------
    mapped : ndarray
    """
    cdef:
        Py_ssize_t i, n
        ndarray[object] result
        object val

    n = len(arr)
    result = np.empty(n, dtype=object)
    for i in range(n):
        val = f(util.get_value_at(arr, i))

        # unbox 0-dim arrays, GH #690
        if is_array(val) and PyArray_NDIM(val) == 0:
            # is there a faster way to unbox?
            val = val.item()

        result[i] = val

    if convert:
        return maybe_convert_objects(result,
                                     try_float=0,
                                     convert_datetime=0,
                                     convert_timedelta=0)

return result
</code>```

... and this is the cliff hangar to my answer. Perhaps the op or someone can modify the cython method to create an inplace version that modifies the original array instead of the creating a new result

-I'm currently away from my coding computer so I can't test anything :(

Body:
Is it possible to apply function to each cell in a DataFrame in place in pandas?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow in place application:

import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)

returns:

               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06

frame = frame.applymap(format) will temporarily hold 2 copies of frame in
memory, which I don't want.

I know one can apply a function to each cell in place with a NumPy array: Mapping a NumPy array in place.

Body:
If it matters a lot to you, you can try making your own cpython function

I found the applymap function in pandas

def applymap(self, func):
      # ...
      def infer(x):
            if x.empty:
                return lib.map_infer(x, func)
            return lib.map_infer(x.asobject, func)

      return self.apply(infer)

which shows that lib.map_infer is doing the work behind the scenes

lib.map_infer is a cython method defined here, you can clearly see them allocating space for a new result: result = np.empty(n, dtype=object), found below

def map_infer(ndarray arr, object f, bint convert=1):
    """
    Substitute for np.vectorize with pandas-friendly dtype inference
    Parameters
    ----------
    arr : ndarray
    f : function
    Returns
    -------
    mapped : ndarray
    """
    cdef:
        Py_ssize_t i, n
        ndarray[object] result
        object val

    n = len(arr)
    result = np.empty(n, dtype=object)
    for i in range(n):
        val = f(util.get_value_at(arr, i))

        # unbox 0-dim arrays, GH #690
        if is_array(val) and PyArray_NDIM(val) == 0:
            # is there a faster way to unbox?
            val = val.item()

        result[i] = val

    if convert:
        return maybe_convert_objects(result,
                                     try_float=0,
                                     convert_datetime=0,
                                     convert_timedelta=0)

return result

... and this is the cliff hangar to my answer. Perhaps the op or someone can modify the cython method to create an inplace version that modifies the original array instead of the creating a new result

-I'm currently away from my coding computer so I can't test anything :(


问:
Mapping same local folder to different visual studio tfs instance
I have already mapped a local folder C:/Projects to VS2015 TFS.

Now I have installed VS2017 on the same machine. So can i map the same local folder to VS2017 also ? If it is then what are the pros and cons doing this ?

Also, I found there is no project.json file available in VS2017 which is available in VS2015. So in this case if I do Get Latest Version(if local folder can be mapped to multiple Visual Studio instances) then there will be a problem ?

Thanks for the help !

答:
No, we cannot map to the same local folder.

The VS clients can identify the workspaces which be created in both VS 2015 and VS 2017 in same machine. So, when we use VS 2017, we can select the workspace which is created in VS 2015 to track the projects, but cannot map other projects to the same local folder which already be mapped. Otherwise it will pop up the error message something like "The path E:\Andy\0706 is already mapped in workspace LC0706."

We can only map to its sub folders if you want to map other sources to the specific local folder. eg : E:\Andy\0706\subfolder


问:
Getting a Custom Checkbox to Display Correctly
I am planning a page with about 20 or more checkboxes and I want to use a particular style of custom checkbox to match other things in other places on the website. Essentially, the aim is for an unchecked box to look like this

and the checked version will be coloured. At the moment I can colour the icon and the text but I'm drawing a blank with the border.

The HTML and PHP code is this:

```<code><?php foreach ($amenity_array as $key => $value) {?>
<label class="amenity">
<input name="<?php echo $key ?>" type="checkbox" value="<?php echo $key ?>"><i class="icon-<?php echo $key ?>"></i><span><?php echo $value ?></span>
</label>
<?php }?>
</code>```

The CSS is this:

```<code>.amenity{position:relative;border:1px solid #ccc;color:#ccc;padding:.25em;width:14.5em;margin:0 .5em .5em 0;float:left;white-space:nowrap;overflow:hidden; cursor:pointer}
.amenity input{z-index:-1;opacity:0;width:0}
.amenity i{color:#ccc}
/* Hover and focus states */
.amenity:hover input ~ i{color:#3498db}

/* Checked state */
.amenity input:checked ~ i{color:#5470a3}
.amenity input:checked ~ span{color:#007aba}
</code>```

Obviously I need a third line under the checked state with

```<code>.amenity {border:1px solid #007aba}
</code>```

but how do I invoke it only when the input is checked?

答:
Considering basic documentation on  html element :

The  tag defines a label for an  element.

The  element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the  element, it toggles the control.

The  element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the  element, it toggles the control.

The for attribute of the  tag should be equal to the id attribute of the related element to bind them together.

EDIT :

The idea of your question is : "Can I apply a CSS property depending on the child state ?".

The answer is NO. It is impossible, and it has been answered many times on Stack Overflow already.

Thus, there are two mains solutions :

1) Use Javascript !

I too prefer making beautiful CSS solutions all the time, but in your case, javascript solves the problem in a second with any framework.

For instance in AngularJS but don't import this MVC for that, go for native javascript or the framework you are using:

```<code>ng-style="{'border' : disabled ? '1px solid red' : '1px solid blue'}"
</code>```

Pros : Very fast, very simple, don't change your html structure at all.

Cons: Some people may feel dishonoured not succeeding in doing a pure CSS solution.

2) A CSS trick.

I just did one, you can see it on this fiddle. The idea was to create a sibling .absolute positioned div with the dimensions of the .amenity div, remove the border of the .amenity div and then apply it to absolute div.

As it is a sibling, we don't have the parent problem anymore and the trick is done.

Pros : Fast and understandable too, pure CSS solution.

Cons : You can use width 100%, but the height need to be hardcoded somehow. If you use SASS, it can be okay, but if the height of your icon or font change with the screen dimension, you'll need to use media queries or just put every height in em.

Don't forget to remove some pixels to height and width to keep some place for the border pixels !

Absolute div class :

```<code>.amenity .borderer {width : 100%; position: absolute; top: 0; left : 0; height : calc(37px - 4px); width : calc(100% - 2px); border:1px solid #ccc;}
</code>```

Border change :

```<code>.amenity input:checked ~ div{border:1px solid #007aba}
</code>```

New HTML :

```<code><div class="amenity">
  <label>
    <input name="disabled" type="checkbox" value="disabled"><i
    class="icon">D </i><span>Disabled Access</span>
    <div class="borderer">

   </div>
  </label>

</div>
</code>```

Body:
I am planning a page with about 20 or more checkboxes and I want to use a particular style of custom checkbox to match other things in other places on the website. Essentially, the aim is for an unchecked box to look like this

and the checked version will be coloured. At the moment I can colour the icon and the text but I'm drawing a blank with the border.

The HTML and PHP code is this:

<?php foreach ($amenity_array as $key => $value) {?>

<input name="<?php echo $key ?>" type="checkbox" value="<?php echo $key ?>"><i class="icon-<?php echo $key ?>"><?php echo $value ?>

<?php }?>

The CSS is this:

.amenity{position:relative;border:1px solid #ccc;color:#ccc;padding:.25em;width:14.5em;margin:0 .5em .5em 0;float:left;white-space:nowrap;overflow:hidden; cursor:pointer}
.amenity input{z-index:-1;opacity:0;width:0}
.amenity i{color:#ccc}
/* Hover and focus states */
.amenity:hover input ~ i{color:#3498db}

/* Checked state */
.amenity input:checked ~ i{color:#5470a3}
.amenity input:checked ~ span{color:#007aba}

Obviously I need a third line under the checked state with

.amenity {border:1px solid #007aba}

but how do I invoke it only when the input is checked?

Body:
Considering basic documentation on  html element :

The  tag defines a label for an  element.

The  element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the  element, it toggles the control.

The  element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the  element, it toggles the control.

The for attribute of the  tag should be equal to the id attribute of the related element to bind them together.

EDIT :

The idea of your question is : "Can I apply a CSS property depending on the child state ?".

The answer is NO. It is impossible, and it has been answered many times on Stack Overflow already.

Thus, there are two mains solutions :

1) Use Javascript !

I too prefer making beautiful CSS solutions all the time, but in your case, javascript solves the problem in a second with any framework.

For instance in AngularJS but don't import this MVC for that, go for native javascript or the framework you are using:

ng-style="{'border' : disabled ? '1px solid red' : '1px solid blue'}"

Pros : Very fast, very simple, don't change your html structure at all.

Cons: Some people may feel dishonoured not succeeding in doing a pure CSS solution.

2) A CSS trick.

I just did one, you can see it on this fiddle. The idea was to create a sibling .absolute positioned div with the dimensions of the .amenity div, remove the border of the .amenity div and then apply it to absolute div.

As it is a sibling, we don't have the parent problem anymore and the trick is done.

Pros : Fast and understandable too, pure CSS solution.

Cons : You can use width 100%, but the height need to be hardcoded somehow. If you use SASS, it can be okay, but if the height of your icon or font change with the screen dimension, you'll need to use media queries or just put every height in em.

Don't forget to remove some pixels to height and width to keep some place for the border pixels !

Absolute div class :

.amenity .borderer {width : 100%; position: absolute; top: 0; left : 0; height : calc(37px - 4px); width : calc(100% - 2px); border:1px solid #ccc;}

Border change :

.amenity input:checked ~ div{border:1px solid #007aba}

New HTML :

<div class="amenity">
  <label>
    <input name="disabled" type="checkbox" value="disabled"><i
    class="icon">D </i><span>Disabled Access</span>
    <div class="borderer">

   </div>
  </label>

</div>


问:
Can I configure record identification to work with custom naming and a custom controller for a rails resource?
Suppose I have defined in my routes the following line

```<code>resources :a, controller: 'b', as: 'a'
</code>```

and the following controller

```<code>class BController < ApplicationController
  ...
  def new
    @b = B.new
  end

  def edit
    @b = B.find(params[:id])
  end
end
</code>```

Is there a way to write a form partial so that I can use it on both the new and edit views? For example, if I write

```<code><%= form_for @b do |f| %>
  ...
<% end %>
</code>```

Rails gives me a routing error.

Inelegant Solution

I came up with an inelegant solution to write the BController as

```<code>class BController < ApplicationController
  ...
  def new
    @b = B.new
    @url = bs_path
  end

  def edit
    @b = B.find(params[:id])
    @url = b_path
  end
end
</code>```

and then write the form as

```<code><%= form_for(@b, url: @url) do |f| %>
  ...
<% end %>
</code>```

I wonder if there is a more "Rails" way to accomplish this though without having to write in the @url variable

答:
Seems like you might be looking for the :path option to the resources...if I followed your example correctly, you have a model B and you want to access it at /a or /a/:id and be able to use a_path(instance_of_b)...so I feel like you want your route to be

```<code>resources :b, as: 'a', path: 'a'
</code>```

and I believe that'll do what you're wanting.

Body:
Suppose I have defined in my routes the following line

resources :a, controller: 'b', as: 'a'

and the following controller

class BController < ApplicationController
  ...
  def new
    @b = B.new
  end

  def edit
    @b = B.find(params[:id])
  end
end

Is there a way to write a form partial so that I can use it on both the new and edit views? For example, if I write

<%= form_for @b do |f| %>
  ...
<% end %>

Rails gives me a routing error.

Inelegant Solution

I came up with an inelegant solution to write the BController as

class BController < ApplicationController
  ...
  def new
    @b = B.new
    @url = bs_path
  end

  def edit
    @b = B.find(params[:id])
    @url = b_path
  end
end

and then write the form as

<%= form_for(@b, url: @url) do |f| %>
  ...
<% end %>

I wonder if there is a more "Rails" way to accomplish this though without having to write in the @url variable

Body:
Seems like you might be looking for the :path option to the resources...if I followed your example correctly, you have a model B and you want to access it at /a or /a/:id and be able to use a_path(instance_of_b)...so I feel like you want your route to be

resources :b, as: 'a', path: 'a'

and I believe that'll do what you're wanting.


问:
How to customize/style woocommerce account page
As you can see here: https://wildlatina.com/my-account/

the white body is not inside the page and there is not margin padding for the login form? what did I do to mess this up? I'm a beginner when it comes to editing with css so please go easy on me. Just would like the account page to look nice.

答:
1) you can add this css add into theme or child theme style.css

```<code>.hfeed.site.grid-container.container.grid-parent{
width: 80%;
}
</code>```

2) you can remove container class Here:

```<code><div id="page" class="hfeed site grid-container container grid-parent">
</code>```

my suggestion is second option is right

ContentLicense: CC BY-SA 4.0

Body:
1) you can add this css add into theme or child theme style.css

.hfeed.site.grid-container.container.grid-parent{
width: 80%;
}

2) you can remove container class Here:

<div id="page" class="hfeed site grid-container container grid-parent">

my suggestion is second option is right


问:
bestway to animate a Label, button or textfield
I want a TextArea background alternate with its inverse when an alarm condition exists every second.
Other than alternating UIID's is there a better more pragmatic approach?</p>

答:
Something like this should work:</p>

```<code>while(animating) {
   ComponentAnimation ca = cmp.createStyleAnimation("Highlighted", 150);
   cmp.getAnimationManager().addAnimationAndBlock(ca);
   ca = cmp.createStyleAnimation("OriginalUIID", 150);
   cmp.getAnimationManager().addAnimationAndBlock(ca);
}
</code>```

Body:
Something like this should work:

while(animating) {
   ComponentAnimation ca = cmp.createStyleAnimation("Highlighted", 150);
   cmp.getAnimationManager().addAnimationAndBlock(ca);
   ca = cmp.createStyleAnimation("OriginalUIID", 150);
   cmp.getAnimationManager().addAnimationAndBlock(ca);
}


问:
Configure Windows Explorer Folder Options through Powershell
I'm looking for a way to configure a few options in Folder Option dialog of Windows Explorer through Powershell.

The options are:

Choose "Show hidden files, folders, and drives"

Uncheck "Hide extensions for known file types"

Uncheck "Hide protected operating system files (Recommended)"

答:
I believe these correspond to registry entries under reg key HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced.  You can use the Set-ItemProperty cmdlet to change their value e.g.:

```<code>$key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced'
Set-ItemProperty $key ShowSuperHidden 1
</code>```

There also seems to be a corresponding key for local machine (as opposed to the per user setting above): HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Folder.

Body:
I believe these correspond to registry entries under reg key HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced.  You can use the Set-ItemProperty cmdlet to change their value e.g.:

$key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced'
Set-ItemProperty $key ShowSuperHidden 1

There also seems to be a corresponding key for local machine (as opposed to the per user setting above): HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Folder.


问:
"Your connection is not private" on paypal payment
I am integrating the pay-pal payment gateway to my site.
And when i am clicking on "Login" to paypal account then it auto redirected to www.sandbox3.paypal.com and showing

```<code>Your connection is not private

Attackers might be trying to steal your information from www.sandbox3.paypal.com (for example, passwords, messages, or credit cards). NET::ERR_CERT_COMMON_NAME_INVALID
</code>```

So when i click on proceed to www.sandbox3.paypal.com then it show me to login and then payment process is halt. i am tired searching Please help me out

答:
try it without ssl i.e on http if it supports then the problem is at your ssl and make sure that you configured your ssl certificate properly and this problem commonly occurs if your https site is redirecting to another https site by some insecure content so use plugin named wp-force ssl so i could help you !
else make sure that you given production keys at keys option so that it could help you !
else make sure that you are using a valid certificate as if take a look over error provided by you  " NET::ERR_CERT_COMMON_NAME_INVALID "
itself says that you have some error with ssl , try solving that</p>

Body:
I am integrating the pay-pal payment gateway to my site.
And when i am clicking on "Login" to paypal account then it auto redirected to www.sandbox3.paypal.com and showing

Your connection is not private

Attackers might be trying to steal your information from www.sandbox3.paypal.com (for example, passwords, messages, or credit cards). NET::ERR_CERT_COMMON_NAME_INVALID

So when i click on proceed to www.sandbox3.paypal.com then it show me to login and then payment process is halt. i am tired searching Please help me out


问:
Removing divs without removing their content in plain Javascript
Could anyone help me on how I can remove div tags without removing their content in JavaScript?

This is my html from which I need to remove all div tags:

```<code><div id="id1" class="someclass">
  <p>some text
    <label> Test content </label>
  </p>
  <div id="id2" style="overfolw:scroll">
    <span>some text</span>
    <div id="level3">
      <label> Test content </label>
      <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a>
    </div>
  </div>
</div>
</code>```

Expected output would be like shown below.

```<code><p>some text
   <label> Test content </label>
</p>
<span>some text</span>
<label> Test content </label>
<a href=https://twitter.com/realDonaldTrump/status/882186896285282304 target=_blank rel=noopener>creepiness</a>
</code>```

答:
you can use unwrap function.

```<code> $('div').children().unwrap();
</code>```

If you want to do in plain javascript. You can get a list of all divs using document.getElementsByTagName("div"), but you will need to unwrap these divs in reverse order. This is a nodelist so reverse() will not work on it, so you can first use [].slice.call() on it which gives you an array and then you can reverse it. Then in the array unwrap each element.

you can do something like this:

var elements = [].slice.call(document.getElementsByTagName("div"), 0).reverse();
elements.forEach(function(el){
    el.outerHTML = el.innerHTML;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="id1" class="someclass">
  <p>some text
    <label> Test content </label>
  </p>
  <div id="id2" style="overfolw:scroll">
    <span>some text</span>
    <div id="level3">
      <label> Test content </label>
      creepiness
    </div>
  </div>
</div></code>```

Body:
Could anyone help me on how I can remove div tags without removing their content in JavaScript?

This is my html from which I need to remove all div tags:

some text
     Test content

    some text

       Test content
      creepiness

Expected output would be like shown below.

some text
    Test content

some text
 Test content
creepiness

Body:
you can use unwrap function.

 $('div').children().unwrap();

If you want to do in plain javascript. You can get a list of all divs using document.getElementsByTagName("div"), but you will need to unwrap these divs in reverse order. This is a nodelist so reverse() will not work on it, so you can first use [].slice.call() on it which gives you an array and then you can reverse it. Then in the array unwrap each element.

you can do something like this:

var elements = [].slice.call(document.getElementsByTagName("div"), 0).reverse();
elements.forEach(function(el){
    el.outerHTML = el.innerHTML;
});

<div id="id1" class="someclass">
  <p>some text
    <label> Test content </label>
  </p>
  <div id="id2" style="overfolw:scroll">
    <span>some text</span>
    <div id="level3">
      <label> Test content </label>
      <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a>
    </div>
  </div>
</div>


问:
Is it possible to extend (Override) git command?
Is it possible to override git command or run another git commands before calling its alias. Like so: git checkout . -> git stash && git stash apply && git checkout .. After accidental checkout i think about it

答:
You cannot override a git command through a git alias.

You can do a bash script called git, which you can put in your $PATH first.

Or you can define a function called git in your .bashrc.

That script would look for checkout as a first argument and would apply your sequence of commands.

See an example here.

```<code>function git {
  if [[ "$1" == "checkout" && "$@" != *"--help"* ]]; then
    shift 1
    command git mycheckout "$@"
  else
    command git "$@"
  fi
}
</code>```

In that case, you would implement your checkout in a script call git-mycheckout: Any script called git-xxx can be called by git as git xxx.

Body:
You cannot override a git command through a git alias.

You can do a bash script called git, which you can put in your $PATH first.

Or you can define a function called git in your .bashrc.

That script would look for checkout as a first argument and would apply your sequence of commands.

See an example here.

function git {
  if [[ "$1" == "checkout" && "$@" != *"--help"* ]]; then
    shift 1
    command git mycheckout "$@"
  else
    command git "$@"
  fi
}

In that case, you would implement your checkout in a script call git-mycheckout: Any script called git-xxx can be called by git as git xxx.


问:
Angular 2 Host in Apache Server issue?
I am trying to build angular 2 project and host in apache server ,  tutorial found from youtube

and the tutorial project result(according to this tutorial it will generate files in dist folder when we build using "ng build --prod") not working in php server it only showing loading message, and in console this errors

Failed to load resource: the server responded with a status of 404 (Not Found)
inline.33006aa0c7f9271418c2.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
main.42e5fd1daf31343420a1.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
polyfills.017b29d939c6479e18cc.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
vendor.9e7a0f6b9f9c8c0e49ba.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
main.42e5fd1daf31343420a1.bundle.js Failed to load resource: the server responded with a status of 404 (Not Found)
styles.d41d8cd98f00b204e980.bundle.css Failed to load resource: the server responded with a status of 404 (Not Found)
 How to solve this ?

答: after changing  <base href="/"> to <base href="./">  problem solved

Title: Angular 2 Host in Apache Server issue?


问:
Angular2/Websocket: how to return an observable for incoming websocket messages
I'm going to use Angular2 to receive websocket incoming messages and update a webpage based on those received messages. Right now, I'm using a dummy echo websocket service and will replace it.

From my understanding, the function which receive websocket messages has to return an observable that is subscribed by a handler who will update the webpage. But I can't figure out how to return an observable.

Code snippet is attached below. The MonitorService creates a websocket connection and return an observable containing the received messages.

```<code>@Injectable()
export class MonitorService {

    private actionUrl: string;
    private headers: Headers;
    private websocket: any;
    private receivedMsg: any;
    constructor(private http: Http, private configuration: AppConfiguration) {

        this.actionUrl = configuration.BaseUrl + 'monitor/';
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Accept', 'application/json');
    }

    public GetInstanceStatus = (): Observable<Response> => {
        this.websocket = new WebSocket("ws://echo.websocket.org/"); //dummy echo websocket service
        this.websocket.onopen =  (evt) => {
            this.websocket.send("Hello World");
        };

        this.websocket.onmessage = (evt) => {
            this.receivedMsg = evt;
        };

        return new Observable(this.receivedMsg).share();
    }

}
</code>```

Below is another component which subscribes to the observable returned from above and updates webpages correspondingly.

```<code>export class InstanceListComponent {
  private instanceStatus: boolean
  private instanceName: string
  private instanceIcon: string
  constructor(private monitor: MonitorService) {
    this.monitor.GetInstanceStatus().subscribe((result) => {
        this.setInstanceProperties(result);
    });
  }

  setInstanceProperties(res:any) {
    this.instanceName = res.Instance.toUpperCase();
    this.instanceStatus = res.Status;
    if (res.Status == true)
    {
      this.instanceIcon = "images/icon/healthy.svg#Layer_1";
    } else {
      this.instanceIcon = "images/icon/cancel.svg#cancel";
    }
  }
}
</code>```

Now, I'm running into this error in the browser console
TypeError: this._subscribe is not a function

答:
Get onMessage data from socket.

```<code>import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Rx';

@Injectable()

export class HpmaDashboardService {
private socketUrl: any = 'ws://127.0.0.0/util/test/dataserver/ws';
private websocket: any;

public GetAllInstanceStatus(objStr): Observable<any> {
      this.websocket = new WebSocket(this.socketUrl);
      this.websocket.onopen =  (evt) => {
        this.websocket.send(JSON.stringify(objStr));
      };
      return Observable.create(observer => {
        this.websocket.onmessage = (evt) => {
          observer.next(evt);
        };
      }).map(res => res.data).share();
 }

**Get only single mesage from socket.**

    public GetSingleInstanceStatus(objStr): Observable<any> {
      this.websocket = new WebSocket(this.socketUrl);
      this.websocket.onopen =  (evt) => {
        this.websocket.send(JSON.stringify(objStr));
      };
      return Observable.create(observer => {
        this.websocket.onmessage = (evt) => {
          observer.next(evt);
          this.websocket.close();
        };
      }).map(res => res.data).share();
  }

}
</code>```

Body:
I'm going to use Angular2 to receive websocket incoming messages and update a webpage based on those received messages. Right now, I'm using a dummy echo websocket service and will replace it.

From my understanding, the function which receive websocket messages has to return an observable that is subscribed by a handler who will update the webpage. But I can't figure out how to return an observable.

Code snippet is attached below. The MonitorService creates a websocket connection and return an observable containing the received messages.

@Injectable()
export class MonitorService {

    private actionUrl: string;
    private headers: Headers;
    private websocket: any;
    private receivedMsg: any;
    constructor(private http: Http, private configuration: AppConfiguration) {

        this.actionUrl = configuration.BaseUrl + 'monitor/';
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Accept', 'application/json');
    }

    public GetInstanceStatus = (): Observable<Response> => {
        this.websocket = new WebSocket("ws://echo.websocket.org/"); //dummy echo websocket service
        this.websocket.onopen =  (evt) => {
            this.websocket.send("Hello World");
        };

        this.websocket.onmessage = (evt) => {
            this.receivedMsg = evt;
        };

        return new Observable(this.receivedMsg).share();
    }

}

Below is another component which subscribes to the observable returned from above and updates webpages correspondingly.

export class InstanceListComponent {
  private instanceStatus: boolean
  private instanceName: string
  private instanceIcon: string
  constructor(private monitor: MonitorService) {
    this.monitor.GetInstanceStatus().subscribe((result) => {
        this.setInstanceProperties(result);
    });
  }

  setInstanceProperties(res:any) {
    this.instanceName = res.Instance.toUpperCase();
    this.instanceStatus = res.Status;
    if (res.Status == true)
    {
      this.instanceIcon = "images/icon/healthy.svg#Layer_1";
    } else {
      this.instanceIcon = "images/icon/cancel.svg#cancel";
    }
  }
}

Now, I'm running into this error in the browser console
TypeError: this._subscribe is not a function

Body:
Get onMessage data from socket.

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Rx';

@Injectable()

export class HpmaDashboardService {
private socketUrl: any = 'ws://127.0.0.0/util/test/dataserver/ws';
private websocket: any;

public GetAllInstanceStatus(objStr): Observable<any> {
      this.websocket = new WebSocket(this.socketUrl);
      this.websocket.onopen =  (evt) => {
        this.websocket.send(JSON.stringify(objStr));
      };
      return Observable.create(observer => {
        this.websocket.onmessage = (evt) => {
          observer.next(evt);
        };
      }).map(res => res.data).share();
 }

**Get only single mesage from socket.**

    public GetSingleInstanceStatus(objStr): Observable<any> {
      this.websocket = new WebSocket(this.socketUrl);
      this.websocket.onopen =  (evt) => {
        this.websocket.send(JSON.stringify(objStr));
      };
      return Observable.create(observer => {
        this.websocket.onmessage = (evt) => {
          observer.next(evt);
          this.websocket.close();
        };
      }).map(res => res.data).share();
  }

}


问:
How to test for situation where a specific library is missing in Python
I have some packages that have soft dependencies on other packages with a fall back to a default (simple) implementation.

The problem is that this is very hard to test for using unit tests. I could set up separate virtual environments, but that is hard to manage.

Is there a package or a way to achieve the following: have

```<code>import X
</code>```

work as usual, but

```<code>hide_package('X')
import X
</code>```

will raise an ImportError.

I keep having bugs creep into the fall-back part of my code because it is hard to test this.

答:
It looks a bit dirty, but you can override the __import__ builtin:

```<code>save_import = __builtin__.__import__
def my_import(name, *rest):
    if name=="hidden":
        raise ImportError, "Hidden package"
    return save_import(name, *rest)
__builtin__.__import__ = my_import
</code>```

BTW, have you read PEP 302? It seems that you can make a more robust mechanism with import hooks.

Body:
I have some packages that have soft dependencies on other packages with a fall back to a default (simple) implementation.

The problem is that this is very hard to test for using unit tests. I could set up separate virtual environments, but that is hard to manage.

Is there a package or a way to achieve the following: have

import X

work as usual, but

hide_package('X')
import X

will raise an ImportError.

I keep having bugs creep into the fall-back part of my code because it is hard to test this.

Body:
It looks a bit dirty, but you can override the __import__ builtin:

save_import = __builtin__.__import__
def my_import(name, *rest):
    if name=="hidden":
        raise ImportError, "Hidden package"
    return save_import(name, *rest)
__builtin__.__import__ = my_import

BTW, have you read PEP 302? It seems that you can make a more robust mechanism with import hooks.


问:
Matching text parsed from a PDF with PDFBox
This is more of a learning than a question. I was recently struggling with matching strings parsed out of a PDF using PDFBox. My solution might be helpful to others

A list of text was obtained from the PDF using PDFBox like this (Exceptions omitted for brevity):

```<code>List<String> lines = new ArrayList<String>();
PDDocument document = PDDocument.load(f);
PDFTextStripper pdfStripper = new PDFTextStripper();
String text = pdfStripper.getText(document);
String[] pageText = text.trim().split(pdfStripper.getLineSeparator());
for (String line : pageText) {
        lines.add(line);
}
</code>```

The List now contains all the lines from the file in order.

However, String.contains and String.equals fails on lines that are seemingly identical in the logs (ie: 'EMERA INCORPORATED'). In converting each characters into a Hex, it became clear the Space character was the issue:

```<code>Line (Parsed from PDF with PDF Box): EMERA INCORPORATED
45 4d 45 52 41 a0 49 4e 43 4f 52 50 4f 52 41 54 45 44

CompanyName (Set In Java): EMERA INCORPORATED
45 4d 45 52 41 20 49 4e 43 4f 52 50 4f 52 41 54 45 44
</code>```

Note the 'a0' in the PDFBox String where in Java there is the space ('20').

The solution was to use Regex to identify the line: EMERA\S+INCORPORATED. This gives better controller over the matching, so its not bad. But it was a bit annoying to figure this out as when reviewing the logs, the Strings being compared looked identical, yet both contains and equals returned false.

My conclusion, use RegEx to identify text patterns coming out of a PDF (obtained with PDFBox) and ensure to add '\S' to represent potential spaces. Maybe this post can save someone some pain. Also, perhaps someone more familiar with PDFBox could provide tips on using the API better if this is user error on my part.

答:
perhaps someone more familiar with PDFBox could provide tips on using the API better if this is user error on my part

It is not an error in PDFBox API usage. It is not even specific to PDFBox at all. It more is a matter of wrong expectations.

Different kinds of space characters

First of all, there are different kinds of space characters. There of course is the most often used Unicode Character 'SPACE' (U+0020) but there  also are others, in particular the Unicode Character 'NO-BREAK SPACE' (U+00A0).

Thus, if you don't know that only one particular space character is used in a given text, it is completely normal to use regular expressions with '\S' instead of ' '.

What does PDFBox extract?

In the case at hand using the non breaking space was not even used by choice of PDFBox. Instead, it was ingrained in the PDF.

When extracting text from a PDF,  PDFBox  (just like other PDF libraries) uses the information inside the PDF concerning which glyph represents which Unicode character. This information can be given by an Encoding entry or an ToUnicode entry of the respective font declaration in the PDF.

Only if there is a gap between two text chunks (a free space not created by drawing a space character but by moving the text insertion point without a text character), PDF text extractors add a space character of their respective choice, usually the regular space.

As PDFBox does use the regular space in the later case, the issue at hand is a situation of the first case, the PDF itself indicates that the space there is a non breaking one.

Body:
This is more of a learning than a question. I was recently struggling with matching strings parsed out of a PDF using PDFBox. My solution might be helpful to others

A list of text was obtained from the PDF using PDFBox like this (Exceptions omitted for brevity):

List<String> lines = new ArrayList<String>();
PDDocument document = PDDocument.load(f);
PDFTextStripper pdfStripper = new PDFTextStripper();
String text = pdfStripper.getText(document);
String[] pageText = text.trim().split(pdfStripper.getLineSeparator());
for (String line : pageText) {
        lines.add(line);
}

The List now contains all the lines from the file in order.

However, String.contains and String.equals fails on lines that are seemingly identical in the logs (ie: 'EMERA INCORPORATED'). In converting each characters into a Hex, it became clear the Space character was the issue:

Line (Parsed from PDF with PDF Box): EMERA INCORPORATED
45 4d 45 52 41 a0 49 4e 43 4f 52 50 4f 52 41 54 45 44

CompanyName (Set In Java): EMERA INCORPORATED
45 4d 45 52 41 20 49 4e 43 4f 52 50 4f 52 41 54 45 44

Note the 'a0' in the PDFBox String where in Java there is the space ('20').

The solution was to use Regex to identify the line: EMERA\S+INCORPORATED. This gives better controller over the matching, so its not bad. But it was a bit annoying to figure this out as when reviewing the logs, the Strings being compared looked identical, yet both contains and equals returned false.

My conclusion, use RegEx to identify text patterns coming out of a PDF (obtained with PDFBox) and ensure to add '\S' to represent potential spaces. Maybe this post can save someone some pain. Also, perhaps someone more familiar with PDFBox could provide tips on using the API better if this is user error on my part.


问:
I want to transpose a list of strings but I get TypeError
suppose I have this list of strings

```<code>li=['efh','opd','qst']
</code>```

I want to "transpose" them so they look like this

```<code>li=['eoq','fps','hdt']
</code>```

Here's the code I proposed but I get a typeError

```<code>previous=''

for i in range (len(li)):
    for j in range (len(li[0])):
        list2[j][i]=previous+list[i][j]
        previous=list2[j][i]
    previous=''
</code>```

答:
Here you can go through this.</p>

```<code>li=['efh','opd','qst']
new_list = []
for i in range(len(li[0])):
    # maiking a list with its index element and convert it into string.
    new_string = ''.join([ls[i] for ls in li])
    # appending the new_string int new_list
    new_list.append(new_string)
print(new_list)

# output : ['eoq', 'fps', 'hdt']
</code>```

Body:
suppose I have this list of strings

li=['efh','opd','qst']

I want to "transpose" them so they look like this

li=['eoq','fps','hdt']

Here's the code I proposed but I get a typeError

previous=''

for i in range (len(li)):
    for j in range (len(li[0])):
        list2[j][i]=previous+list[i][j]
        previous=list2[j][i]
    previous=''

Body:
Here you can go through this.

li=['efh','opd','qst']
new_list = []
for i in range(len(li[0])):
    # maiking a list with its index element and convert it into string.
    new_string = ''.join([ls[i] for ls in li])
    # appending the new_string int new_list
    new_list.append(new_string)
print(new_list)

# output : ['eoq', 'fps', 'hdt']


问:
How to convert substrb in Oracle to Postgresql
Oracle: select substrb('よろしくお願いいたします',2,3) from dual;
Result: ろ

How to convert to Postgresql?

答:
With byte, in postgresql you can change it to bytea then extract the bytes:

```<code>select convert_from(substring('よろしくお願いいたします'::bytea,4,3),'UTF8');
</code>```

The Substring(bytea [from int] [for int] ) will get the sub-bytea from input. Then you can convert it into UTF-8.
Reference more: https://www.postgresql.org/docs/current/static/functions-binarystring.html

You can try this for extract with character:

```<code>select substring('よろしくお願いいたします',2,1)
</code>```

Get String at location '2' for '1' character(s)

Reference document: https://www.postgresql.org/docs/current/static/functions-string.html

Body:
With byte, in postgresql you can change it to bytea then extract the bytes:

select convert_from(substring('よろしくお願いいたします'::bytea,4,3),'UTF8');

The Substring(bytea [from int] [for int] ) will get the sub-bytea from input. Then you can convert it into UTF-8.
Reference more: https://www.postgresql.org/docs/current/static/functions-binarystring.html

You can try this for extract with character:

select substring('よろしくお願いいたします',2,1)

Get String at location '2' for '1' character(s)

Reference document: https://www.postgresql.org/docs/current/static/functions-string.html


问:
Use @Parameters in TestNg on class level
The @Parameters annotation implementation from org.testng.annotations looks like this:

```<code>@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE})
public @interface Parameters {
    String[] value() default {};
}
</code>```

So, it should allow me to use it on a ElementType.TYPE => it could also be used on a class.

When I use it on a method, I simply take the value using:

```<code>@Parameters("value")
public void m(String value) {
    ...
}
</code>```

But if I use

```<code>@Parameters("value")
public class A {
    ...
}
</code>```

how can I get the value inside the class?

答:
If you want to use it for initialising class variables you can put in on constructor of class and use it.

ElementType.TYPE also means applicable to interfaces and enums - may be that one is specified if you want to extend the annotation.

Body:
The @Parameters annotation implementation from org.testng.annotations looks like this:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE})
public @interface Parameters {
    String[] value() default {};
}

So, it should allow me to use it on a ElementType.TYPE => it could also be used on a class.

When I use it on a method, I simply take the value using:

@Parameters("value")
public void m(String value) {
    ...
}

But if I use

@Parameters("value")
public class A {
    ...
}

how can I get the value inside the class?


问:
how to make a server listen to a path in nodejs
Can anyone help me figure out how to make a server in nodejs to listen to a specific path in localhost? If I replace the following path by 'port: 3000' then the localhost:3000 works properly but I just cannot find out how to carry out with path.</p>

```<code>var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen({path:__dirname + '/example.html'});
app.get('/',function(req, res){
res.sendFile(__dirname + '/example.html');
});
</code>```

答:
var express = require("express"),
    app = express();
 var fs = require('fs');
var port = process.env.PORT || 8000;

app.use(express.static(__dirname + '/public'));
app.get("/login", function (request, response) {
  var request= request.query.body;
    });
app.listen(port);```

Body:
Can anyone help me figure out how to make a server in nodejs to listen to a specific path in localhost? If I replace the following path by 'port: 3000' then the localhost:3000 works properly but I just cannot find out how to carry out with path.

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen({path:__dirname + '/example.html'});
app.get('/',function(req, res){
res.sendFile(__dirname + '/example.html');
});


问:
How to group all values by semicolon separated in SQL query
Please help how to achieve data as per shown in attached image

Highlighted rows actually group on Item Number field

Thanks in advance

答:
Following should work:</p>

```<code>SELECT distinct ItemNumber,SUBSTRING(
(SELECT ';' + TotalItem+' x '+ItemName
FROM YourTable
where ItemNumber=c.ItemNumber
ORDER BY ItemNumber
FOR XML PATH('')),2,200000 ) AS NewDescription from YourTable c
GO
</code>```

Body:
Following should work:

SELECT distinct ItemNumber,SUBSTRING(
(SELECT ';' + TotalItem+' x '+ItemName
FROM YourTable
where ItemNumber=c.ItemNumber
ORDER BY ItemNumber
FOR XML PATH('')),2,200000 ) AS NewDescription from YourTable c
GO


问:
How does react-redux know what store fragment to pass?
I'm working on my first react-redux app. And I'm wondering how does a reducer method know which store fragment should be passed for a given action.

Basically my approach is based on two screens: a list and a form. When I choose an item from a table and click edit button, then ENTERPRISE_SELECTED action is dispatched. And the form renders that selected item.

This is my store fragment so far:

```<code>// store skeleton draft
const storeReference = {
  enterprises: {
    filters: [
      { country: null },
      { type: null },
    ],
    list: [{}, {}, {}],
    selected: {} /* object or int. Not yet decided that. */
  }
}
</code>```

Having two different pages (list and form) I have two different containers:

List defines this:

```<code>const mapStateToProps = (store, ownProps) => {
    return {
        enterprises: store.enterprises.list
    }
}
</code>```

Form defines this:

```<code>const mapStateToProps = (store, ownProps) => {
    return {
        data: store.enterprises.selected
    }
}
</code>```

My reducers are basically in a single file. But ENTERPRISE_LIST_SUCCESS receives my root element (so I have to access "list" by myself) while SAVE_ENTERPRISE receives only the "selected" fragment of my store. Why is that?

```<code>function enterprises (state = {}, action) {

    switch (action.type) {
        case 'ENTERPRISE_LIST_SUCCESS':
            return Object.assign({}, state, {
                list: action.payload.list
            });
        case 'ENTERPRISE_SELECTED':
            return Object.assign({}, state, {
                selected: action.payload.data
            });
        case 'ENTERPRISE_UNSELECTED':
            return Object.assign({}, state, {
                selected: {}
            });
        case 'ADD_ENTERPRISE':
            return Object.assign({}, state, {
                list: state.list.concat([action.payload.data])
            });
        case 'SAVE_ENTERPRISE':
            console.log(state); // Here I don't have list, just selected
            // replace item in list
            const updatedList = state.list.map(item => {

                if(item.id === action.data.id){
                    return { ...item, ...action.payload.data }
                }
                return item
            })

            return Object.assign({}, state, {
                list: updatedList
            });
        case 'REMOVE_ENTERPRISE':
            return Object.assign({}, state, {
                list: state.list.filter( (item) => { return item.id !== action.payload.id } )
            });
        default:
            return state
    }
}

export default enterprises
</code>```

UPDATED the reducer with the fix that @DonovanM pointed out.

Notice the problem persists: when I save the form, my SAVE_ENTERPRISE reducer just get { selected: {...} } when I'd expect this:

```<code>{
   list: [...],
   selected: {...}
}
</code>```

That's why I'm asking: shouldn't all the reducers receive the same state? Why this one is missing a chunk? But I'm realizing that somewhere in the middle when I go from list to form that chunk is being erased. Not sure why yet. But that kinda solves the mystery. It's not that I'm receiving something different, I'm just loosing something on the way.

答:
In the reducer you can define on which property to workout your action.
Look at example from redux documentation.
Below you can see that action SET_VISIBILITY_FILTER works on state when instead action TOGGLE_TODO works on a property of state.todos.

```<code>function todoApp(state = initialState, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      // working on `state`
      return Object.assign({}, state, {
        visibilityFilter: action.filter
      })
    case TOGGLE_TODO:
      // working on `todos` on `state`
      return Object.assign({}, state, {
        todos: state.todos.map((todo, index) => {
          if (index === action.index) {
            return Object.assign({}, todo, {
              completed: !todo.completed
            })
          }
          return todo
        })
      })
    default:
      return state
  }
}
</code>```

Body:
I'm working on my first react-redux app. And I'm wondering how does a reducer method know which store fragment should be passed for a given action.

Basically my approach is based on two screens: a list and a form. When I choose an item from a table and click edit button, then ENTERPRISE_SELECTED action is dispatched. And the form renders that selected item.

This is my store fragment so far:

// store skeleton draft
const storeReference = {
  enterprises: {
    filters: [
      { country: null },
      { type: null },
    ],
    list: [{}, {}, {}],
    selected: {} /* object or int. Not yet decided that. */
  }
}

Having two different pages (list and form) I have two different containers:

List defines this:

const mapStateToProps = (store, ownProps) => {
    return {
        enterprises: store.enterprises.list
    }
}

Form defines this:

const mapStateToProps = (store, ownProps) => {
    return {
        data: store.enterprises.selected
    }
}

My reducers are basically in a single file. But ENTERPRISE_LIST_SUCCESS receives my root element (so I have to access "list" by myself) while SAVE_ENTERPRISE receives only the "selected" fragment of my store. Why is that?

function enterprises (state = {}, action) {

    switch (action.type) {
        case 'ENTERPRISE_LIST_SUCCESS':
            return Object.assign({}, state, {
                list: action.payload.list
            });
        case 'ENTERPRISE_SELECTED':
            return Object.assign({}, state, {
                selected: action.payload.data
            });
        case 'ENTERPRISE_UNSELECTED':
            return Object.assign({}, state, {
                selected: {}
            });
        case 'ADD_ENTERPRISE':
            return Object.assign({}, state, {
                list: state.list.concat([action.payload.data])
            });
        case 'SAVE_ENTERPRISE':
            console.log(state); // Here I don't have list, just selected
            // replace item in list
            const updatedList = state.list.map(item => {

                if(item.id === action.data.id){
                    return { ...item, ...action.payload.data }
                }
                return item
            })

            return Object.assign({}, state, {
                list: updatedList
            });
        case 'REMOVE_ENTERPRISE':
            return Object.assign({}, state, {
                list: state.list.filter( (item) => { return item.id !== action.payload.id } )
            });
        default:
            return state
    }
}

export default enterprises

UPDATED the reducer with the fix that @DonovanM pointed out.

Notice the problem persists: when I save the form, my SAVE_ENTERPRISE reducer just get { selected: {...} } when I'd expect this:

{
   list: [...],
   selected: {...}
}

That's why I'm asking: shouldn't all the reducers receive the same state? Why this one is missing a chunk? But I'm realizing that somewhere in the middle when I go from list to form that chunk is being erased. Not sure why yet. But that kinda solves the mystery. It's not that I'm receiving something different, I'm just loosing something on the way.

Body:
In the reducer you can define on which property to workout your action.
Look at example from redux documentation.
Below you can see that action SET_VISIBILITY_FILTER works on state when instead action TOGGLE_TODO works on a property of state.todos.

function todoApp(state = initialState, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      // working on `state`
      return Object.assign({}, state, {
        visibilityFilter: action.filter
      })
    case TOGGLE_TODO:
      // working on `todos` on `state`
      return Object.assign({}, state, {
        todos: state.todos.map((todo, index) => {
          if (index === action.index) {
            return Object.assign({}, todo, {
              completed: !todo.completed
            })
          }
          return todo
        })
      })
    default:
      return state
  }
}