问:
Why is opencv dnn slower if I use Halide?
I am testing the performance of some samples in the opencv source tree depending on if halide is used or not.

Surprisingly, the performance is worse if halide is used for the computation:

squeezenet_halide: ~24ms with halide and ~16ms without halide.

resnet_ssd_face: ~84ms with halide and ~36ms without halide.

I have compiled halide and opencv following the instructions in this tutorial. The opencv code was downloaded from the master branch of the opencv git repository.

I have tested the performance using the sample files 'resnet_ssd_face.cpp' and 'squeezenet_halide.cpp'.  In both cases I include one of these code lines just before call 'forward', to activate or deactivate halide:

```<code>net.setPreferableBackend(DNN_BACKEND_HALIDE);  // use Halide

net.setPreferableBackend(DNN_BACKEND_DEFAULT);   // NOT use Halide
</code>```

The time is measured using this code just after the call to 'forward' function:

```<code>std::vector<double> layersTimings;
double freq = cv::getTickFrequency() / 1000;
double time = net.getPerfProfile(layersTimings) / freq;
std::cout << "Time: " << time << " ms" << std::endl;
</code>```

Is there anything missed in the tutorial? Should Halide be compiled with different parameters?

My setup is:

```<code>OS: Linux (Ubuntu 16.04)
CPU: Intel(R) Core(TM) i5-4570 CPU @ 3.20GHz
GPU: nVidia GeForce GT 730 (Driver Version: 384.90)
Cuda: CUDA Version 9.0.176
</code>```

答:
Taking into account the comment by Dmitry Kurtaev and looking the wiki in the OpenCV GitHub account, I found a page where a benchmark comparing different approaches is included (I missed the links in the tutorial).

Also, there is a merge request where a similar benchmark is included.

In both of them, the time measurement shows that the performance using Halide is worse than with the original c++ approach.

I can assume that the Halide integration is in an early stage. Moreover, as Zalman Stern comments, the Halide scheduling is a work in progress and the original optimizations in dnn module of opencv could be more accurate than the included scheduling for Halide.

I hope this measures could change in future versions of OpenCV, but for now, this is the performance.

Body:
I am testing the performance of some samples in the opencv source tree depending on if halide is used or not.

Surprisingly, the performance is worse if halide is used for the computation:

squeezenet_halide: ~24ms with halide and ~16ms without halide.

resnet_ssd_face: ~84ms with halide and ~36ms without halide.

I have compiled halide and opencv following the instructions in this tutorial. The opencv code was downloaded from the master branch of the opencv git repository.

I have tested the performance using the sample files 'resnet_ssd_face.cpp' and 'squeezenet_halide.cpp'.  In both cases I include one of these code lines just before call 'forward', to activate or deactivate halide:

net.setPreferableBackend(DNN_BACKEND_HALIDE);  // use Halide

net.setPreferableBackend(DNN_BACKEND_DEFAULT);   // NOT use Halide

The time is measured using this code just after the call to 'forward' function:

std::vector<double> layersTimings;
double freq = cv::getTickFrequency() / 1000;
double time = net.getPerfProfile(layersTimings) / freq;
std::cout << "Time: " << time << " ms" << std::endl;

Is there anything missed in the tutorial? Should Halide be compiled with different parameters?

My setup is:

OS: Linux (Ubuntu 16.04)
CPU: Intel(R) Core(TM) i5-4570 CPU @ 3.20GHz
GPU: nVidia GeForce GT 730 (Driver Version: 384.90)
Cuda: CUDA Version 9.0.176


来源: stackexchange

问:
How to test if BufferedImage using ImageIO picks up a 'null'
I am trying to set my program (java using netbeans) to do one thing if it finds the image its looking for, and another thing if it doesn't...

this is what I have got so far however it never completes the else statement. I believe this is because "image" is not technically null, as it still has corresponds to the filename entered, however I am not sure how to set java to do something based on if the filename is not found within the directory.

```<code>public void displayImage(String strfilename, JLabel JLlabel) {

    try {
        JLabel label = JLlabel;

        String FileName = strfilename;
        BufferedImage image = ImageIO.read(new File(FileName + ".jpg"));
        if(image!=null){
        ImageIcon icon = new ImageIcon(image);

        label.setIcon(icon);}
        else{
        BufferedImage image2 = ImageIO.read(new File("NOIMAGE.jpg"));
        ImageIcon icon2 = new ImageIcon(image2);
        label.setIcon(icon2);
        }
    } catch (IOException ioe) {
    }
}
</code>```

If anyone could help me with this I would be very grateful

答:
you can check the file if exist before you process this method also i removed some unnecessary code.</p>

```<code>public void displayImage(String strfilename, JLabel JLlabel)  {
// declare only one reference you don't need two references

BufferedImage image=null;

if(!isImageExist(strfilename)){
// assign the NOIMAGE if image not found
 image = ImageIO.read(new File("NOIMAGE.jpg"));
} else {

    try {
        // assign the image if found
        image = ImageIO.read(new File(strfilename + ".jpg"));

    } catch (IOException ioe) {
      ioe.printStackTrace();
   }
}
     ImageIcon icon = new ImageIcon(image);
    //setting the image once instead of repeating the code in if and else blocks also you don't need to add another reference to JLlabel because you are already got it from a parameter
     JLlabel.setIcon(icon);
}
private boolean isImageExist(String imageName) {
return new File(imageName.jpg).exist();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set my program (java using netbeans) to do one thing if it finds the image its looking for, and another thing if it doesn't...

this is what I have got so far however it never completes the else statement. I believe this is because "image" is not technically null, as it still has corresponds to the filename entered, however I am not sure how to set java to do something based on if the filename is not found within the directory.

public void displayImage(String strfilename, JLabel JLlabel) {

    try {
        JLabel label = JLlabel;

        String FileName = strfilename;
        BufferedImage image = ImageIO.read(new File(FileName + ".jpg"));
        if(image!=null){
        ImageIcon icon = new ImageIcon(image);

        label.setIcon(icon);}
        else{
        BufferedImage image2 = ImageIO.read(new File("NOIMAGE.jpg"));
        ImageIcon icon2 = new ImageIcon(image2);
        label.setIcon(icon2);
        }
    } catch (IOException ioe) {
    }
}

If anyone could help me with this I would be very grateful

Body:
you can check the file if exist before you process this method also i removed some unnecessary code.

public void displayImage(String strfilename, JLabel JLlabel)  {
// declare only one reference you don't need two references

BufferedImage image=null;

if(!isImageExist(strfilename)){
// assign the NOIMAGE if image not found
 image = ImageIO.read(new File("NOIMAGE.jpg"));
} else {

    try {
        // assign the image if found
        image = ImageIO.read(new File(strfilename + ".jpg"));

    } catch (IOException ioe) {
      ioe.printStackTrace();
   }
}
     ImageIcon icon = new ImageIcon(image);
    //setting the image once instead of repeating the code in if and else blocks also you don't need to add another reference to JLlabel because you are already got it from a parameter
     JLlabel.setIcon(icon);
}
private boolean isImageExist(String imageName) {
return new File(imageName.jpg).exist();
}


问:
how to test method that prints to console in golang?
I have next struct.

```<code>package logger

import "fmt"

type IPrinter interface {
    Print(value string)
}

type ConsolePrinter struct{}

func (cp *ConsolePrinter) Print(value string) {
    fmt.Printf("this is value: %s", value)
}
</code>```

Test coverage says I need to test that ConsolePrinter Print method.

How can I cover this method?

Thanks.

答:
I would recommend to create new instance of the logger, which would behave exactly as fmt methods for printing data to console. Also, you can configure it with additional features like showing the filename, date and etc. Such custom logger can be passed as a parameter to your service/instance factory method. That would make it really easy to mock and test.

Your code

```<code>type Logs interface {
    Println(v ...interface{})
}

type InstanceToTest struct {
    log Logs
}

func InstanceToTestFactory(logger Logs) *InstanceToTest {
    return &InstanceToTest{logger}
}

func (i *InstanceToTest) SomeMethod(a string) {
    i.log.Println(a)
}
</code>```

Create a mock for logger

```<code>type LoggerMock struct {
    CalledPrintln []interface{}
}

func (l *LoggerMock) Println(v ...interface{}) {
    l.CalledPrintln = append(CalledPrintln, v)
}
</code>```

And in your test

```<code>func TestInstanceToTestSomeMethod(t *testing.T) {
    l := &LoggerMock{}
    i := InstanceToTestFactory(l)
    a := "Test"

    i.SomeMethod(a)

    if len(l.CalledPrintln) == 0 || l.CalledPrintln[0] != a {
        t.Error("Not called")
    }
}
</code>```

Body:
I have next struct.

package logger

import "fmt"

type IPrinter interface {
    Print(value string)
}

type ConsolePrinter struct{}

func (cp *ConsolePrinter) Print(value string) {
    fmt.Printf("this is value: %s", value)
}

Test coverage says I need to test that ConsolePrinter Print method.

How can I cover this method?

Thanks.

Body:
I would recommend to create new instance of the logger, which would behave exactly as fmt methods for printing data to console. Also, you can configure it with additional features like showing the filename, date and etc. Such custom logger can be passed as a parameter to your service/instance factory method. That would make it really easy to mock and test.

Your code

type Logs interface {
    Println(v ...interface{})
}

type InstanceToTest struct {
    log Logs
}

func InstanceToTestFactory(logger Logs) *InstanceToTest {
    return &InstanceToTest{logger}
}

func (i *InstanceToTest) SomeMethod(a string) {
    i.log.Println(a)
}

Create a mock for logger

type LoggerMock struct {
    CalledPrintln []interface{}
}

func (l *LoggerMock) Println(v ...interface{}) {
    l.CalledPrintln = append(CalledPrintln, v)
}

And in your test

func TestInstanceToTestSomeMethod(t *testing.T) {
    l := &LoggerMock{}
    i := InstanceToTestFactory(l)
    a := "Test"

    i.SomeMethod(a)

    if len(l.CalledPrintln) == 0 || l.CalledPrintln[0] != a {
        t.Error("Not called")
    }
}


问:
Remove Rows From Data Frame where a Row matches a String
I do I remove all rows in a dataframe where a certain row meets a string match criteria?

For example:

```<code>A,B,C
4,3,Foo
2,3,Bar
7,5,Zap
</code>```

How would I return a dataframe that excludes all rows where C = Foo:

```<code>A,B,C
2,3,Bar
7,5,Zap
</code>```

答:
You can use the dplyr package to easily remove those particular rows.

```<code>library(dplyr)
df <- filter(df, C != "Foo")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I do I remove all rows in a dataframe where a certain row meets a string match criteria?

For example:

A,B,C
4,3,Foo
2,3,Bar
7,5,Zap

How would I return a dataframe that excludes all rows where C = Foo:

A,B,C
2,3,Bar
7,5,Zap

Body:
You can use the dplyr package to easily remove those particular rows.

library(dplyr)
df <- filter(df, C != "Foo")


问:
How to intercept all http requests including form submits
I would like to intercept all http requests going out from my web page and add a parameter to the request body. My page includes forms - I also want to capture form submits. I have tried using Jquery ajaxSend and Javascript's setRequestHeader but both did not work for me. How do I achieve this?

Thanks

答:
try this code :</p>

```<code>(function(send) {

XMLHttpRequest.prototype.send = function(data) {

    var _valuToAdd = $("input[name='valuToAdd']").val();
    this.setRequestHeader('valueName', _valuToAdd);
    send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
</code>```

Body:
try this code :

(function(send) {

XMLHttpRequest.prototype.send = function(data) {

    var _valuToAdd = $("input[name='valuToAdd']").val();
    this.setRequestHeader('valueName', _valuToAdd);
    send.call(this, data);
};
})(XMLHttpRequest.prototype.send);


问:
Error: module not found in Jupyter Notebook (sklearn)
I have an issue importing scikit-learn in my Jupyter notebooks, and I am at a loss as to why this is not working. I do not recall having this issue before with other packages. I have seen several threads with people having similar problems with this specific module, but none of the proposed checks have solved my problem, nor revealed to me what might be wrong. I have tried to add as much info as possible below, to try and figure out why this refuses to work.

I use anaconda to manage my packages, and scikit-learn was installed as follows:

```<code>source activate python3
conda install scikit-learn
Fetching package metadata .............
Solving package specifications: .

# All requested packages already installed.
# packages in environment at /Users/overaa/anaconda/envs/python3:
#
scikit-learn              0.19.1           py36hffbff8c_0
</code>```

Now, if I start a python session directly from the command line, import sklearn works as intended and the module is imported correctly. Doing the same in Jupyter results in

ModuleNotFoundError: No module named 'sklearn'

I have checked a number of things. First, making sure that my jupyter and jupyter-notebook point to the correct environment

```<code>which jupyter
/Users/user_name/anaconda/envs/python3/bin/jupyter
which jupyter-notebook
/Users/user_name/anaconda/envs/python3/bin/jupyter-notebook
</code>```

So the notebook checks out.

Then from a command-line python session (in the same environment as where I launch my notebook):

```<code>>>> import sklearn
>>> sklearn.__file__
'/Users/user_name/anaconda/envs/python3/lib/python3.6/site_packages/sklearn/__init__.py'
</code>```

So scikit-learn is also installed in the right environment.

Now comparing that I am running the same version;

From command line:

```<code>>>> print(sys.version)
3.6.1 |Continuum Analytics, Inc.| (default, May 11 2017, 13:04:09)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
</code>```

From Jupyter notebook:

```<code>print(sys.version)
3.6.1 |Continuum Analytics, Inc.| (default, May 11 2017, 13:04:09
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
</code>```

Comparing the packages path.

From command line:

```<code>import site
print(site.getsitepackages())
['/Users/user_name/anaconda/envs/python3/lib/python3.6/site-packages']
</code>```

From Jupyter notebook:

```<code>import site
print(site.getsitepackages())
['/Users/user_name/anaconda/envs/python3/lib/python3.6/site-packages']
</code>```

Similarly for my sys.path

command line:

```<code>>>> print(sys.path)
['', '/Users/user_name/anaconda/envs/python3/lib/python36.zip',
'/Users/user_name/anaconda/envs/python3/lib/python3.6',
'/Users/user_name/anaconda/envs/python3/lib/python3.6/lib-dynload',
'/Users/user_name/anaconda/envs/python3/lib/python3.6/site-packages',
'/Users/user_name/anaconda/envs/python3/lib/python3.6/site_packages/setuptools-27.2.0-py3.6.egg']
</code>```

Jupyter:

```<code>print(sys.path)
['', '/Users/user_name/anaconda/envs/python36/lib/python36.zip',
'/Users/user_name/anaconda/envs/python36/lib/python3.6',
'/Users/user_name/anaconda/envs/python36/lib/python3.6/lib-dynload',
'/Users/user_name/anaconda/envs/python36/lib/python3.6/site-packages',
'/Users/user_name/anaconda/envs/python36/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg',
'/Users/user_name/anaconda/envs/python36/lib/python3.6/site-packages/IPython/extensions',
'/Users/user_name/.ipython']
</code>```

So everything is the same, except that the directory containing the setuptools differ between the command-line version and the Jupyter version. I also noticed that scikit-learn seems to be installed in the site_packages subdir, rather than in the site-packages subdirectory, which is where Jupyter appear to be looking for modules. So I tried two things. First, adding the path to my JUPYTER_PATH in my .bash_profile before running my notebook.

```<code>export JUPYTER_PATH="/Users/user_name/anaconda/envs/python36/lib/python3.6/site-packages:$JUPYTER_PATH"
</code>```

I also tried to add it to my sys.path directly in the jupyter notebook, prior to trying to import scikit-learn

```<code>sys.path.append("/Users/user_name/anaconda/envs/python3/lib/python3.6/site_packages")
</code>```

Both to no avail, sklearn still refuses to import in my notebook.

Any ideas as to why scikit-learn is not getting imported into my Jupyter Notebook would be highly appreciated. Are there more things I can check? And how do I get this to work?

I have tried activating/deactivating my environment, restart the kernels etc. also without success.

EDIT: I have no problems importing other packages, like numpy or scipy

答:
Make sure you have both numpy and scipy installed - scikit-learn depends on them but does not install them for you.

Also, after installing them, restart your notebook server.

Body:
I have an issue importing scikit-learn in my Jupyter notebooks, and I am at a loss as to why this is not working. I do not recall having this issue before with other packages. I have seen several threads with people having similar problems with this specific module, but none of the proposed checks have solved my problem, nor revealed to me what might be wrong. I have tried to add as much info as possible below, to try and figure out why this refuses to work.

I use anaconda to manage my packages, and scikit-learn was installed as follows:

source activate python3
conda install scikit-learn
Fetching package metadata .............
Solving package specifications: .

# All requested packages already installed.
# packages in environment at /Users/overaa/anaconda/envs/python3:
#
scikit-learn              0.19.1           py36hffbff8c_0

Now, if I start a python session directly from the command line, import sklearn works as intended and the module is imported correctly. Doing the same in Jupyter results in

ModuleNotFoundError: No module named 'sklearn'

I have checked a number of things. First, making sure that my jupyter and jupyter-notebook point to the correct environment

which jupyter
/Users/user_name/anaconda/envs/python3/bin/jupyter
which jupyter-notebook
/Users/user_name/anaconda/envs/python3/bin/jupyter-notebook

So the notebook checks out.

Then from a command-line python session (in the same environment as where I launch my notebook):

>>> import sklearn
>>> sklearn.__file__
'/Users/user_name/anaconda/envs/python3/lib/python3.6/site_packages/sklearn/__init__.py'

So scikit-learn is also installed in the right environment.

Now comparing that I am running the same version;

From command line:

>>> print(sys.version)
3.6.1 |Continuum Analytics, Inc.| (default, May 11 2017, 13:04:09)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]

From Jupyter notebook:

print(sys.version)
3.6.1 |Continuum Analytics, Inc.| (default, May 11 2017, 13:04:09
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]

Comparing the packages path.

From command line:

import site
print(site.getsitepackages())
['/Users/user_name/anaconda/envs/python3/lib/python3.6/site-packages']

From Jupyter notebook:

import site
print(site.getsitepackages())
['/Users/user_name/anaconda/envs/python3/lib/python3.6/site-packages']

Similarly for my sys.path

command line:

>>> print(sys.path)
['', '/Users/user_name/anaconda/envs/python3/lib/python36.zip',
'/Users/user_name/anaconda/envs/python3/lib/python3.6',
'/Users/user_name/anaconda/envs/python3/lib/python3.6/lib-dynload',
'/Users/user_name/anaconda/envs/python3/lib/python3.6/site-packages',
'/Users/user_name/anaconda/envs/python3/lib/python3.6/site_packages/setuptools-27.2.0-py3.6.egg']

Jupyter:

print(sys.path)
['', '/Users/user_name/anaconda/envs/python36/lib/python36.zip',
'/Users/user_name/anaconda/envs/python36/lib/python3.6',
'/Users/user_name/anaconda/envs/python36/lib/python3.6/lib-dynload',
'/Users/user_name/anaconda/envs/python36/lib/python3.6/site-packages',
'/Users/user_name/anaconda/envs/python36/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg',
'/Users/user_name/anaconda/envs/python36/lib/python3.6/site-packages/IPython/extensions',
'/Users/user_name/.ipython']

So everything is the same, except that the directory containing the setuptools differ between the command-line version and the Jupyter version. I also noticed that scikit-learn seems to be installed in the site_packages subdir, rather than in the site-packages subdirectory, which is where Jupyter appear to be looking for modules. So I tried two things. First, adding the path to my JUPYTER_PATH in my .bash_profile before running my notebook.

export JUPYTER_PATH="/Users/user_name/anaconda/envs/python36/lib/python3.6/site-packages:$JUPYTER_PATH"

I also tried to add it to my sys.path directly in the jupyter notebook, prior to trying to import scikit-learn

sys.path.append("/Users/user_name/anaconda/envs/python3/lib/python3.6/site_packages")

Both to no avail, sklearn still refuses to import in my notebook.

Any ideas as to why scikit-learn is not getting imported into my Jupyter Notebook would be highly appreciated. Are there more things I can check? And how do I get this to work?

I have tried activating/deactivating my environment, restart the kernels etc. also without success.

EDIT: I have no problems importing other packages, like numpy or scipy


问:
Can I draw outside the bounds of an Android Canvas
I'm porting an app written in a graphics environment that allows drawing to happen outside the bounds of the clipping rectangle. Any way to do this in Android?</p>

答:
If you want to draw text out of bounds in TextView, you should be doing this instead:

```<code><TextView
    ...
    android:shadowColor="#01000000"
    android:shadowDx="100" // out of right bound
    android:shadowDy="0"
    android:shadowRadius="1"
.../>
</code>```

It's not working to use clipRect() like @numan's answer because TextView clip it's own rect in onDraw():

```<code>if (mShadowRadius != 0) {
    clipLeft += Math.min(0, mShadowDx - mShadowRadius);
    clipRight += Math.max(0, mShadowDx + mShadowRadius);

    clipTop += Math.min(0, mShadowDy - mShadowRadius);
    clipBottom += Math.max(0, mShadowDy + mShadowRadius);
}

canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);
</code>```

Last but not least, Don't forget to set android:clipChildren="false" and android:clipToPadding="false" in your parent ViewGroup

ContentLicense: CC BY-SA 2.5

Body:
If you want to draw text out of bounds in TextView, you should be doing this instead:

<TextView
    ...
    android:shadowColor="#01000000"
    android:shadowDx="100" // out of right bound
    android:shadowDy="0"
    android:shadowRadius="1"
.../>

It's not working to use clipRect() like @numan's answer because TextView clip it's own rect in onDraw():

if (mShadowRadius != 0) {
    clipLeft += Math.min(0, mShadowDx - mShadowRadius);
    clipRight += Math.max(0, mShadowDx + mShadowRadius);

    clipTop += Math.min(0, mShadowDy - mShadowRadius);
    clipBottom += Math.max(0, mShadowDy + mShadowRadius);
}

canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);

Last but not least, Don't forget to set android:clipChildren="false" and android:clipToPadding="false" in your parent ViewGroup


问:
Append mode requires a document without errors, even if recovery is possible
The PDF which I signed with append mode is exported from Office Word 2016.

Here is my file : word.pdf

And I got this error message:

com.itextpdf.kernel.PdfException: Append mode requires a document without errors, even if recovery is possible.

I am using iText7 7.0.4 .

答:
The document you are trying to change in append mode is broken. Most likely, the byte offsets as defined in the cross-reference table don't correspond with the actual byte positions of the PDF objects.

In your case, I see something strange at the end of the file:

```<code>xref
0 26
0000000010 65535 f
0000000017 00000 n
0000000166 00000 n
0000000222 00000 n
0000000492 00000 n
0000000755 00000 n
0000000932 00000 n
0000001180 00000 n
0000001233 00000 n
0000001286 00000 n
0000000011 65535 f
0000000012 65535 f
0000000013 65535 f
0000000014 65535 f
0000000015 65535 f
0000000016 65535 f
0000000017 65535 f
0000000018 65535 f
0000000019 65535 f
0000000020 65535 f
0000000000 65535 f
0000001961 00000 n
0000002154 00000 n
0000044863 00000 n
0000048000 00000 n
0000048045 00000 n
trailer
<</Size 26/Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] >>
startxref
48341
%%EOF
xref
0 0
trailer
<</Size 26/Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] /Prev 48341/XRefStm 48045>>
startxref
49017
%%EOF
</code>```

You have a PDF with two trailers. One trailer claims that the cross-reference table in stored in a stream:

```<code>/XRefStm 48045
</code>```

While at the same time indication the start of the cross-reference table at byte position 49017:

```<code>startxref
49017
</code>```

The other trailer claims that there's an uncompressed cross-reference table and that it starts at byte position 48341:

```<code>startxref
48341
</code>```

And indeed: there is an uncompressed cross-reference stream:

```<code>xref
0 26
0000000010 65535 f
0000000017 00000 n
</code>```

Do you understand the inconsistency in your file?

When you use append mode, iText doesn't change anything to the original document: not a single byte is changed; new bytes are added after the final %%EOF marker of the original file. However, iText refuses to do this when the original file is broken. I hope you understand the rationale: you'd make a bad situation worse if iText allowed you to do this.

To solve this problem, you need to fix the broken file first. That can be done by "manipulating" the document without changing anything, but to do this in normal mode, not in append mode.

Have you tried removing the extra trailer. I threw away:

```<code>xref
0 0
trailer
<</Size 26/Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] /Prev 48341/XRefStm 48045>>
startxref
49017
%%EOF
</code>```

Adobe Reader didn't complain after removing these bytes.

Body:
The document you are trying to change in append mode is broken. Most likely, the byte offsets as defined in the cross-reference table don't correspond with the actual byte positions of the PDF objects.

In your case, I see something strange at the end of the file:

xref
0 26
0000000010 65535 f
0000000017 00000 n
0000000166 00000 n
0000000222 00000 n
0000000492 00000 n
0000000755 00000 n
0000000932 00000 n
0000001180 00000 n
0000001233 00000 n
0000001286 00000 n
0000000011 65535 f
0000000012 65535 f
0000000013 65535 f
0000000014 65535 f
0000000015 65535 f
0000000016 65535 f
0000000017 65535 f
0000000018 65535 f
0000000019 65535 f
0000000020 65535 f
0000000000 65535 f
0000001961 00000 n
0000002154 00000 n
0000044863 00000 n
0000048000 00000 n
0000048045 00000 n
trailer
<</Size 26/Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] >>
startxref
48341
%%EOF
xref
0 0
trailer
<</Size 26/Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] /Prev 48341/XRefStm 48045>>
startxref
49017
%%EOF

You have a PDF with two trailers. One trailer claims that the cross-reference table in stored in a stream:

/XRefStm 48045

While at the same time indication the start of the cross-reference table at byte position 49017:

startxref
49017

The other trailer claims that there's an uncompressed cross-reference table and that it starts at byte position 48341:

startxref
48341

And indeed: there is an uncompressed cross-reference stream:

xref
0 26
0000000010 65535 f
0000000017 00000 n

Do you understand the inconsistency in your file?

When you use append mode, iText doesn't change anything to the original document: not a single byte is changed; new bytes are added after the final %%EOF marker of the original file. However, iText refuses to do this when the original file is broken. I hope you understand the rationale: you'd make a bad situation worse if iText allowed you to do this.

To solve this problem, you need to fix the broken file first. That can be done by "manipulating" the document without changing anything, but to do this in normal mode, not in append mode.

Have you tried removing the extra trailer. I threw away:

xref
0 0
trailer
<</Size 26/Root 1 0 R/Info 9 0 R/ID[<8812105F6F93284DAEF240C8C1FC4C4E><8812105F6F93284DAEF240C8C1FC4C4E>] /Prev 48341/XRefStm 48045>>
startxref
49017
%%EOF

Adobe Reader didn't complain after removing these bytes.


问:
ASCII files, how to deal with separator in quoted string?
I have an ASCII file (csv, for instance) that uses , as separator, however this char is also present in quoted strings:

```<code>3,       "hh,1,foo",            foo
"5,,,5", "1,2,3d,,,something ", foo2
test,    "col3",                foo3
</code>```

To avoid such ambiguity I want to replace the , separator by the ; one. How to do that with command line? (under linux).

UPDATE/extra question:

There are at least two options using sed or awk.

My extra question is which one is the fastest? (this can be important for big csv files).

答:
For this not so complicated substitution, use sed

```<code>$ cat file
3,       "hh,1,foo",            foo
"5,,,5", "1,2,3d,,,something ", foo2
test,    "col3",                foo3
$ sed -E 's/,([[:space:]]*")/;\1/g;s/("[[:space:]]*),/\1;/g' file
3;       "hh,1,foo";            foo
"5,,,5"; "1,2,3d,,,something "; foo2
test;    "col3";                foo3
</code>```

Or even shorter

```<code># sed -E 's/,(\s*"[^"]*"\s*),/;\1;/g' file
3;       "hh,1,foo";            foo
"5,,,5"; "1,2,3d,,,something "; foo2
test;    "col3";                foo3
</code>```

And the perl solution would be

```<code># perl -ane  's/,(\s*"[^"]*"\s*),/;$1;/g;print' 47281774
3;       "hh,1,foo";            foo
"5,,,5"; "1,2,3d,,,something "; foo2
test;    "col3";                foo3
</code>```

Body:
I have an ASCII file (csv, for instance) that uses , as separator, however this char is also present in quoted strings:

3,       "hh,1,foo",            foo
"5,,,5", "1,2,3d,,,something ", foo2
test,    "col3",                foo3

To avoid such ambiguity I want to replace the , separator by the ; one. How to do that with command line? (under linux).

UPDATE/extra question:

There are at least two options using sed or awk.

My extra question is which one is the fastest? (this can be important for big csv files).

Body:
For this not so complicated substitution, use sed

$ cat file
3,       "hh,1,foo",            foo
"5,,,5", "1,2,3d,,,something ", foo2
test,    "col3",                foo3
$ sed -E 's/,([[:space:]]*")/;\1/g;s/("[[:space:]]*),/\1;/g' file
3;       "hh,1,foo";            foo
"5,,,5"; "1,2,3d,,,something "; foo2
test;    "col3";                foo3

Or even shorter

# sed -E 's/,(\s*"[^"]*"\s*),/;\1;/g' file
3;       "hh,1,foo";            foo
"5,,,5"; "1,2,3d,,,something "; foo2
test;    "col3";                foo3

And the perl solution would be

# perl -ane  's/,(\s*"[^"]*"\s*),/;$1;/g;print' 47281774
3;       "hh,1,foo";            foo
"5,,,5"; "1,2,3d,,,something "; foo2
test;    "col3";                foo3


问:
Ruby : hydrate hash values from array
Let's say I have an ruby array like this :

```<code>values = ['val_a', 'val_b',..., 'val_z'] # 26 values
</code>```

And an hash with keys

```<code>hash = {a: nil, b: nil, ... , z: nil} # 26 keys
</code>```

I know that the array is sorted, and I know that keys of hash are sorted, and I know both array and hash are of same size.

How can I elegantly hydrate hash values so that I end up with

```<code>{a: 'val_a', b: 'val_b', ... , z: 'val_z'}
</code>```

答:
Since Ruby 2.4.0 you can do the following:

```<code>hash.transform_values.with_index { |v,i| values[i] }
</code>```

Using Hash#transform_values, the intent is clear. Its dangerous counterpart Hash#transform_values! is also available.

Title: Ruby : hydrate hash values from array

Body:
Let's say I have an ruby array like this :

values = ['val_a', 'val_b',..., 'val_z'] # 26 values

And an hash with keys

hash = {a: nil, b: nil, ... , z: nil} # 26 keys

I know that the array is sorted, and I know that keys of hash are sorted, and I know both array and hash are of same size.

How can I elegantly hydrate hash values so that I end up with

{a: 'val_a', b: 'val_b', ... , z: 'val_z'}

Body:
Since Ruby 2.4.0 you can do the following:

hash.transform_values.with_index { |v,i| values[i] }

Using Hash#transform_values, the intent is clear. Its dangerous counterpart Hash#transform_values! is also available.


问:
Download MP4 Video In Specific Folder In server With CURL
I'm Trying To Download .MP4 Extension File With PHP Code In Specific Folder My Code Working Fine For .MP4 Extension Only But I Can't Download This URL MP4 Video With This Code

https://r3---sn-vgqsrnel.c.doc-0-0-sj.sj.googleusercontent.com/videoplayback?itag=18&key=yt6&source=youtube&mime=video%2Fmp4&sparams=dur%2Cei%2Cid%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Csource%2Cexpire&mv=m&ipbits=0&ratebypass=yes&ms=au&mn=sn-vgqsrnel&pl=28&mm=31&dur=296.147&id=o-AGGQKzVE4Kx-vQgQkb_7v_-2v8RJEP8bYukfJukhn8PM&expire=1510672628&lmt=1510636913694890&ip=107.178.194.23&mt=1510650948&ei=lLQKWoz2NcruDrDrikg&signature=B548DE94A6C594DE473F900D22D3A2685FBEBDED.126ED86D280FC8A4B1FF33B62A6F02EFC0E43576

I'm Trying This Code

```<code>    function download ($url, $location){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSLVERSION,3);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $data = curl_exec ($ch);
    $error = curl_error($ch);
    curl_close ($ch);

    $file = fopen($location, "wb");
    fwrite($file, $data);
    fclose($file);
    return 'done';
    }
    ?>
    <!DOCTYPE html>
    <html>
    <body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    Video URL (Only With .MP4 Extension):
    <input type="text" name="url" placeholder="Video URL Here" required/><br>
    Video ID Number:
    <input type="text" name="id" placeholder="Video ID Nmber eg:1,2,3" required/><br>
    <input type="submit"/>
    </form>
    </body>
    </html>
    <?php
    @$url = $_POST['url'];
    @$ID = $_POST['id'];
    $SCRIPT_DIR = dirname(__FILE__);
    $TEMP_DIR = $SCRIPT_DIR . '/videos/';
    $location = $TEMP_DIR . $ID . '.mp4';
    if(isset($_POST['url'])){

        echo download($url, $location);

    }
</code>```

答:
I have used this code before to download videos from same source:</p>

```<code>function download ($url, $location){
  $fp = fopen($location, "w+");
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  curl_setopt($ch, CURLOPT_FILE, $fp);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_exec($ch);
  curl_close($ch);
  fclose($fp);

  return 'done';
}
</code>```

Body:
I'm Trying To Download .MP4 Extension File With PHP Code In Specific Folder My Code Working Fine For .MP4 Extension Only But I Can't Download This URL MP4 Video With This Code

<a href="https://r3---sn-vgqsrnel.c.doc-0-0-sj.sj.googleusercontent.com/videoplayback?itag=18&key=yt6&source=youtube&mime=video%2Fmp4&sparams=dur%2Cei%2Cid%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Csource%2Cexpire&mv=m&ipbits=0&ratebypass=yes&ms=au&mn=sn-vgqsrnel&pl=28&mm=31&dur=296.147&id=o-AGGQKzVE4Kx-vQgQkb_7v_-2v8RJEP8bYukfJukhn8PM&expire=1510672628&lmt=1510636913694890&ip=107.178.194.23&mt=1510650948&ei=lLQKWoz2NcruDrDrikg&signature=B548DE94A6C594DE473F900D22D3A2685FBEBDED.126ED86D280FC8A4B1FF33B62A6F02EFC0E43576" rel="nofollow noreferrer">https://r3---sn-vgqsrnel.c.doc-0-0-sj.sj.googleusercontent.com/videoplayback?itag=18&key=yt6&source=youtube&mime=video%2Fmp4&sparams=dur%2Cei%2Cid%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Csource%2Cexpire&mv=m&ipbits=0&ratebypass=yes&ms=au&mn=sn-vgqsrnel&pl=28&mm=31&dur=296.147&id=o-AGGQKzVE4Kx-vQgQkb_7v_-2v8RJEP8bYukfJukhn8PM&expire=1510672628&lmt=1510636913694890&ip=107.178.194.23&mt=1510650948&ei=lLQKWoz2NcruDrDrikg&signature=B548DE94A6C594DE473F900D22D3A2685FBEBDED.126ED86D280FC8A4B1FF33B62A6F02EFC0E43576

I'm Trying This Code

    function download ($url, $location){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSLVERSION,3);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $data = curl_exec ($ch);
    $error = curl_error($ch);
    curl_close ($ch);

    $file = fopen($location, "wb");
    fwrite($file, $data);
    fclose($file);
    return 'done';
    }
    ?>
    <!DOCTYPE html>

    <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    Video URL (Only With .MP4 Extension):
    <input type="text" name="url" placeholder="Video URL Here" required/>

    Video ID Number:
    <input type="text" name="id" placeholder="Video ID Nmber eg:1,2,3" required/>

    <input type="submit"/>
    </form>

    <?php
    @$url = $_POST['url'];
    @$ID = $_POST['id'];
    $SCRIPT_DIR = dirname(__FILE__);
    $TEMP_DIR = $SCRIPT_DIR . '/videos/';
    $location = $TEMP_DIR . $ID . '.mp4';
    if(isset($_POST['url'])){

        echo download($url, $location);

    }

Body:
I have used this code before to download videos from same source:

function download ($url, $location){
  $fp = fopen($location, "w+");
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  curl_setopt($ch, CURLOPT_FILE, $fp);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_exec($ch);
  curl_close($ch);
  fclose($fp);

  return 'done';
}


问:
Up ActionBar action on DialogFragment
I have a DialogFragment that is styled to full screen using setStyle(STYLE_NORMAL, R.style.Theme_App).

The DialogFragment shows fine but the up action (the homeAsUp action on the ActionBar) does not work. I tried implementing onOptionsItemSelected in the DialogFragment but it is never called.

Is there a way to get the up action callback in the DialogFragment so I can dismiss it ? For reference, I'm using ActionBarCompat.

答:
define toolbar in layout and call it on your dialog fragment</p>

```<code>Toolbar toolbar=dialog.findViewById(R.id.toolbar);
                           toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
                          toolbar.setOnClickListener(new View.OnClickListener() {
                              @Override
                              public void onClick(View view) {
                                  dialog.dismiss();
                              }
                          });
</code>```

Title: Up ActionBar action on DialogFragment

Body:
define toolbar in layout and call it on your dialog fragment

Toolbar toolbar=dialog.findViewById(R.id.toolbar);
                           toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
                          toolbar.setOnClickListener(new View.OnClickListener() {
                              @Override
                              public void onClick(View view) {
                                  dialog.dismiss();
                              }
                          });


问:
how to trigger a validation of child component from parent component OnSubmit Angular 4?
I Have forms like this, in parent i am including multiple child components each child component is formgroup. now i need to check all this child forms validation on parent form when user click OnSubmit.

How should i trigger child form validations from parent on submit. I have used FormBuilder in each childcomponent.

I am able to do validation when user click on child fields but if user doesn't enter anything or touched anything and try to submit validations not showing errors.

parent.component.html

```<code><form>
    <child1></child1>
    <child2></child2>
    <child3></child4>
    <child4></child4>
''''
''''
''''
</form>
</code>```

child1.component.html

```<code><div formgroup="child1group">
      <div formarray= "child1array">
      ....
      ...
      ...
      </div>
</div
</code>```

child2.component.html

```<code><div formgroup="child2group">
      <div formarray= "child2array">
      ....
      ...
      ...
      </div>
</div
</code>```

please someone tell me how to do this validation on angular 4 ?

答:
Pass the Formcontrol to Parent as OUTPUT and then do validation by calling function SaveConsole() in button click

child1.component.ts

```<code>@Output() public childControls = new EventEmitter();

 public ngOnInit() {
        this.childControls.emit(this.child1group);
        this.child1group.valueChanges.subscribe(() => {
            this.childControls.emit(this.child1group);
        });
  }
</code>```

parent.component.html

```<code>   <form>
        <child1 (childControls)="child1Control = $event"></child1>
         <button (Click)=SaveConsole()> Submit </butto>
   </form>
</code>```

parent.ts

```<code>   public child1Control: FormGroup;
   public SaveConsole() {
          if (this.child1Control.valid) {
            // SAVE FORM
          } else {
            this.validateAllFormFields(this.child1Control);
          }
      }
     public validateAllFormFields(formGroup: FormGroup) {
      Object.keys(formGroup.controls).forEach(field => {
      const control = formGroup.get(field);
      if (control instanceof FormControl) {
        control.markAsTouched({ onlySelf: true });
      } else if (control instanceof FormGroup) {
        this.validateAllFormFields(control);
      }
    });
}
</code>```

Body:
I Have forms like this, in parent i am including multiple child components each child component is formgroup. now i need to check all this child forms validation on parent form when user click OnSubmit.

How should i trigger child form validations from parent on submit. I have used FormBuilder in each childcomponent.

I am able to do validation when user click on child fields but if user doesn't enter anything or touched anything and try to submit validations not showing errors.

parent.component.html

<form>
    <child1></child1>
    <child2></child2>
    <child3></child4>
    <child4></child4>
''''
''''
''''
</form>

child1.component.html

      ....
      ...
      ...

</div

child2.component.html

      ....
      ...
      ...

</div

please someone tell me how to do this validation on angular 4 ?

Body:
Pass the Formcontrol to Parent as OUTPUT and then do validation by calling function SaveConsole() in button click

child1.component.ts

@Output() public childControls = new EventEmitter();

 public ngOnInit() {
        this.childControls.emit(this.child1group);
        this.child1group.valueChanges.subscribe(() => {
            this.childControls.emit(this.child1group);
        });
  }

parent.component.html

   <form>
        <child1 (childControls)="child1Control = $event"></child1>
         <button (Click)=SaveConsole()> Submit </butto>
   </form>

parent.ts

   public child1Control: FormGroup;
   public SaveConsole() {
          if (this.child1Control.valid) {
            // SAVE FORM
          } else {
            this.validateAllFormFields(this.child1Control);
          }
      }
     public validateAllFormFields(formGroup: FormGroup) {
      Object.keys(formGroup.controls).forEach(field => {
      const control = formGroup.get(field);
      if (control instanceof FormControl) {
        control.markAsTouched({ onlySelf: true });
      } else if (control instanceof FormGroup) {
        this.validateAllFormFields(control);
      }
    });
}


问:
PHP Singleton Acting Funny
I have the following code:

```<code>$e1 = call_user_func(array("MySQL_Extension", "getInstance"));
$e2 = call_user_func(array("Error_Extension", "getInstance"));
self::$extensions->MySQL = $e1;
self::$extensions->Error = $e2;

// Debug
echo "```";
print_r(self::$extensions);
```

<p>Each getInstance() method looks like this:</p>

```public static function getInstance()
{
    if (self::$_instance == null)
    {
        self::$_instance = new self;
    }

    return self::$_instance;
}
```

<p>Both classes extend the same "Extension_Abstract" class, but for some reason, the "print_r" debug statement listed outputs the following:</p>

```stdClass Object (
    [MySQL] => MySQL_Extension Object
    [Error] => MySQL_Extension Object
)
```

Do you all have any idea why it would be returning two "MySQL_Extension" objects, and completely ignoring the Error_Extension class?  I'm so confused!

答:
late binding issue.</p>

```<code>public static function getInstance()
{
    if (static::$_instance == null)
    {
        static::$_instance = new static();
    }

    return static::$_instance;
}
</code>```

Title: PHP Singleton Acting Funny

Body:
I have the following code:

$e1 = call_user_func(array("MySQL_Extension", "getInstance"));
$e2 = call_user_func(array("Error_Extension", "getInstance"));
self::$extensions->MySQL = $e1;
self::$extensions->Error = $e2;

// Debug
echo "
";
print_r(self::$extensions);

Each getInstance() method looks like this:

public static function getInstance()
{
    if (self::$_instance == null)
    {
        self::$_instance = new self;
    }

    return self::$_instance;
}

Both classes extend the same "Extension_Abstract" class, but for some reason, the "print_r" debug statement listed outputs the following:

stdClass Object (
    [MySQL] => MySQL_Extension Object
    [Error] => MySQL_Extension Object
)

Do you all have any idea why it would be returning two "MySQL_Extension" objects, and completely ignoring the Error_Extension class?  I'm so confused!

Body:
late binding issue.

public static function getInstance()
{
    if (static::$_instance == null)
    {
        static::$_instance = new static();
    }

    return static::$_instance;
}


问:
sql query with two joins and a simple logic
Please find the fiddle
http://sqlfiddle.com/#!9/4a4aff/7

Friends_list Table

```<code> | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P
</code>```

User Table

```<code>| ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx
</code>```

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status  NOT IN ('P', 'B')
</code>```

答:
You can use this query, your fiddle is showing blank result as you have only data with P Status, try to add one more entry with some other status then you will get the result.  </p>

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u left join friends_list f
on f.friend_id=u.ID where f.status is NULL
</code>```

Body:
Please find the fiddle
http://sqlfiddle.com/#!9/4a4aff/7

Friends_list Table

 | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P

User Table

| ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status  NOT IN ('P', 'B')

Body:
You can use this query, your fiddle is showing blank result as you have only data with P Status, try to add one more entry with some other status then you will get the result.

select DISTINCT u.ID, u.user_nicename from wp_users u left join friends_list f
on f.friend_id=u.ID where f.status is NULL


问:
Writing vba code in sas
I want to implement my VBA code into my SAS-code, so I can do the whole process with one run.  My SAS code reads a big SAS table, does some transformations, and finally exportes to an Excel file (the code is below). I also wrote some VBA code in the Excel file (for example AutoFiltering for some variables, you can see the code below).

The table looks like this:

```<code>A B C Var1 Var2 Var3
--------------------
1 1 1 10 15 20
1 1 2 15 20 30
1 2 1 20 30 40
1 2 2 30 40 50
2 1 1 40 50 60
2 1 2 50 60 70
2 2 1 60 70 80
..............
..............
</code>```

However, I want to implement my VBA code into my SAS-code, so I can do the whole process with one run. I know how to open and run an Excel file in SAS (the code is below), but I don't know how to implement a VBA code in my SAS.

If you wonder why I want to implement my Macro-code in my SAS, I will work with similar SAS-tables many times in the future, so it would be more practicle to keep the whole-code in one place.

I just realized that I can't export an table in SAS in macro-enabled Excel format, XLSM. I guess it is also a challange. Also, it is not so practicle to save a Macro-code from an Excel file, because it must be saved in Adds-in menu. So it would be much better to handle the whole process in one place, like inside the SAS editor.

THE code in SAS which exports the final table to an Excel file:

```<code>PROC EXPORT DATA=File1
        OUTFILE= "&server\&env\test1.xlsx"
        DBMS=EXCEL REPLACE;
   SHEET="sheet1";
RUN;
</code>```

The VBA code example in the Excel file to create AutoFilter for variables in the Excel file:

```<code>Sub Macro1()
    Dim N As Long, r As Range
With Sheets("sheet1")
    N = .Cells(Rows.Count, "B").End(xlUp).Row
    ReDim ary(1 To N)
    For i = 1 To N
        ary(i) = .Cells(i, 1)
    Next i
End With

Range("A1:F20").AutoFilter
ActiveSheet.Range("$A$1:$F$20").AutoFilter Field:=1, Criteria1:=ary, Operator:=xlFilterValues
End Sub
</code>```

The code in SAS to start and run an Excel file in SAS:

```<code>OPTIONS NOXWAIT NOXSYNC;
   DATA _NULL_;
   RC=SYSTEM('START EXCEL');
   RC=SLEEP(0.5);
RUN;
FILENAME CMDS DDE 'EXCEL|SYSTEM';
DATA _NULL_;
   FILE CMDS;
   PUT "[OPEN(""&server\&env\test1.XLS"")]";
   PUT '[RUN("Macro1")]';
   PUT '[SAVE.AS("&server\&env\FORMATTED_FILE.XLSM")';
   PUT "[QUIT()]";
RUN;
QUIT;
</code>```

答:
With DDE you can set the filter in SAS:</p>

```<code>data _null_;
    FILE CMDS;
    /* select your worksheet */
    put '[workbook.select("your_sheet")]';
    /* select the column range you want to set the filter */
    put '[select("r1c2:r1c5")]';
    /* set filter */
    put '[filter]';
run;
</code>```

Title: Writing vba code in sas

Body:
I want to implement my VBA code into my SAS-code, so I can do the whole process with one run.  My SAS code reads a big SAS table, does some transformations, and finally exportes to an Excel file (the code is below). I also wrote some VBA code in the Excel file (for example AutoFiltering for some variables, you can see the code below).

The table looks like this:

A B C Var1 Var2 Var3
--------------------
1 1 1 10 15 20
1 1 2 15 20 30
1 2 1 20 30 40
1 2 2 30 40 50
2 1 1 40 50 60
2 1 2 50 60 70
2 2 1 60 70 80
..............
..............

However, I want to implement my VBA code into my SAS-code, so I can do the whole process with one run. I know how to open and run an Excel file in SAS (the code is below), but I don't know how to implement a VBA code in my SAS.

If you wonder why I want to implement my Macro-code in my SAS, I will work with similar SAS-tables many times in the future, so it would be more practicle to keep the whole-code in one place.

I just realized that I can't export an table in SAS in macro-enabled Excel format, XLSM. I guess it is also a challange. Also, it is not so practicle to save a Macro-code from an Excel file, because it must be saved in Adds-in menu. So it would be much better to handle the whole process in one place, like inside the SAS editor.

THE code in SAS which exports the final table to an Excel file:

PROC EXPORT DATA=File1
        OUTFILE= "&server\&env\test1.xlsx"
        DBMS=EXCEL REPLACE;
   SHEET="sheet1";
RUN;

The VBA code example in the Excel file to create AutoFilter for variables in the Excel file:

Sub Macro1()
    Dim N As Long, r As Range
With Sheets("sheet1")
    N = .Cells(Rows.Count, "B").End(xlUp).Row
    ReDim ary(1 To N)
    For i = 1 To N
        ary(i) = .Cells(i, 1)
    Next i
End With

Range("A1:F20").AutoFilter
ActiveSheet.Range("$A$1:$F$20").AutoFilter Field:=1, Criteria1:=ary, Operator:=xlFilterValues
End Sub

The code in SAS to start and run an Excel file in SAS:

OPTIONS NOXWAIT NOXSYNC;
   DATA _NULL_;
   RC=SYSTEM('START EXCEL');
   RC=SLEEP(0.5);
RUN;
FILENAME CMDS DDE 'EXCEL|SYSTEM';
DATA _NULL_;
   FILE CMDS;
   PUT "[OPEN(""&server\&env\test1.XLS"")]";
   PUT '[RUN("Macro1")]';
   PUT '[SAVE.AS("&server\&env\FORMATTED_FILE.XLSM")';
   PUT "[QUIT()]";
RUN;
QUIT;

Body:
With DDE you can set the filter in SAS:

data _null_;
    FILE CMDS;
    /* select your worksheet */
    put '[workbook.select("your_sheet")]';
    /* select the column range you want to set the filter */
    put '[select("r1c2:r1c5")]';
    /* set filter */
    put '[filter]';
run;


问:
Is using parenthesis in HTML classes okay?
I'm trying to create some helper classes in a reusable and readable way.

I want to use this scheme : class="property-name(direction)(value)"

For example : class="margin(top)(15)"

In CSS, It will be written as .margin\(top\)(\15\) { ... }

Does it works? Yes, see the fiddle below:

.sample__wrapper {
  border: 1px solid #eee;
  padding: 15px;
}

.sample__item {
  width: 100%;
  height: 100px;
  background: #eee;
}

.margin\(top\)\(15\) {
  margin-top: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sample__wrapper">
  <div class="sample__item"></div>
  <div class="sample__item margin(top)(15)"></div>
</div></code>```

Because I rarely see this kind of syntax (using \ for parenthesis), I wonder if It's allowed to do so?

EDIT

Regarding the grammar of CSS (here 2.1), parenthesis are allowed.

Thanks to @Dan Kreiger in comments below, there is a CSS framework - using the same "readability idea" - called Atomic CSS. Also, a link to a CSS tricks article about it (not the Framework, the terminology).

Finally, HTML will be (to me) extremely readable. CSS or JS will not!

Have fun! ☺

答:
This might not be the answer of the question as it is primarily opinion based.

It's better to use BEM in the context of re-usability and readability. It gives the classes a good structure compare to what you are going with.

Using \ each and every time while defining the classes it would be a mess.

Body:
I'm trying to create some helper classes in a reusable and readable way.

I want to use this scheme : class="property-name(direction)(value)"

For example : class="margin(top)(15)"

In CSS, It will be written as .margin\(top\)(\15\) { ... }

Does it works? Yes, see the fiddle below:

.sample__wrapper {
  border: 1px solid #eee;
  padding: 15px;
}

.sample__item {
  width: 100%;
  height: 100px;
  background: #eee;
}

.margin\(top\)\(15\) {
  margin-top: 15px;
}

Because I rarely see this kind of syntax (using \ for parenthesis), I wonder if It's allowed to do so?

EDIT

Regarding the grammar of CSS (here 2.1), parenthesis are allowed.

Thanks to @Dan Kreiger in comments below, there is a CSS framework - using the same "readability idea" - called Atomic CSS. Also, a link to a CSS tricks article about it (not the Framework, the terminology).

Finally, HTML will be (to me) extremely readable. CSS or JS will not!

Have fun! ☺


问:
How to get columns name in mysqldb with a Python 2.7?
If I am using select * from query it is working well, but when I am trying to query the columns name too, it isnt working (maybe because I have got a column called "FROM" but that's why i used 'FROM!?)

Here my code:

```<code>connection = MySQLdb.connect(host='localhost',
    user='admin',
    passwd='',
    db='database1',
    use_unicode=True,
    charset="utf8")
cursor = connection.cursor()
query = """ select ACTUAL_TIME, 'FROM, ID
    union all
    select ACTUAL_TIME,  FROM , ID
    from TEST
        into outfile '/tmp/test.csv'
        fields terminated by ';'
        enclosed by '"'
        lines terminated by '\n';
        """

cursor.execute(query)
connection.commit()
cursor.close()
</code>```

I get this error message:

```<code>raise errorvalue
_mysql_exceptions.OperationalError: (1054, "Unknown column 'ACTUAL_TIME' in 'field list'")
</code>```

EDIT: SHOW CREATE TABLE TEST;

```<code>| TEST | CREATE TABLE `TEST` (
  `ACTUAL_TIME` varchar(100) DEFAULT NULL,
  `FROM` varchar(100) DEFAULT NULL,
  `STATUS` varchar(100) DEFAULT NULL,
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=76287 DEFAULT CHARSET=utf8 |
</code>```

答:
try this :

```<code>connection = MySQLdb.connect(host='localhost',
    user='admin',
    passwd='',
    db='database1',
    use_unicode=True,
    charset="utf8")
cursor = connection.cursor()
query = """ select 'ACTUAL_TIME', 'FROM', 'ID' -- add single quotes
    union all
    select `ACTUAL_TIME`, `FROM`, `ID`  -- add here backtick in column names
    from TEST
        into outfile '/tmp/test.csv'
        fields terminated by ';'
        enclosed by '"'
        lines terminated by '\n';
        """

cursor.execute(query)
connection.commit()
cursor.close()
</code>```

or else you can use this to get column names "SHOW columns"

or :

```<code>cursor.execute("SELECT * FROM table_name LIMIT 0")
print cursor.description
</code>```

Body:
If I am using select * from query it is working well, but when I am trying to query the columns name too, it isnt working (maybe because I have got a column called "FROM" but that's why i used 'FROM!?)

Here my code:

connection = MySQLdb.connect(host='localhost',
    user='admin',
    passwd='',
    db='database1',
    use_unicode=True,
    charset="utf8")
cursor = connection.cursor()
query = """ select ACTUAL_TIME, 'FROM, ID
    union all
    select ACTUAL_TIME,  FROM , ID
    from TEST
        into outfile '/tmp/test.csv'
        fields terminated by ';'
        enclosed by '"'
        lines terminated by '\n';
        """

cursor.execute(query)
connection.commit()
cursor.close()

I get this error message:

raise errorvalue
_mysql_exceptions.OperationalError: (1054, "Unknown column 'ACTUAL_TIME' in 'field list'")

EDIT: SHOW CREATE TABLE TEST;

| TEST | CREATE TABLE `TEST` (
  `ACTUAL_TIME` varchar(100) DEFAULT NULL,
  `FROM` varchar(100) DEFAULT NULL,
  `STATUS` varchar(100) DEFAULT NULL,
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=76287 DEFAULT CHARSET=utf8 |

Body:
try this :

connection = MySQLdb.connect(host='localhost',
    user='admin',
    passwd='',
    db='database1',
    use_unicode=True,
    charset="utf8")
cursor = connection.cursor()
query = """ select 'ACTUAL_TIME', 'FROM', 'ID' -- add single quotes
    union all
    select `ACTUAL_TIME`, `FROM`, `ID`  -- add here backtick in column names
    from TEST
        into outfile '/tmp/test.csv'
        fields terminated by ';'
        enclosed by '"'
        lines terminated by '\n';
        """

cursor.execute(query)
connection.commit()
cursor.close()

or else you can use this to get column names "SHOW columns"

or :

cursor.execute("SELECT * FROM table_name LIMIT 0")
print cursor.description


问:
How to close all open terminal windows except the one running a shell script
I wanted to have a script that is capable of killing console windows, that are either running something or not, but at the same time, keep alive the window that executed this script.

Thanks for your help

答:
You can find the command name of the parent the script (bash, sh, zsh, etc.) then kill all the processes with that command-name.
This way you kill all the bash processes but the one running the script.
i.e.

```<code>C=$(ps -p $(ps -p $$ -o ppid=) o args=)
P=$(ps -p $$ -o pid=)
for p in $(pgrep $C); do
    if [ $p -ne $P ]; then
        kill $p
    fi
done
</code>```

This is very not portable. If you also want to close the consoles that are running something it becomes even less portable:

```<code>C=$(ps -p $(ps -p $$ -o ppid=) o args=)
P1=$(ps -p $$ -o pid=)
P2=$(ps -p $$ -o ppid=)
echo $(pgrep $C)
for p in $(pgrep $C | tail -n +2); do
    [ $p -ne $P1 ] && [ $p -ne $P2 ] && kill -9 $p
done
</code>```

It will not work if the script is launched by another script or in a
bash session within another bash session (e.g. a root session)

It will not kill the first bash window if the Desktop Environment was
not launched by bash (e.g. if you have the desktop environment set to
run at startup), to address this issue, you can remove the | tail -n +2 in the for loop.

It will also close the console tabs in addition to the windows.

Body:
You can find the command name of the parent the script (bash, sh, zsh, etc.) then kill all the processes with that command-name.
This way you kill all the bash processes but the one running the script.
i.e.

C=$(ps -p $(ps -p $$ -o ppid=) o args=)
P=$(ps -p $$ -o pid=)
for p in $(pgrep $C); do
    if [ $p -ne $P ]; then
        kill $p
    fi
done

This is very not portable. If you also want to close the consoles that are running something it becomes even less portable:

C=$(ps -p $(ps -p $$ -o ppid=) o args=)
P1=$(ps -p $$ -o pid=)
P2=$(ps -p $$ -o ppid=)
echo $(pgrep $C)
for p in $(pgrep $C | tail -n +2); do
    [ $p -ne $P1 ] && [ $p -ne $P2 ] && kill -9 $p
done

It will not work if the script is launched by another script or in a
bash session within another bash session (e.g. a root session)

It will not kill the first bash window if the Desktop Environment was
not launched by bash (e.g. if you have the desktop environment set to
run at startup), to address this issue, you can remove the | tail -n +2 in the for loop.

It will also close the console tabs in addition to the windows.


问:
Bootstrap 4 Beta nav not working
FIXED: Was custom CSS, not bootstrap at all :/

This nav worked a few days ago but now it won't display the items on xsand sm screens when I toggle it. Everything works om md and up.

```<code><nav class="navbar navbar-expand-md nav-margin-md navbar-dark bg-dark">

            <div class="navbar-brand" style="font-size: 95%;">
                Brand
            </div>

            <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navCollapse">
                <span class="navbar-toggler-icon"></span>
            </button>

            <!-- Container for all links and navbar content -->
            <div class="collapse navbar-collapse" id="navCollapse">
                <ul class="navbar-nav nav-margin-md">
                    <li class="nav-item"><a class="nav-link" href="index.html">Hjem</a></li>
                    <li class="nav-item"><a class="nav-link" href="./pages/bilder.html">Bilder</a></li>
                    <li class="nav-item"><a class="nav-link disabeled" href="./pages/about.html">Om Oss</a></li>
                    <li class="nav-item"><a class="nav-link disabeled" href="./pages/services.html">Tjenester</a></li>
                </ul>
            </div>

        </nav> <!-- /navbar -->
</code>```

答:
Maybe you miss any of required file for the bootstrap 4 beta.For this, you need a jquery.js and tether.js files.

check your code here

Title: Bootstrap 4 Beta nav not working

Body:
FIXED: Was custom CSS, not bootstrap at all :/

This nav worked a few days ago but now it won't display the items on xsand sm screens when I toggle it. Everything works om md and up.

                Brand

            <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navCollapse">

            </button>

Hjem

Bilder

Om Oss

Tjenester


问:
C# - Add common behaviour in abstract class after calling individual behaviours in subclasses
I'm quite new to abstract classes. Usually you can create a member in a base-class and then extend its logic by calling it in the subclasses using base.Member. But can I do it the other way around?

I have an abstract class A with a property of type IEnumerable<T>:

```<code>abstract class A
{
    IEnumerable<int> Foo { get; }
}
</code>```

I want the derived classes of A to return an individual IEnumerable and want to "filter" them using .Where by the same condition. I did following:

```<code>abstract class A
{
    public IEnumerable<int> Foo => Bar.Where(x => true);
    protected abstract IEnumerable<int> Bar { get; }
}
abstract class B : A
{
    protected override IEnumerable<int> Bar {
        get { yield return 1; }
    }
}
</code>```

It works, but is this the right approach? Or can I do the same thing using only one property? It feels especially clunky if I have some classes between which also have to filter it because I'd just have to add more and more members based on the amount of layers I have.

答:
It's a pretty standard idiom.

Consider it thus: In defining the abstract Bar you're saying "all implementations can 'Bar'", and then when you call it from Foo that makes perfect since, since all implementations can 'Bar'.

It feels especially clunky if I have some classes between which also have to filter it because I'd just have to add more and more members based on the amount of layers I have.

Do you mean that other classes are also doing Where() on the same enumerable? Don't mind that; A is doing what Foo means, and the subclass is doing what Bar means for it, and whether that's another Where() or not is not something to worry about in A. (Sometimes we do have to break that rule if it turns out to be a performance hotspot, but firstly the initial design is not a place to consider that, and secondly Enumerable.Where() is in fact already optimised for sequential calls of a Where() on the results of Where() anyway).

Body:
I'm quite new to abstract classes. Usually you can create a member in a base-class and then extend its logic by calling it in the subclasses using base.Member. But can I do it the other way around?

I have an abstract class A with a property of type IEnumerable<T>:

abstract class A
{
    IEnumerable<int> Foo { get; }
}

I want the derived classes of A to return an individual IEnumerable and want to "filter" them using .Where by the same condition. I did following:

abstract class A
{
    public IEnumerable<int> Foo => Bar.Where(x => true);
    protected abstract IEnumerable<int> Bar { get; }
}
abstract class B : A
{
    protected override IEnumerable<int> Bar {
        get { yield return 1; }
    }
}

It works, but is this the right approach? Or can I do the same thing using only one property? It feels especially clunky if I have some classes between which also have to filter it because I'd just have to add more and more members based on the amount of layers I have.


问:
enable fpu support for aarch64 (armv8-a) on gcc version 5.0.1
I am measuring the GFLOPS performance of the Cortex-a57 with the HPLinpack benchmarks and it barely achieves 1 FP/cycle (considering ~2.4 GFLOPS @ 2.4 GHz). Since the old compiler (gcc 4.9.1) complained with several version of the -mfpu= option, I tried to configure gcc 5.0.1 as below

../gcc/configure --with-gmp=/tmp/gcc --with-mpfr=/tmp/gcc --with-mpc=/tmp/gcc --with-libelf=/tmp/gcc --enable-languages=c,c++,fortran,go --target=aarch64-linux-gnu --prefix=/opt/another-gcc5 --with-arch=armv8-a --with-cpu=cortex-a57 --with-fpu=neon-fp-armv8

configuration went fine, but when invoking make the --with-fpu flag crashed in gcc/gcc/config.gcc :4351

echo "This target does not support --with-$option." 2>&1

due to the supported_defaults for the aarch64 architecture as defined in gcc/gcc/config.gcc 3464:3467

supported_defaults=
  case "${target}" in
    aarch64*--)
        supported_defaults="abi cpu arch"

How come the fpu option is not supported? any advice is appreciated, I have never done this before and I am a bit lost :)

答:
The 32-bit arm and 64-bit aarch64 targets are separate in GCC.
The aarch64 target does not support a --with-fpu configure option (or an -mfpu command-line option) because an FPU is assumed to be present by default. So you always get floating-point and AdvancedSIMD support by default.

This is unlike the 32-bit arm target (the arm*-*-* triplets) which also supports a soft-float ABI and can be configured with different levels of FPU support from older versions of the architecture.

In summary: if you're targeting aarch64 you don't need to specify a --with-fpu configure option (and it's not supported on aarch64 anyway)


问:
docker could not use system proxy
I am trying to use docker behind corporate firewall.

I would like to force docker to use system Proxy, but this option is not available. How can I make docker to system Proxy.

答:
I've written a blog post about using the weird DummyDesperatePoitras virtual switch as an anchor for CNTLM, and that resolves some of the problems I mentioned here (having to change the proxy address for Docker every time your IP changes, among other things):

http://mandie.net/2017/12/10/docker-for-windows-behind-a-corporate-web-proxy-tips-and-tricks/

As of November 2017, this feature was still not implemented in Docker for Windows: https://github.com/docker/for-win/issues/589

The best solution I've found is CNTLM, but I'm not delighted with it, because:

1) CNTLM has not been updated in 5 years

2) You have to set the proxy IP in the Docker GUI, making it rather automation-resistant. The Docker for Windows GUI reads the proxy settings from the MobyLinux VM, not from the Windows registry, a config file or Windows environment variables. Setting HTTP_PROXY and HTTPS_PROXY in Windows has absolutely no effect on Docker. I've not found any way of setting the proxy value programmatically; the MobyLinux VM doesn't accept ssh connections. If anyone ever finds a way to do this from a command line or script, I'd love to know.

3) Setting the proxy IP to 127.0.0.1 won't work, because that will get the virtual machine that Docker is really running on to try its own interface, not the one on the host PC running CNTLM. I have also tried the DockerNAT interface IP, 10.0.75.1, with no success.

4) This means that the proxy IP needs to be the current IP address of your active external network interface. If you move around buildings a lot, you need to check this every time you want to use Docker.

Set CNTLM to listen on 0.0.0.0 3128, not just 3128 or 127.0.0.1 3128. This will save you the trouble of updating this IP address every time your PC gets a new IP address. Just having the port number will keep traffic from the VM running Docker from being "heard".

Calculate the NTLMv2 hash and store that in the config file instead of your username and password. This will be different for every PC and user account, so don't share your unredacted config file with another PC unless you want to get locked out. You will need to update this stored hash when you next change your Windows password.

Restart the cntlm Windows service after any changes to its config file.

Run ipconfig in cmd.exe or PowerShell to find your current IP address. If you're using corporate VPN, use the IP address of the WiFi or Ethernet adapter, not the VPN.

Type http://ipfromipconfig:3128/ into the "Web Server (HTTP)" box. Make sure the checkbox "Use same for both" is checked.

Title: docker could not use system proxy


问:
Return referenced sheet name within an formula in excel
Is there a way to check which spreadsheet is being referenced within a formula.

For example, I have the following reference =('2015'!A1) and I need to check which sheet I am using in the reference. In this example it's "2015". But sometimes I changes to "2016", sometimes to "2012"... Is there a way to check or return the referenced sheet within the formula? Preferably without VBA.

答:
I'll add this as an answer for versions earlier than Excel 2013.

You can use an Excel 4 Macro Function in a named range to return the formula in a cell.

This formula as a named range will return the formula in the cell above the formula:

```<code>=GET.CELL(6,OFFSET(INDIRECT("RC",FALSE),-1,0))
</code>```

I'll add this link for more info on the other types of info that can be returned:  https://www.mrexcel.com/forum/excel-questions/20611-info-only-get-cell-arguments.html

Body:
I'll add this as an answer for versions earlier than Excel 2013.

You can use an Excel 4 Macro Function in a named range to return the formula in a cell.

This formula as a named range will return the formula in the cell above the formula:

=GET.CELL(6,OFFSET(INDIRECT("RC",FALSE),-1,0))

I'll add this link for more info on the other types of info that can be returned:  https://www.mrexcel.com/forum/excel-questions/20611-info-only-get-cell-arguments.html


问:
Sharing config between node app and client side javascript
I need to have some config object both in the node app and in the browser. Here is the path and the content of the config:

path: [app]/public/js/config.js

content:

```<code>var config = {
    "foo": "bar",
    "num": 42,
    "list": ["a","b","f"]
};
var isBrowser=new Function("try {return this===window;}catch(e){ return false;}");
if(!isBrowser) {
    module.exports = config;
}
</code>```

In my html I just add a script element and it works fine:

```<code><script src="/js/config.js"></script>
</code>```

In node app however I do not seem to have imported the object and I get an empty object:

```<code>var config = require('./public/js/config.js');
console.log('config:', config); // gives config: {}
</code>```

What am I doing wrong?

答:
Your isBrowser variable is assigned a function, but it is never executed.

Therefore it does not perform any environment detection.

Body:
I need to have some config object both in the node app and in the browser. Here is the path and the content of the config:

path: [app]/public/js/config.js

content:

var config = {
    "foo": "bar",
    "num": 42,
    "list": ["a","b","f"]
};
var isBrowser=new Function("try {return this===window;}catch(e){ return false;}");
if(!isBrowser) {
    module.exports = config;
}

In my html I just add a script element and it works fine:

In node app however I do not seem to have imported the object and I get an empty object:

var config = require('./public/js/config.js');
console.log('config:', config); // gives config: {}

What am I doing wrong?


问:
Splitting XML file into multiple files based on labels using python
I have a large xml file that contains the details of image annotations.  A sample of the same is as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="ScoreBoard-Vivon" color="#bf5786"/>
        <tag name="Perimeter-Vivon" color="#032585"/>
    </tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box top="253" left="166" width="56" height="24">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="255" left="229" width="61" height="21">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="290" width="58" height="23">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="361" width="56" height="20">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="417" width="63" height="22">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="486" width="63" height="20">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="504" left="329" width="51" height="29">
                <label>ScoreBoard-Vivon</label>
            </box>
        </image>
    </images>
</dataset>
</code>```

I want this file to be split based on their tag names.  This file has two tags viz - ScoreBoard and Perimeter.  I want to create two different xmls out of this for each tag.  The desired output would be as follows:

for ScoreBoard-Vivon.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="ScoreBoard-Vivon" color="#bf5786"/>
    </tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box top="504" left="329" width="51" height="29">
                <label>ScoreBoard-Vivon</label>
            </box>
        </image>
    </images>
</dataset>
</code>```

For Perimeter-Vivon.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="Perimeter-Vivon" color="#032585"/>
    </tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box top="253" left="166" width="56" height="24">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="255" left="229" width="61" height="21">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="290" width="58" height="23">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="361" width="56" height="20">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="417" width="63" height="22">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="486" width="63" height="20">
                <label>Perimeter-Vivon</label>
            </box>
        </image>
    </images>
</dataset>
</code>```

I have 350-400 such tags.  How can I split them into individual files.

New Example:

```<code><?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="Perimeter-SVT" color="#f9e99c"/>
        <tag name="Perimeter-Vivon" color="#032585"/>
        <tag name="ScoreBoard-Vivon" color="#bf5786"/>
        <tag name="Perimeter-StarSports" color="#12dadd"/>
    </tags>
    <images>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0011.jpg">
            <box top="505" left="327" width="56" height="29">
                <label>ScoreBoard-Vivon</label>
            </box>
            <box top="218" left="387" width="67" height="24">
                <label>Perimeter-SVT</label>
            </box>
        </image>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0005.jpg">
            <box top="254" left="159" width="64" height="23">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="255" left="225" width="61" height="20">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="285" width="63" height="23">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="253" left="357" width="58" height="24">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="424" width="56" height="25">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="256" left="484" width="65" height="23">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="507" left="326" width="58" height="26">
                <label>ScoreBoard-Vivon</label>
            </box>
        </image>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0009.jpg">
            <box top="249" left="400" width="59" height="29">
                <label>Perimeter-StarSports</label>
            </box>
        </image>
    </images>
</dataset>
</code>```

答:
One way would be to take the original XML, determine the <tags> in use, then make copies of the XML and remove all tags that don't match:

```<code>import xml.etree.ElementTree as ET
import copy

img_xml = """<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="ScoreBoard-Vivon" color="#bf5786"/>
        <tag name="Perimeter-Vivon" color="#032585"/>
    </tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box top="253" left="166" width="56" height="24">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="255" left="229" width="61" height="21">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="290" width="58" height="23">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="361" width="56" height="20">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="417" width="63" height="22">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="486" width="63" height="20">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="504" left="329" width="51" height="29">
                <label>ScoreBoard-Vivon</label>
            </box>
        </image>
    </images>
</dataset>
"""

root = ET.fromstring(img_xml)
tag_names = [tag.attrib['name'] for tag in root.find('tags')]

for tag_name in tag_names:
    root_copy = copy.deepcopy(root)

    # First remove unwanted tag
    for tag in root_copy.find('tags'):
        if tag.attrib['name'] != tag_name:
            tag.clear()

    # Now remove unwanted box
    for box in root_copy.findall("./images/image/box"):
        if box[0].text != tag_name:
            box.clear()

    ET.ElementTree(root_copy).write('{}.xml'.format(tag_name))
</code>```

Giving you two output XML files:

Perimeter-Vivon.xml

```<code><dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag /><tag color="#032585" name="Perimeter-Vivon" />
    </tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box height="24" left="166" top="253" width="56">
                <label>Perimeter-Vivon</label>
            </box>
            <box height="21" left="229" top="255" width="61">
                <label>Perimeter-Vivon</label>
            </box>
            <box height="23" left="290" top="254" width="58">
                <label>Perimeter-Vivon</label>
            </box>
            <box height="20" left="361" top="254" width="56">
                <label>Perimeter-Vivon</label>
            </box>
            <box height="22" left="417" top="254" width="63">
                <label>Perimeter-Vivon</label>
            </box>
            <box height="20" left="486" top="254" width="63">
                <label>Perimeter-Vivon</label>
            </box>
            <box /></image>
    </images>
</dataset>
</code>```

ScoreBoard-Vivon.xml

```<code><dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag color="#bf5786" name="ScoreBoard-Vivon" />
        <tag /></tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box /><box /><box /><box /><box /><box /><box height="29" left="329" top="504" width="51">
                <label>ScoreBoard-Vivon</label>
            </box>
        </image>
    </images>
</dataset>
</code>```

Body:
I have a large xml file that contains the details of image annotations.  A sample of the same is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="ScoreBoard-Vivon" color="#bf5786"/>
        <tag name="Perimeter-Vivon" color="#032585"/>
    </tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box top="253" left="166" width="56" height="24">
                Perimeter-Vivon
            </box>
            <box top="255" left="229" width="61" height="21">
                Perimeter-Vivon
            </box>
            <box top="254" left="290" width="58" height="23">
                Perimeter-Vivon
            </box>
            <box top="254" left="361" width="56" height="20">
                Perimeter-Vivon
            </box>
            <box top="254" left="417" width="63" height="22">
                Perimeter-Vivon
            </box>
            <box top="254" left="486" width="63" height="20">
                Perimeter-Vivon
            </box>
            <box top="504" left="329" width="51" height="29">
                ScoreBoard-Vivon
            </box>
        </image>
    </images>
</dataset>

I want this file to be split based on their tag names.  This file has two tags viz - ScoreBoard and Perimeter.  I want to create two different xmls out of this for each tag.  The desired output would be as follows:

for ScoreBoard-Vivon.xml

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="ScoreBoard-Vivon" color="#bf5786"/>
    </tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box top="504" left="329" width="51" height="29">
                ScoreBoard-Vivon
            </box>
        </image>
    </images>
</dataset>

For Perimeter-Vivon.xml

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="Perimeter-Vivon" color="#032585"/>
    </tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box top="253" left="166" width="56" height="24">
                Perimeter-Vivon
            </box>
            <box top="255" left="229" width="61" height="21">
                Perimeter-Vivon
            </box>
            <box top="254" left="290" width="58" height="23">
                Perimeter-Vivon
            </box>
            <box top="254" left="361" width="56" height="20">
                Perimeter-Vivon
            </box>
            <box top="254" left="417" width="63" height="22">
                Perimeter-Vivon
            </box>
            <box top="254" left="486" width="63" height="20">
                Perimeter-Vivon
            </box>
        </image>
    </images>
</dataset>

I have 350-400 such tags.  How can I split them into individual files.

New Example:

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="Perimeter-SVT" color="#f9e99c"/>
        <tag name="Perimeter-Vivon" color="#032585"/>
        <tag name="ScoreBoard-Vivon" color="#bf5786"/>
        <tag name="Perimeter-StarSports" color="#12dadd"/>
    </tags>
    <images>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0011.jpg">
            <box top="505" left="327" width="56" height="29">
                ScoreBoard-Vivon
            </box>
            <box top="218" left="387" width="67" height="24">
                Perimeter-SVT
            </box>
        </image>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0005.jpg">
            <box top="254" left="159" width="64" height="23">
                Perimeter-Vivon
            </box>
            <box top="255" left="225" width="61" height="20">
                Perimeter-Vivon
            </box>
            <box top="254" left="285" width="63" height="23">
                Perimeter-Vivon
            </box>
            <box top="253" left="357" width="58" height="24">
                Perimeter-Vivon
            </box>
            <box top="254" left="424" width="56" height="25">
                Perimeter-Vivon
            </box>
            <box top="256" left="484" width="65" height="23">
                Perimeter-Vivon
            </box>
            <box top="507" left="326" width="58" height="26">
                ScoreBoard-Vivon
            </box>
        </image>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0009.jpg">
            <box top="249" left="400" width="59" height="29">
                Perimeter-StarSports
            </box>
        </image>
    </images>
</dataset>

Body:
One way would be to take the original XML, determine the <tags> in use, then make copies of the XML and remove all tags that don't match:

import xml.etree.ElementTree as ET
import copy

img_xml = """<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="ScoreBoard-Vivon" color="#bf5786"/>
        <tag name="Perimeter-Vivon" color="#032585"/>
    </tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box top="253" left="166" width="56" height="24">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="255" left="229" width="61" height="21">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="290" width="58" height="23">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="361" width="56" height="20">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="417" width="63" height="22">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="486" width="63" height="20">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="504" left="329" width="51" height="29">
                <label>ScoreBoard-Vivon</label>
            </box>
        </image>
    </images>
</dataset>
"""

root = ET.fromstring(img_xml)
tag_names = [tag.attrib['name'] for tag in root.find('tags')]

for tag_name in tag_names:
    root_copy = copy.deepcopy(root)

    # First remove unwanted tag
    for tag in root_copy.find('tags'):
        if tag.attrib['name'] != tag_name:
            tag.clear()

    # Now remove unwanted box
    for box in root_copy.findall("./images/image/box"):
        if box[0].text != tag_name:
            box.clear()

    ET.ElementTree(root_copy).write('{}.xml'.format(tag_name))

Giving you two output XML files:

Perimeter-Vivon.xml

<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag /><tag color="#032585" name="Perimeter-Vivon" />
    </tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box height="24" left="166" top="253" width="56">
                <label>Perimeter-Vivon</label>
            </box>
            <box height="21" left="229" top="255" width="61">
                <label>Perimeter-Vivon</label>
            </box>
            <box height="23" left="290" top="254" width="58">
                <label>Perimeter-Vivon</label>
            </box>
            <box height="20" left="361" top="254" width="56">
                <label>Perimeter-Vivon</label>
            </box>
            <box height="22" left="417" top="254" width="63">
                <label>Perimeter-Vivon</label>
            </box>
            <box height="20" left="486" top="254" width="63">
                <label>Perimeter-Vivon</label>
            </box>
            <box /></image>
    </images>
</dataset>

ScoreBoard-Vivon.xml

<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag color="#bf5786" name="ScoreBoard-Vivon" />
        <tag /></tags>
    <images>
        <image file="/var/www/html/beacon.com/resources/videos/ST2_20170812/ST_2_20170812-0005.jpg">
            <box /><box /><box /><box /><box /><box /><box height="29" left="329" top="504" width="51">
                <label>ScoreBoard-Vivon</label>
            </box>
        </image>
    </images>
</dataset>


问:
blur an image by imagemagick
m a newbie in imagemagick...nd i wanted to know how to use some simple basic activities on an image by using imagemagic...i've also downloaded test project of imagemagic..but facin some problem..</p>

答:
You've put the tag "iphone" on this question, which makes me think you're blurring your image on a web server and then pulling it down to an iPhone.

There's a library I recently discovered but haven't had the opportunity to use yet that does image manipulations right on the phone. See here: http://code.google.com/p/simple-iphone-image-processing/

Title: blur an image by imagemagick


问:
Identify XPath from particular element
I'm working on a page, where page loads dynamically and the data gets added while scrolling. To identify the properties of an item, I identified the parent div, where to identify the address, I have to locate an XPath from the parent to span element.
Below is my DOM structure:

```<code><div class = "parentdiv">
    <div class = "search">
    <div class="header">
    <div class="data"></div>
    <div class="address-data">
      <div class="address" itemprop="address">
        <a itemprop="url" href="/search/Los-Angeles-CA-90025">
                <span itemprop="streetAddress">
                    Avenue
                </span>

                <br>
                <span itemprop="Locality">Los Angeles</span>
                <span itemprop="Region">CA</span>
            </a>
        </div>
        </div>
        </div>
    </div>
</div>
</div>
</code>```

Here I want to locate the three spans, where I' currently in parent div.
Can someone guide how to locate an element using XPath from particular div?

答:
You can try the following XPaths,

To locate the street address:

```<code>//div[@class="parentdiv"]/div/div/a/span[@itemprop="streetAddress"]
</code>```

To locate the locality/city:

```<code>//div[@class="parentdiv"]/div/div/a/span[@itemprop="Locality"]
</code>```

To locate the state:

```<code>//div[@class="parentdiv"]/div/div/a/span[@itemprop="Region"]
</code>```

Title: Identify XPath from particular element

Body:
I'm working on a page, where page loads dynamically and the data gets added while scrolling. To identify the properties of an item, I identified the parent div, where to identify the address, I have to locate an XPath from the parent to span element.
Below is my DOM structure:

                    Avenue

                Los Angeles
                CA

Here I want to locate the three spans, where I' currently in parent div.
Can someone guide how to locate an element using XPath from particular div?

Body:
You can try the following XPaths,

To locate the street address:

//div[@class="parentdiv"]/div/div/a/span[@itemprop="streetAddress"]

To locate the locality/city:

//div[@class="parentdiv"]/div/div/a/span[@itemprop="Locality"]

To locate the state:

//div[@class="parentdiv"]/div/div/a/span[@itemprop="Region"]


问:
React Native Firebase write user data after account creation
I'm currently working with Firebase and React Native I have come to a slight problem.

Reading the documentation for the: createUserWithEmailAndPassword:

On successful creation of the user account, this user will also be signed in to your application.

I was trying to work with the promise as follows:

```<code>firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(function(authData){
    this.writeUserData(authData.uid);
}).catch(function(error){
    console.warn(error)
});
</code>```

And my writeUserData() method:

```<code>writeUserData(the_uid) {
    console.warn("Writting data ")
    var today = new Date();
    firebase.database().ref('users/' + authData.uid + '/').set({
        name: this.state.name,
        birthday: this.state.date,
        email: this.state.email,
        registered: today
    });
}
</code>```

In the function however the console.warn is never fired hence the event isn't fired since the user is automatically logged in.

Problem: The .then isn't executed since user is logged in straight away.

Goal: Be able to add the user information (name, birthday, etc) after user creation before sign in.

答:
Okay understood you, the problem seems to be how you define a function in your .then statement. You should be using an Arrow function, like so -

```<code>firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
    .then((authData) => {
        this.writeUserData(authData.uid);
    }).catch(function(error){
        console.warn(error)
    });
</code>```

Body:
I'm currently working with Firebase and React Native I have come to a slight problem.

Reading the documentation for the: createUserWithEmailAndPassword:

On successful creation of the user account, this user will also be signed in to your application.

I was trying to work with the promise as follows:

firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(function(authData){
    this.writeUserData(authData.uid);
}).catch(function(error){
    console.warn(error)
});

And my writeUserData() method:

writeUserData(the_uid) {
    console.warn("Writting data ")
    var today = new Date();
    firebase.database().ref('users/' + authData.uid + '/').set({
        name: this.state.name,
        birthday: this.state.date,
        email: this.state.email,
        registered: today
    });
}

In the function however the console.warn is never fired hence the event isn't fired since the user is automatically logged in.

Problem: The .then isn't executed since user is logged in straight away.

Goal: Be able to add the user information (name, birthday, etc) after user creation before sign in.

Body:
Okay understood you, the problem seems to be how you define a function in your .then statement. You should be using an Arrow function, like so -

firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
    .then((authData) => {
        this.writeUserData(authData.uid);
    }).catch(function(error){
        console.warn(error)
    });