问:
Avoiding define macro when making a lot of similar method calls
The code below uses the #define macro. I'd like to avoid this but I don't see a way that uses C++ features and is more readable. The code is for testing a class ClassUnderTest that merges two instances of PoorLegacyClass into one. This PoorLegacyClass has many getters and setters and for testing purposes I need to call a lot of setters (or do I?).

In short, instead of writing

```<code>a.setValueX(20);
b.setValueX(30);
</code>```

I would like to write something like

```<code>set(a, b, ValueX, 20, 30);
// or
set<ValueX>(a, 20, b, 30);
// or even
set(a, b, &PoorLegacyClass::setValueX, 20, 30);
</code>```

Here is code similar to the code I use at the moment:

```<code>#include <boost/test/unit_test.hpp>

#include "ClassUnderTest.h"

BOOST_AUTO_TEST_SUITE(Test_ClassUnderTest);

#define SETTER_A_B(fieldname, valueA, valueB)\
        a.set##fieldname(valueA);\
        b.set##fieldname(valueB);

struct TestContext
{
    PoorLegacyClass a, b;
};

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description1, TestContext)
{
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(20 == result.getValueX());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description2, TestContext)
{
    SETTER_A_B(ValueY, 21, 37);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(21 + 37 == result.getValueY());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description3, TestContext)
{
    SETTER_A_B(ValueZ, 12, 83);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(12 + 83 == result.getValueZ());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description4, TestContext)
{
    SETTER_A_B(ValueY, 212, 37);
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(a.getValueY() == result.getValueY());
}

// more test cases that are similar to those above

BOOST_AUTO_TEST_SUITE_END();
</code>```

While I will refactor PoorLegacyClass in the future that is not the subject of this question. What I would like to know, though, is how to avoid using the #define macro.

答:
You could try this:

Use BOOST_FUSION_ADAPT_STRUCT to make a fusion sequence of your structure.

Then use the fusion::at_c<N> to access the Nth element and set it's value

Put a free function around the above to take the sequence and use the at_c<N> to access a member appropriately.

Should avoid the need for macros..

Body:
The code below uses the #define macro. I'd like to avoid this but I don't see a way that uses C++ features and is more readable. The code is for testing a class ClassUnderTest that merges two instances of PoorLegacyClass into one. This PoorLegacyClass has many getters and setters and for testing purposes I need to call a lot of setters (or do I?).

In short, instead of writing

a.setValueX(20);
b.setValueX(30);

I would like to write something like

set(a, b, ValueX, 20, 30);
// or
set<ValueX>(a, 20, b, 30);
// or even
set(a, b, &PoorLegacyClass::setValueX, 20, 30);

Here is code similar to the code I use at the moment:

#include <boost/test/unit_test.hpp>

#include "ClassUnderTest.h"

BOOST_AUTO_TEST_SUITE(Test_ClassUnderTest);

#define SETTER_A_B(fieldname, valueA, valueB)\
        a.set##fieldname(valueA);\
        b.set##fieldname(valueB);

struct TestContext
{
    PoorLegacyClass a, b;
};

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description1, TestContext)
{
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(20 == result.getValueX());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description2, TestContext)
{
    SETTER_A_B(ValueY, 21, 37);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(21 + 37 == result.getValueY());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description3, TestContext)
{
    SETTER_A_B(ValueZ, 12, 83);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(12 + 83 == result.getValueZ());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description4, TestContext)
{
    SETTER_A_B(ValueY, 212, 37);
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(a.getValueY() == result.getValueY());
}

// more test cases that are similar to those above

BOOST_AUTO_TEST_SUITE_END();

While I will refactor PoorLegacyClass in the future that is not the subject of this question. What I would like to know, though, is how to avoid using the #define macro.


来源: stackexchange

问:
Downscaling Video With FFMPEG - Setting Max Width and Height
I'm currently trying to use FFMPEG to scale down my video sources from various resolution down to a max width of 854 and a max height of 480. I want to scale the aspect ratio properly with a modulus/divder min of 2.

Currently this is what I got:
scale=-2:'min(ih\,480)'

This is for the height part only, but still need to figure out how to do the width part and to keep the -2 divider enabled for both. Any ideas? Thanks

ContentLicense: CC BY-SA 3.0

Body: Use scale=w='if(gt(dar,854/480),min(854,iw*sar),2*trunc(iw*sar*oh/ih/2))':h='if(gt(dar,854/480),2*trunc(ih*ow/iw/sar/2),min(480,ih))'


问:
How to make checkbox selected during rendering
I have already look and applied lots of the solution methods on web i.e. Check/Uncheck checkbox with javascript? but my problem is make the checkbox to be checked after page load. I use $(window).load(function () and $(document).ready(function () but none of them working. However, if I can set checked property in html of checkbox the problem will be solved. But I cannot set this property via a Javascript variable. I also tried by jQuery but the problem is related to setting this property after rendering of checkbox. Any idea to fix the problem?

```<code><input type="checkbox" class="form-check-input" id="chkAll" >

//Although the checkboz is already rendered at this stage I cannot set it
$(window).load(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});
</code>```

and

```<code>//As the checkbox is not rendering during page load this method is useless
$(document).ready(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});
</code>```

答:
You do not need any javascript. Your using the CheckBox() method which will correctly set the checked attribute based on the value of the boolean property your binding to. The issue is that your not binding to your property. Change the code in the view to

```<code>@Html.CheckBox("IsAll")
</code>```

and if the value of ViewBag.IsAll istrue` it will be checked, otherwise it will not.

Body:
I have already look and applied lots of the solution methods on web i.e. Check/Uncheck checkbox with javascript? but my problem is make the checkbox to be checked after page load. I use $(window).load(function () and $(document).ready(function () but none of them working. However, if I can set checked property in html of checkbox the problem will be solved. But I cannot set this property via a Javascript variable. I also tried by jQuery but the problem is related to setting this property after rendering of checkbox. Any idea to fix the problem?

<input type="checkbox" class="form-check-input" id="chkAll" >

//Although the checkboz is already rendered at this stage I cannot set it
$(window).load(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});

and

//As the checkbox is not rendering during page load this method is useless
$(document).ready(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});

Body:
You do not need any javascript. Your using the CheckBox() method which will correctly set the checked attribute based on the value of the boolean property your binding to. The issue is that your not binding to your property. Change the code in the view to

@Html.CheckBox("IsAll")

and if the value of ViewBag.IsAll istrue` it will be checked, otherwise it will not.


问:
.php downloads instead of opening in Chrome and FF
I'm using sftp to reach my folder on a server at uni. Both chrome and firefox would download my simple test.php instead of opening the page.

Is there any suggestion where should I look with the preferences to change this? (Ubuntu 16.04)

答: Your webserver isnt passing the php file to php for processing and is just sending it on as it would any other file.  You will need to ensure that your webserver is setup to handle php correctly be it php-fpm for apache and nginx or the php module for apache</p>


问:
What do people find so appealing about dynamic languages?
It seems that everybody is jumping on the dynamic, non-compiled bandwagon lately.  I've mostly only worked in compiled, static typed languages (C, Java, .Net).  The experience I have with dynamic languages is stuff like ASP (Vb Script), JavaScript, and PHP.  Using these technologies has left a bad taste in my mouth when thinking about dynamic languages.  Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime.  And even then, you may not notice an error, as it just creates a new variable, and assigns some default value.  I've also never seen intellisense work well in a dynamic language, since, well, variables don't have any explicit type.

What I want to know is, what people find so appealing about dynamic languages?  What are the main advantages in terms of things that dynamic languages allow you to do that can't be done, or are difficult to do in compiled languages.  It seems to me that we decided a long time ago, that things like uncompiled asp pages throwing runtime exceptions was a bad idea. Why is there is a resurgence of this type of code?  And why does it seem to me at least, that Ruby on Rails doesn't really look like anything you couldn't have done with ASP 10 years ago?

答:
For me, the advantage of dynamic languages is how much more readable the code becomes due to less code and functional techniques like Ruby's block and Python's list comprehension.

But then I kind of miss the compile time checking (typo does happen) and IDE auto complete. Overall, the lesser amount of code and readability pays off for me.

Another advantage is the usually interpreted/non compiled nature of the language. Change some code and see the result immediately. It's really a time saver during development.

Last but not least, I like the fact that you can fire up a console and try out something you're not sure of, like a class or method that you've never used before and see how it behaves. There are many uses for the console and I'll just leave that for you to figure out.

OwnerDisplayName: Kibbee

LastEditorDisplayName: kronoz

OwnerDisplayName: htanata

ContentLicense: CC BY-SA 2.5


问:
Create zip style file without compression
I know that there are many free and not so free compression libraries out there, but for the project i am working on, i need to be able to take file data from a stream and put it into some kind zip or pack file, but without compression, because i will need to access these files quickly without having to wait for them to decompress.

Anyone know how this could be approached, or if there are some libraries out there that do this that i am not aware of?

答:
Remember to profile first.  Your harddrive is much slower than your cpu or ram.  If the file is sitting on disk reading a smaller, compressed file will take less time than if you read an uncompressed blob.  The difference may well be more than the time it takes to decompress it.

Also the OS may cache the file in memory.  When that happens the harddrive is completely removed from the loop (transparent to you).  That could make the decompression time too costly.

I learned this "technique" when dealing with slow internet connections.  The client needed the data fast and we had cycles to spare.  Sending compressed packets increase the throughput/latency of the application.

OwnerDisplayName: Jason Miesionczek

OwnerDisplayName: Caspin

LastEditorDisplayName: Caspin


问:
Is there any way to convert Transport for London's TransXChange data to GTFS?
There used to be a tool by Google called Transxchange2GoogleTransit, but the project looks abandoned. It's not working with the latest NaPTAN data format which was released two years ago.

答:
This project appears to solve this problem, providing a simple way to produce combined GTFS data from TfL's Unified API:

https://github.com/CommuteStream/tflgtfs.git


问:
how to show UIImage file path on UILabel in objective c
I am new in iOS and I am facing problem regarding to show file path on UILabel. I am taking Image for gallery and I want to show Image name and its extension on UILabel.

My code is like this

Button Click...

```<code>UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    imgPanCard.image = image;
    [picker dismissModalViewControllerAnimated:YES];
}
</code>```

I need to show Image name and its extension on UILabel "No. File Chosen" How to do this.Thanks in Advance!

答:
I just change code like this</p>

```<code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
        NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];

        // define the block to call when we get the asset based on the url (below)
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
        {
            ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
            NSLog(@"[imageRep filename] : %@", [imageRep filename]);
            lblPanCard.text=[imageRep filename];
            [picker dismissViewControllerAnimated:NO completion:nil];
            imgPanCard.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        };

        // get the asset library and fetch the asset based on the ref url (pass in block above)
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];

}
</code>```

Body:
I am new in iOS and I am facing problem regarding to show file path on UILabel. I am taking Image for gallery and I want to show Image name and its extension on UILabel.

My code is like this

Button Click...

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    imgPanCard.image = image;
    [picker dismissModalViewControllerAnimated:YES];
}

I need to show Image name and its extension on UILabel "No. File Chosen" How to do this.Thanks in Advance!

Body:
I just change code like this

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
        NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];

        // define the block to call when we get the asset based on the url (below)
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
        {
            ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
            NSLog(@"[imageRep filename] : %@", [imageRep filename]);
            lblPanCard.text=[imageRep filename];
            [picker dismissViewControllerAnimated:NO completion:nil];
            imgPanCard.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        };

        // get the asset library and fetch the asset based on the ref url (pass in block above)
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];

}


问:
Edittext linespacing extra and cursor position issue
i am trying to make an Edittext with a good amount of line spacing. It is working but the cursor is not in the correct position. Look at the image below. As you can see the cursor is halfway in between the lines.
Here is the Edittext Code :-

```<code>     <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:fadingEdge="vertical"
            android:gravity="left|center_vertical"
            android:lineSpacingExtra="10dp"
            android:lineSpacingMultiplier="2"
            android:padding="18dp"
            android:scrollbars="vertical"
            android:textSize="22sp" >

            <requestFocus />
        </EditText>
</code>```

答:
There is another problem if you're using textCursorDrawble with lineSpacingExtra: when your app is running above Lollipop, because the line height won't be changed for the last line, if you defines a negative bottom padding in your custom textCursorDrawable, the cursor will be shrank in last line like this:

To achieve more dramatic effect, I set the lineSpacingExtra to 8dp, and a part of my custom textCursorDrawable is <padding android:bottom="-8dp"/>. As a result, you can see the small cursor appearing in last line.

Of course we don't like this. I searched this in Internet for hours and days, but no page helps. But don't worry for this if you saw this answer since I've solved it in my way, which is a little hacky but works well as far as I know.

The root cause of our problem is that we've set a bottom padding to the textCursorDrawable, made it shorter for all lines. Let's say the text size is 12dp, then the original line height is also 12dp(just make things easier). After we define a lineSpacingExtra="8dp", the line height will increase to 20dp. If we don't do anything to textCursorDrawable, the cursor height will also be 20dp now, which is longer than text size apparently, so we shorten it, cut the bottom 8dp by defining <padding android:bottom="-8dp"/> in custom textCursorDrawable shape xml file. However, above Lollipop, lineSpacingExtra is ignored for the last line, so the line height of that remains at 12dp. So does the cursor of last line if we don't use custom one. And then we cut 8dp of that and now we see a 4dp cursor, which is wrong, while the correct operation is stopping setting the -8dp bottom padding in custom textCursorDrawable.

So the solution is: use different textCursorDrawable for normal lines and last line, showing enough respect to special one.

Then, when should we change the textCursorDrawable? My answer is: when user clicks last line of your EditText. This is reasonable because the cursor can only appear after this operation(maybe not the last operation if user clicks "enter" after this, but that doesn't influence our solution).

Next step is listening for user's clicking on last line. My solution is crude:

```<code>mEditText.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            EditText et = (EditText) v;
            // lineSpacingExtra's unit is px.
            int lastLineHeight = (int) (et.getLineHeight() - et.getLineSpacingExtra());
            if (et.getHeight() - event.getY() <= lastLineHeight) {
                setTextCursorDrawable(et, lastLineCursorRes);
            } else {
                setTextCursorDrawable(et, normalCursorRes);
            }
            return true;
        }
        return false;
    }
});
</code>```

And This is the not elegant(but we have to) implementation for setTextCursorDrawable:

```<code>public void setTextCursorDrawable(EditText et, @DrawableRes int res) {
    try {
        Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
        f.setAccessible(true);
        f.set(et, res);
    } catch (Exception ignored) {}
}
</code>```

Finally, the special part of lastLineCursorRes:

<padding android:bottom="0dp"/>

OK, there you go. Please be noticed that I wrote this answer just after I tried on this solution and found it worked, which means I didn't check it very carefully. If you meet any problems with this solution, please comment.

REFERENCES

To know why lineSpacingExtra/Multiplier is ignored in last line of TextView and its subclasses, check: How LineSpace Affects StaticLayout Height in One Line Text, Android TextView 行间距解析(in Chinese) and StaticLayout源码解析(in Chinese).

Body:
i am trying to make an Edittext with a good amount of line spacing. It is working but the cursor is not in the correct position. Look at the image below. As you can see the cursor is halfway in between the lines.
Here is the Edittext Code :-

     <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:fadingEdge="vertical"
            android:gravity="left|center_vertical"
            android:lineSpacingExtra="10dp"
            android:lineSpacingMultiplier="2"
            android:padding="18dp"
            android:scrollbars="vertical"
            android:textSize="22sp" >

            <requestFocus />
        </EditText>

Body:
There is another problem if you're using textCursorDrawble with lineSpacingExtra: when your app is running above Lollipop, because the line height won't be changed for the last line, if you defines a negative bottom padding in your custom textCursorDrawable, the cursor will be shrank in last line like this:

To achieve more dramatic effect, I set the lineSpacingExtra to 8dp, and a part of my custom textCursorDrawable is <padding android:bottom="-8dp"/>. As a result, you can see the small cursor appearing in last line.

Of course we don't like this. I searched this in Internet for hours and days, but no page helps. But don't worry for this if you saw this answer since I've solved it in my way, which is a little hacky but works well as far as I know.

The root cause of our problem is that we've set a bottom padding to the textCursorDrawable, made it shorter for all lines. Let's say the text size is 12dp, then the original line height is also 12dp(just make things easier). After we define a lineSpacingExtra="8dp", the line height will increase to 20dp. If we don't do anything to textCursorDrawable, the cursor height will also be 20dp now, which is longer than text size apparently, so we shorten it, cut the bottom 8dp by defining <padding android:bottom="-8dp"/> in custom textCursorDrawable shape xml file. However, above Lollipop, lineSpacingExtra is ignored for the last line, so the line height of that remains at 12dp. So does the cursor of last line if we don't use custom one. And then we cut 8dp of that and now we see a 4dp cursor, which is wrong, while the correct operation is stopping setting the -8dp bottom padding in custom textCursorDrawable.

So the solution is: use different textCursorDrawable for normal lines and last line, showing enough respect to special one.

Then, when should we change the textCursorDrawable? My answer is: when user clicks last line of your EditText. This is reasonable because the cursor can only appear after this operation(maybe not the last operation if user clicks "enter" after this, but that doesn't influence our solution).

Next step is listening for user's clicking on last line. My solution is crude:

mEditText.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            EditText et = (EditText) v;
            // lineSpacingExtra's unit is px.
            int lastLineHeight = (int) (et.getLineHeight() - et.getLineSpacingExtra());
            if (et.getHeight() - event.getY() <= lastLineHeight) {
                setTextCursorDrawable(et, lastLineCursorRes);
            } else {
                setTextCursorDrawable(et, normalCursorRes);
            }
            return true;
        }
        return false;
    }
});

And This is the not elegant(but we have to) implementation for setTextCursorDrawable:

public void setTextCursorDrawable(EditText et, @DrawableRes int res) {
    try {
        Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
        f.setAccessible(true);
        f.set(et, res);
    } catch (Exception ignored) {}
}

Finally, the special part of lastLineCursorRes:

<padding android:bottom="0dp"/>

OK, there you go. Please be noticed that I wrote this answer just after I tried on this solution and found it worked, which means I didn't check it very carefully. If you meet any problems with this solution, please comment.

REFERENCES

To know why lineSpacingExtra/Multiplier is ignored in last line of TextView and its subclasses, check: How LineSpace Affects StaticLayout Height in One Line Text, Android TextView 行间距解析(in Chinese) and StaticLayout源码解析(in Chinese).


问:
Draw arrow with text outside axes
I want to draw an arrow with text that would stretch across several axes.  Reading http://matplotlib.org/users/annotations_guide.html

I got that far :

```<code>fig,ax = plt.subplots(2,3)
bbox_props = dict(boxstyle="rarrow,pad=0.2", fc="cyan", ec="b", lw=1)
t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)
</code>```

which makes

I found from text docs that bbox is a dictionary of Rectangle, which has width and height,  but when I set

```<code>bbox_props = dict(boxstyle="rarrow,pad=0.2", fc="cyan", ec="b", lw=1, width=3)
t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)
</code>```

I get a conflict :

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-255-006733283545> in <module>()
     13 # properties of a rectangle : http://matplotlib.org/api/patches_api.html#matplotlib.patches.Rectangle
     14
---> 15 t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)
     16 plt.savefig('example.png', bbox_inches='tight')

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/axes/_axes.py in text(self, x, y, s, fontdict, withdash, **kwargs)
    626         if fontdict is not None:
    627             t.update(fontdict)
--> 628         t.update(kwargs)
    629
    630         t.set_clip_path(self.patch)

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/text.py in update(self, kwargs)
    242         super(Text, self).update(kwargs)
    243         if bbox:
--> 244             self.set_bbox(bbox)  # depends on font properties
    245
    246     def __getstate__(self):

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/text.py in set_bbox(self, rectprops)
    514                                     bbox_transmuter=bbox_transmuter,
    515                                     transform=mtransforms.IdentityTransform(),
--> 516                                     **props)
    517         else:
    518             self._bbox_patch = None

TypeError: __init__() got multiple values for argument 'width'
</code>```

How can I control the size of my arrow with bbox ? Is there a way to extend it all the way to the right?

Thank you!
Chris

答:
An option would be to built our own width argument to a custom arrowstyle.

To this end we might subclass BoxStyle.RArrow and introduce a width argument in the newly created class MyRArrow.

The points of the arrow will then be offset by this width. In this simple example, width is in pixels.
Finally, we might register this new class as a boxstyle "myrarrow".

```<code>from matplotlib.patches import BoxStyle

class MyRArrow(BoxStyle.RArrow):
        def __init__(self, pad=0.3, width=220):
            self.width_ = width
            super(MyRArrow, self).__init__(pad)

        def transmute(self, x0, y0, width, height, mutation_size):
            p = BoxStyle.RArrow.transmute(self, x0, y0,
                                          width, height, mutation_size)
            x = p.vertices[:, 0]
            p.vertices[1:3, 0] = x[1:3] - self.width_
            p.vertices[0, 0]   = x[0]   + self.width_
            p.vertices[3:, 0]  = x[3:]  + self.width_
            return p

BoxStyle._style_list["myrarrow"] = MyRArrow
</code>```

We can now use this new style and specify a boxstyle="myrarrow,pad=0.2, width=150" as bbox keyword argument.

It then also makes sense to specify the arrow position in figure coordinates instead of axes coordinates.

```<code>import matplotlib.pyplot as plt

fig,ax = plt.subplots(2,3)
bbox_props = dict(boxstyle="myrarrow,pad=0.2, width=150", fc="cyan", ec="b", lw=1)
t = ax[0,1].text(0.5, 0.95, "Mag", ha="center", va="center",
                rotation=0, size=15, bbox=bbox_props, transform=fig.transFigure)

plt.show()
</code>```

Title: Draw arrow with text outside axes

Body:
I want to draw an arrow with text that would stretch across several axes.  Reading http://matplotlib.org/users/annotations_guide.html

I got that far :

fig,ax = plt.subplots(2,3)
bbox_props = dict(boxstyle="rarrow,pad=0.2", fc="cyan", ec="b", lw=1)
t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)

which makes

I found from text docs that bbox is a dictionary of Rectangle, which has width and height,  but when I set

bbox_props = dict(boxstyle="rarrow,pad=0.2", fc="cyan", ec="b", lw=1, width=3)
t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)

I get a conflict :

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-255-006733283545> in <module>()
     13 # properties of a rectangle : http://matplotlib.org/api/patches_api.html#matplotlib.patches.Rectangle
     14
---> 15 t = ax[0,1].text(-0.8, 1.2, "Mag", ha="center", va="center", rotation=0, size=15, bbox=bbox_props)
     16 plt.savefig('example.png', bbox_inches='tight')

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/axes/_axes.py in text(self, x, y, s, fontdict, withdash, **kwargs)
    626         if fontdict is not None:
    627             t.update(fontdict)
--> 628         t.update(kwargs)
    629
    630         t.set_clip_path(self.patch)

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/text.py in update(self, kwargs)
    242         super(Text, self).update(kwargs)
    243         if bbox:
--> 244             self.set_bbox(bbox)  # depends on font properties
    245
    246     def __getstate__(self):

/Users/chris/anaconda3/lib/python3.5/site-packages/matplotlib/text.py in set_bbox(self, rectprops)
    514                                     bbox_transmuter=bbox_transmuter,
    515                                     transform=mtransforms.IdentityTransform(),
--> 516                                     **props)
    517         else:
    518             self._bbox_patch = None

TypeError: __init__() got multiple values for argument 'width'

How can I control the size of my arrow with bbox ? Is there a way to extend it all the way to the right?

Thank you!
Chris

Body:
An option would be to built our own width argument to a custom arrowstyle.

To this end we might subclass BoxStyle.RArrow and introduce a width argument in the newly created class MyRArrow.

The points of the arrow will then be offset by this width. In this simple example, width is in pixels.
Finally, we might register this new class as a boxstyle "myrarrow".

from matplotlib.patches import BoxStyle

class MyRArrow(BoxStyle.RArrow):
        def __init__(self, pad=0.3, width=220):
            self.width_ = width
            super(MyRArrow, self).__init__(pad)

        def transmute(self, x0, y0, width, height, mutation_size):
            p = BoxStyle.RArrow.transmute(self, x0, y0,
                                          width, height, mutation_size)
            x = p.vertices[:, 0]
            p.vertices[1:3, 0] = x[1:3] - self.width_
            p.vertices[0, 0]   = x[0]   + self.width_
            p.vertices[3:, 0]  = x[3:]  + self.width_
            return p

BoxStyle._style_list["myrarrow"] = MyRArrow

We can now use this new style and specify a boxstyle="myrarrow,pad=0.2, width=150" as bbox keyword argument.

It then also makes sense to specify the arrow position in figure coordinates instead of axes coordinates.

import matplotlib.pyplot as plt

fig,ax = plt.subplots(2,3)
bbox_props = dict(boxstyle="myrarrow,pad=0.2, width=150", fc="cyan", ec="b", lw=1)
t = ax[0,1].text(0.5, 0.95, "Mag", ha="center", va="center",
                rotation=0, size=15, bbox=bbox_props, transform=fig.transFigure)

plt.show()


问:
Windows Forms with SQlite Project runs well in Visual-Studio while. But the setup file when installed shows an exception
```<code>See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.IO.FileNotFoundException: Could not load file or assembly
'SQLite.NET, Version=0.21.1869.3794, Culture=neutral,
PublicKeyToken=c273bd375e695f9c' or one of its dependencies. The system
cannot find the file specified.
File name: 'SQLite.NET, Version=0.21.1869.3794, Culture=neutral,
PublicKeyToken=c273bd375e695f9c'
   at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs
e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr
wparam, IntPtr lparam)

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value
[HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind
failure logging.
To turn this feature off, remove the registry value
[HKLM\Software\Microsoft\Fusion!EnableLog].

************** Loaded Assemblies **************
mscorlib
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
WindowsFormsApplication1
    Assembly Version: 1.0.0.0
    Win32 Version: 1.0.0.0
    CodeBase: file:///C:/Users/Public/Desktop/WindowsFormsApplication1.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
 file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/
v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
 file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/
v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Drawing
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
 file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/
v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System.Configuration
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/
v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Core
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Core/
v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
System.Xml
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/
v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.
</code>```

I am using SQlite database and installed everything required. The project is runs well in visual studio. But when the setup file is built and run on my machine it throws this exception.

And I just don't understand what is this warning message.Should I turn on the Assembly binding logging? or whatsoever?

答:
Can you please check whether your assembly 'SQLite.NET' property Copy Local is true.

if yes you can also check

```<code><dependentAssembly>
    <assemblyIdentity name="someAssembly"
      publicKeyToken="32ab4ba45e0a69a1"
      culture="en-us" />

    <bindingRedirect oldVersion="7.0.0.0" newVersion="8.0.0.0" />
  </dependentAssembly>
</code>```

Replace your assembly name and version in upper configuration.

Body:
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.IO.FileNotFoundException: Could not load file or assembly
'SQLite.NET, Version=0.21.1869.3794, Culture=neutral,
PublicKeyToken=c273bd375e695f9c' or one of its dependencies. The system
cannot find the file specified.
File name: 'SQLite.NET, Version=0.21.1869.3794, Culture=neutral,
PublicKeyToken=c273bd375e695f9c'
   at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs
e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr
wparam, IntPtr lparam)

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value
[HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind
failure logging.
To turn this feature off, remove the registry value
[HKLM\Software\Microsoft\Fusion!EnableLog].

************** Loaded Assemblies **************
mscorlib
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
WindowsFormsApplication1
    Assembly Version: 1.0.0.0
    Win32 Version: 1.0.0.0
    CodeBase: file:///C:/Users/Public/Desktop/WindowsFormsApplication1.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
 file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/
v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
 file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/
v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Drawing
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
 file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/
v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System.Configuration
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/
v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Core
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Core/
v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
System.Xml
    Assembly Version: 4.0.0.0
    Win32 Version: 4.6.1087.0 built by: NETFXREL4STAGE
    CodeBase:
file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/
v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.

I am using SQlite database and installed everything required. The project is runs well in visual studio. But when the setup file is built and run on my machine it throws this exception.

And I just don't understand what is this warning message.Should I turn on the Assembly binding logging? or whatsoever?

Body:
Can you please check whether your assembly 'SQLite.NET' property Copy Local is true.

if yes you can also check

<dependentAssembly>
    <assemblyIdentity name="someAssembly"
      publicKeyToken="32ab4ba45e0a69a1"
      culture="en-us" />

    <bindingRedirect oldVersion="7.0.0.0" newVersion="8.0.0.0" />
  </dependentAssembly>

Replace your assembly name and version in upper configuration.


问:
How to access the nested JSON objects
I want to access nested JSON object values by iterating.

I tried console.log(test[0].Invoice[0].Cost.NO[0]); but it's not working.

var test = [{
  "Invoice": {
    "NO": "869",
    "$$hashKey": "object:186"
  },
  "Cost": [{
    "NO": 183,
    "Amnt": 100
  }, {
    "NO": 184,
    "Amnt": 200
  }]
}, {
  "Invoice": {
    "NO": "698",
    "$$hashKey": "object:189"
  },
  "Cost": [{
    "NO": 110,
    "Amnt": 150
  }, {
    "NO": 142,
    "Amnt": 263
  }]
}];

console.log(test[0].Invoice[0].Cost.NO[0]);```

答:
test is an array thus you need to iterate over it.

Each iteration will give you an object with 2 properties : Invoice and Cost

Invoice is again an object thus you only need to access the property you need

Cost is an array thus you need to iterate each items which are objects

var test = [{
  "Invoice": {
    "NO": "869",
    "$$hashKey": "object:186"
  },
  "Cost": [{
    "NO": 183,
    "Amnt": 100
  }, {
    "NO": 184,
    "Amnt": 200
  }]
}, {
  "Invoice": {
    "NO": "698",
    "$$hashKey": "object:189"
  },
  "Cost": [{
    "NO": 110,
    "Amnt": 150
  }, {
    "NO": 142,
    "Amnt": 263
  }]
}];

test.forEach(t=>{
  console.log("Invoice N°: " + t.Invoice.NO);
  t.Cost.forEach(c=>{
    console.log("- Cost N°: "+ c.NO + " - Amount: " + c.Amnt);
  });
});```

Title: How to access the nested JSON objects


问:
Rendered nodes overlap in visjs network graph
I render a graph using visjs. The shape of the nodes are of type dot. Each node is given a custom size using the size attribute.

When the graph is rendered some of the nodes overlap. So the graph looks like in the following picture:

I expected a graph like the this picture is showing:

What am I doing wrong?

答:
Try to use the physics configuration.

see this example of visjs.

GOOD LUCK.


问:
How do I make the below UI completely responsive
Please take a look at this design

Below is my html, currently only for 2 legs/flights but I should be able to design for upto 5 legs.

For now, I've given a percentage width to the lines in between, the rest of the elements have a fixed widths.

```<code><div class="roster-steps">

                                <span class="roster-points">DOH</span>
                                <span class="roster-meta-bottom-step-one font-size-065">E17 MAR 10:30</span>
                                <span class="fa  fa-circle-thin fa-lg"></span>

                                <span class="o-arrow"><hr class="hr-custom-three"></span>

                                <span><i class="fa fa-plane roster-points" ></i></span>
                                <span class="roster-meta-step2-top font-size-065">QR 2345 A360</span>
                                <span class="roster-meta-bottom-step-two font-size-065">10:30 hrs</span>
                                <span class="roster-meta-bottom-step-twosub font-size-065"><span class="two-sub1" >OP</span><span class="two-sub2">B</span></span>

                                <span class="arrow-o"><hr class="hr-custom-three" ></span>

                                <span class="fa  fa-circle-thin fa-lg"></span>
                                <span class="roster-points">LHR</span>
                                <span class="roster-meta-bottom-step-three font-size-065"><i class="fa fa-plane"></i> E17 MAR 16:30</span>
                                <span class="roster-meta-bottom-step-threesub font-size-065"><i class="fa fa-plane fa-rotate-90"></i> E17 MAR 17:30</span>
                                <span class="fa  fa-circle-thin fa-lg"></span>

                                <span class="o-arrow"><hr class="hr-custom-three" ></span>

                                <span><i class="fa fa-taxi roster-points" ></i></span>
                                <span class="roster-meta-step4-top font-size-065">TAXI</span>
                                <span class="roster-meta-bottom-step-four font-size-065">1:30 hrs</span>
                                <span class="roster-meta-bottom-step-foursub font-size-065"><span class="four-sub1" >DH</span></span>

                                <span class="arrow-o"><hr class="hr-custom-three" ></span>

                                <span class="fa  fa-circle-thin fa-lg"></span>
                                <span class="roster-points">LGW</span>
                                <span class="roster-meta-bottom-step-one font-size-065">E17 MAR 20:00</span>

                            </div>
</code>```

Any guidance in the right direction is highly appreciated.

Edit:

Can't make it vertical now as the design team has signed off on this.

So it was super easy doing this with css grid layout:

Check it out

Note: To view it in chrome You need to  turn on the experimental flag.
First load the chrome://flags URL and scroll down to the option to Enable     experimental Web Platform features

But since css grid layout is still not supported in major browsers, is there a more reliable alternative?

Thanks.

答:
You should use media queries. Something like this :

@media screen and (max-width:450px){
  /**
  your css code for mobile version of website
  **/
}```

You can learn more about responsiveness from here : responsive website css

Body:
Please take a look at this design

Below is my html, currently only for 2 legs/flights but I should be able to design for upto 5 legs.

For now, I've given a percentage width to the lines in between, the rest of the elements have a fixed widths.

                                DOH
                                E17 MAR 10:30

                                QR 2345 A360
                                10:30 hrs
                                OPB

                                LHR
                                 E17 MAR 16:30
                                 E17 MAR 17:30

                                TAXI
                                1:30 hrs
                                DH

                                LGW
                                E17 MAR 20:00

Any guidance in the right direction is highly appreciated.

Edit:

Can't make it vertical now as the design team has signed off on this.

So it was super easy doing this with css grid layout:

Check it out

Note: To view it in chrome You need to  turn on the experimental flag.
First load the chrome://flags URL and scroll down to the option to Enable     experimental Web Platform features

But since css grid layout is still not supported in major browsers, is there a more reliable alternative?

Thanks.

Body:
You should use media queries. Something like this :

@media screen and (max-width:450px){
  /**
  your css code for mobile version of website
  **/
}

You can learn more about responsiveness from here : responsive website css


问:
Apache - how to get REMOTE_USER variable
Previously I used the IIS server as PHP server. Currently, it is the apache.

On IIS I could access to the variable $_SERVER ['REMOTE_USER'] which returns the username and domain (eg domain\user) but after installing XAMPP this variable is not available.

What I should do to get this variable get again?

My app is on local network with no-internet connection

答: I battled with this for a long time, it turned out that I had to install VC redistributable to make it work.</p>


问:
 does not display local images in WordPress header.php and index.php
I am trying to use a simple <img src= tag to link to a favicon.ico in my header.php file and a .png logo in my index.php file in my WordPress theme, but without any luck. I've tested the link by replacing it with a hyperlink to an image hosted online, which works and proves that the <img src= tag isn't broken, but obviously I would prefer to be able to have the images linked within an internal img folder in the theme. The background image I have used in my site (which is linked in the bootstrap.css and is in the same 'img' folder as the two images I am trying to link to) works perfectly. I've tried copying the formatting of that href link but it doesn't seem to work either.

I've tried many variations of 'img/favicon.ico', '/img/favicon.ico', '../img/favicon.ico' but none of them worked to link to the image files in both cases.

Here is my code for the header.php file:

```<code><?php
/**
 * The header for our theme
 *
 * This is the template that displays all of the <head> section and everything up until <div id="content">
 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package wpbootstrap-sofa
 */

?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="icon" href='../img/favicon.ico'>
<!-- Bootstrap core CSS -->

<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->

<!-- Custom styles for this template -->

<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
    <?php wp_head(); ?>
</head>

<body>

    <div class="background">

        <nav class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="index.html">home</a>
                </div>
                <div id="navbar" class="collapse navbar-collapse">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="index.html">home</a>
                        </li>
                        <li><a href="#about">about</a>
                        </li>
                        <li><a href="#blog">blog posts</a>
                        </li>
                        <li><a href="#submit">submit</a>
                        </li>
                        <li><a href="#events">events</a>
                        </li>
                        <li><a href="#mailing">mailing list</a>
                        </li>
                        <li><a href="#contact">contact</a>
                        </li>
                        <li><a href="http://uqsofa.bigcartel.com/" target="_blank">store</a>
                        </li>
                    </ul>
                </div>
                <!--/.collapse navbar-collapse -->
            </div>
        </nav>

        <div class="container">
</code>```

And here is the code for the index.php file:

```<code><?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package wpbootstrap-sofa
 */

get_header(); ?>

<div class="starter-template">
    <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-3">
        <div class="center-block">
            <a href="index.html">
                    <img src='../img/sofa-logo.png' class="img-responsive center-block" alt="UQ SoFA logo">
            </a>
        </div>
        <!-- /.center-block -->
    </div>
    </div>
        <div class="row">
                <div class="col-xs-0 col-sm-0 col-md-4 col-lg-4 col-xl-4">
                        <div class="navbar-collapse collapse sidebar-navbar-collapse">
                                <ul class="nav navbar-nav">
                                    <li class="active"><a href="index.html">home</a>
                                    </li>
                                    <li><a href="#about">about</a>
                                    </li>
                                    <li><a href="#blog">blog posts</a>
                                    </li>
                                    <li><a href="#submit">submit</a>
                                    </li>
                                    <li><a href="#events">events</a>
                                    </li>
                                    <li><a href="#mailing">mailing list</a>
                                    </li>
                                    <li><a href="#contact">contact</a>
                                    </li>
                                    <li><a href="http://uqsofa.bigcartel.com/" target="_blank">store</a>
                                    </li>
                                </ul>
                        </div>
                        <!--/.collapse navbar-collapse -->
                    </div>
                    <!-- /.col-xs-0 col-sm-0 col-md-4 col-lg-4 col-xl-4 -->

                <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
                        <div class="panel panel-default">
                                <div class="panel-body">SoFA at Market Day</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">Cut Thumb ARI</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">GoMA Talks</div>
                        </div>
                        <!-- /.panel panel-default-->
                </div>
                <!-- /.col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4-->

                <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
                        <div class="panel panel-default">
                                <div class="panel-body">Interview with...</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">Lecture by...</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">Post #474</div>
                        </div>
                        <!-- /.panel panel-default-->
                </div>
                <!-- /.col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4-->
        </div>
        <!-- /.row-->
</div>
<!-- /.starter-template-->

</div>
<!-- /.container -->

</div>
<!-- /.background -->

<?php
get_footer();?>
</code>```

Linked here is a screenshot of the configuration of my theme's folders, including the 'img' folder where the images are contained.

Any help that could be provided would be much appreciated.

答:
Please use it as follow :--

```<code><img src="<?php echo get_template_directory_uri(); ?>/img/favicon.ico">
</code>```

I hope it will works for you.

Title: <img src=...> does not display local images in WordPress header.php and index.php

Body:
I am trying to use a simple <img src= tag to link to a favicon.ico in my header.php file and a .png logo in my index.php file in my WordPress theme, but without any luck. I've tested the link by replacing it with a hyperlink to an image hosted online, which works and proves that the <img src= tag isn't broken, but obviously I would prefer to be able to have the images linked within an internal img folder in the theme. The background image I have used in my site (which is linked in the bootstrap.css and is in the same 'img' folder as the two images I am trying to link to) works perfectly. I've tried copying the formatting of that href link but it doesn't seem to work either.

I've tried many variations of 'img/favicon.ico', '/img/favicon.ico', '../img/favicon.ico' but none of them worked to link to the image files in both cases.

Here is my code for the header.php file:

<?php
/**
 * The header for our theme
 *
 * This is the template that displays all of the  section and everything up until

 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package wpbootstrap-sofa
 */

?><!DOCTYPE html>
<html <?php language_attributes(); ?>>

<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="icon" href='../img/favicon.ico'>

    <?php wp_head(); ?>

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        Toggle navigation

                    </button>
                    home

home

about

blog posts

submit

events

mailing list

contact

store

And here is the code for the index.php file:

<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package wpbootstrap-sofa
 */

get_header(); ?>

home

about

blog posts

submit

events

mailing list

contact

store

SoFA at Market Day

Cut Thumb ARI

GoMA Talks

Interview with...

Lecture by...

Post #474

<?php
get_footer();?>

Linked here is a screenshot of the configuration of my theme's folders, including the 'img' folder where the images are contained.

Any help that could be provided would be much appreciated.

Body:
Please use it as follow :--

<img src="<?php echo get_template_directory_uri(); ?>/img/favicon.ico">

I hope it will works for you.


问:
DB connectivity using angular, php, mysql
Hi I am having some trouble with a small project. It's my first time using mySQL and PHP so I'm just trying to get connectivity for now. I have followed some tutorials and I cannot connect to the database, I am getting the "Sorry! Data Couldnt be inserted!" error from my php script at the bottom of index.html.

I also have a password on the database for the root user however even when i type this in the php file it still wont work.

Any help is much appreciated guys.

index.html:

 <!DOCTYPE html>

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></link>

            Email
            <input type ="text" name="email" ng-model="email" class="form-control"/>

             Password
            <input type ="text" name="password" ng-model="password" class="form-control"/>

            <input type="submit" name="btnInsert" ng-click="insertData()" value="ADD"/>

 ```
</div>
</div>
</p>

<p>and my insert.php:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
//insert.php

$data = json_decode(file_get_contents("php://input"));

    $email =  $data->email;
    $password = $data->password;

    mysql_connect("localhost","root","");
    mysql_select_db("test");

    mysql_query ("INSERT INTO 'test_user'('email', 'password') VALUES ('".$email."','".$password."')") or die(mysql_error());

    echo $email. " " .$password;

/*
    if(mysqli_query($connect, $query)){
        echo "User inserted...";
    }
    else{
        echo "User not inserted...";
    }
*/

#mysqli_real_escape_string($connect,
#mysqli_real_escape_string($connect,
?></code>```

答:
It's my first time using mySQL and PHP

But you seem to be using a very old version of PHP (the mysql_ extension is deprecated).

I'm not familiar with Angular but it looks like your code relies on Angular to determine if the PHP script ran as intended. Angular can't base that decision on the content sent by your script, therefore it must be basing its decision on the HTTP status returned by your script (which has no debugging in it). I expecting your PHP code is crashing and burning before it gets to run the insert.

I suggest you:

1) build a test rig using a textare and NO javascript to fire a request at your insert.php script

2) amend your PHP script so that it
  - captures more information about the processing
  - uses appropriate error reporting and ensure your error logging is working
  - presents the (appropriate) details of the actions it took in a parseable format (i.e. JSON)

3) read your log files - for both PHP and MySQL (you might want to do this before going to the trouble of changing/verifying your logging as described above)

4) read up on SQL injection

Body:
Hi I am having some trouble with a small project. It's my first time using mySQL and PHP so I'm just trying to get connectivity for now. I have followed some tutorials and I cannot connect to the database, I am getting the "Sorry! Data Couldnt be inserted!" error from my php script at the bottom of index.html.

I also have a password on the database for the root user however even when i type this in the php file it still wont work.

Any help is much appreciated guys.

index.html:

 <!DOCTYPE html>

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></link>

            Email
            <input type ="text" name="email" ng-model="email" class="form-control"/>

             Password
            <input type ="text" name="password" ng-model="password" class="form-control"/>

            <input type="submit" name="btnInsert" ng-click="insertData()" value="ADD"/>

and my insert.php:

<?php
//insert.php

$data = json_decode(file_get_contents("php://input"));

    $email =  $data->email;
    $password = $data->password;

    mysql_connect("localhost","root","");
    mysql_select_db("test");

    mysql_query ("INSERT INTO 'test_user'('email', 'password') VALUES ('".$email."','".$password."')") or die(mysql_error());

    echo $email. " " .$password;

/*
    if(mysqli_query($connect, $query)){
        echo "User inserted...";
    }
    else{
        echo "User not inserted...";
    }
*/

#mysqli_real_escape_string($connect,
#mysqli_real_escape_string($connect,
?>


问:
Eclipse java debugging: source not found
While debugging a java app in eclipse I receive a "Source not found" error in two cases:

Stepping in to a file in a different project which is already imported

Stepping in to a file in an installed maven repository

The files are there, but eclipse won't step into them, instead it shows a button to "attach source"

I tried attaching (which opened a dialog to define a variable?!) and eclipse did jump to the file, but the debugger could not inspect any variables there. Also manually attaching the source for each dependency isn't practical, as in my case there are thousands of dependency files.

Why is this happening, and how can it be resolved?

答:
I was facing the same issue,I followed the bellow steps.

Window => Preferences => Java => Installed JREs,

You see in the above screen Jre1.8.0_12 is selected.

select the JRE you are using and click Edit. Now You should see the bellow screen.

Click on the directory, browse for Jdk, It should look like bellow screen.

click ok, and its done

ContentLicense: CC BY-SA 4.0


问:
SQL display total on the first row only
I want to display my data like this</p>

```<code>Name             Product         Amount     Total
_______________________________________________
John Smith     Burger          60.00      100.00
John Smith     Fries           40.00
Michael Smith  Burger          60.00      60.00
</code>```

答:
You can do this using window functions, but you have to be very careful.  The problem is the ordering of the results and the definition oft he first row.

Let me attempt a stable sort using name, amount, and product:

```<code>select name, amount, product,
       (case when row_number() over (partition by name order by amount desc, product) = 1
             then sum(amount) over (partition by name)
        end) as total
from t
order by name, amount desc, product;
</code>```

It is very important to have the same order by keys in the outer query and for the window functions.

Title: SQL display total on the first row only

Body:
I want to display my data like this

Name             Product         Amount     Total
_______________________________________________
John Smith     Burger          60.00      100.00
John Smith     Fries           40.00
Michael Smith  Burger          60.00      60.00

Body:
You can do this using window functions, but you have to be very careful.  The problem is the ordering of the results and the definition oft he first row.

Let me attempt a stable sort using name, amount, and product:

select name, amount, product,
       (case when row_number() over (partition by name order by amount desc, product) = 1
             then sum(amount) over (partition by name)
        end) as total
from t
order by name, amount desc, product;

It is very important to have the same order by keys in the outer query and for the window functions.


问:
Multiple threads accessing a collection
I have the following scenario.

I have a queue that I receive messages from. When a message comes in a new thread is created to deal with it.

This thread takes the message and adds it to a collection. It then checks if the collection contains 100 items and if it does it sends them elsewhere and clears the collection.

I can't use a regular list because I get collection is modified, enumeration can't continue errors. So I need to use a thread safe collection.

My worry here though is, one thread writes to it and its the 100th item, while it's sending them off elsewhere another thread adds to the collection. Making it 101 items, the thread that triggered the 100th then clears it and I lose an item.

I can't use a concurrent bag, because it has no clear, I can't iterate the bag and remove 1 by 1 as messages might be coming in and being added quicker than it can remove and it will never end.

ConcurrentStack has a clear, but would that work in this scenario?

Some code to demonstrate what I mean, HandleMeasurementMessage happens on a new thread for each message.

```<code>private static readonly ConcurrentStack<EventHubDatum> EventHubDataBatch = new ConcurrentStack<EventHubDatum>();

private static void HandleMeasurementMessage(IMessage<MessageEnvelope> msg)
{
    /* Do a bunch of stuff to msg */

   EventHubDataBatch.Push(eventHubDatum);

   if(EventHubDataBatch.Count == 100)
   {
      /* Send them off*/
      EventHubDatabatch.Clear();
   }
}
</code>```

Wierdly, the problem with the enumeration being modified only occurs if I'm not running it via the debugger in VS2015. The program runs for an hour or so just fine. If I turn off the debugger, I get these enumeration errors which is why I'm trying to switch to a threadsafe collection. I'm just not sure which one is appropriate.

Code that calls HandleMeasurementMessage

```<code>_busSingle.Consume<MessageEnvelope>(_queueMeasurement, (msg, MessageReceivedInfo) => Task.Factory.StartNew(() =>
            {
                try
                {
                    HandleMeasurementMessage(msg);
                }
                catch (Exception ex)
                {
                    /* Logging stuff*/
                }
            }));
</code>```

答:
Use a synchronisation object like AutoResetEvent to only allow one thread to access the collection at a time.

Example usage:

```<code>static AutoResetEvent MeasureMessageEvent = new AutoResetEvent(true);

private static void HandleMeasurementMessage(IMessage<MessageEnvelope> msg)
{
    /* Do a bunch of stuff to msg */

    // Wait for exclusive access
    MeasureMessageEvent.WaitOne();

    EventHubDataBatch.Push(eventHubDatum);

    if(EventHubDataBatch.Count == 100)
    {
       /* Send them off*/
       EventHubDatabatch.Clear();
    }

    // Release exclusive access
    MeasureMessageEvent.Set();
}
</code>```

Title: Multiple threads accessing a collection

Body:
I have the following scenario.

I have a queue that I receive messages from. When a message comes in a new thread is created to deal with it.

This thread takes the message and adds it to a collection. It then checks if the collection contains 100 items and if it does it sends them elsewhere and clears the collection.

I can't use a regular list because I get collection is modified, enumeration can't continue errors. So I need to use a thread safe collection.

My worry here though is, one thread writes to it and its the 100th item, while it's sending them off elsewhere another thread adds to the collection. Making it 101 items, the thread that triggered the 100th then clears it and I lose an item.

I can't use a concurrent bag, because it has no clear, I can't iterate the bag and remove 1 by 1 as messages might be coming in and being added quicker than it can remove and it will never end.

ConcurrentStack has a clear, but would that work in this scenario?

Some code to demonstrate what I mean, HandleMeasurementMessage happens on a new thread for each message.

private static readonly ConcurrentStack<EventHubDatum> EventHubDataBatch = new ConcurrentStack<EventHubDatum>();

private static void HandleMeasurementMessage(IMessage<MessageEnvelope> msg)
{
    /* Do a bunch of stuff to msg */

   EventHubDataBatch.Push(eventHubDatum);

   if(EventHubDataBatch.Count == 100)
   {
      /* Send them off*/
      EventHubDatabatch.Clear();
   }
}

Wierdly, the problem with the enumeration being modified only occurs if I'm not running it via the debugger in VS2015. The program runs for an hour or so just fine. If I turn off the debugger, I get these enumeration errors which is why I'm trying to switch to a threadsafe collection. I'm just not sure which one is appropriate.

Code that calls HandleMeasurementMessage

_busSingle.Consume<MessageEnvelope>(_queueMeasurement, (msg, MessageReceivedInfo) => Task.Factory.StartNew(() =>
            {
                try
                {
                    HandleMeasurementMessage(msg);
                }
                catch (Exception ex)
                {
                    /* Logging stuff*/
                }
            }));

Body:
Use a synchronisation object like AutoResetEvent to only allow one thread to access the collection at a time.

Example usage:

static AutoResetEvent MeasureMessageEvent = new AutoResetEvent(true);

private static void HandleMeasurementMessage(IMessage<MessageEnvelope> msg)
{
    /* Do a bunch of stuff to msg */

    // Wait for exclusive access
    MeasureMessageEvent.WaitOne();

    EventHubDataBatch.Push(eventHubDatum);

    if(EventHubDataBatch.Count == 100)
    {
       /* Send them off*/
       EventHubDatabatch.Clear();
    }

    // Release exclusive access
    MeasureMessageEvent.Set();
}


问:
How to pass Json string with variable in c#?
```<code>string a;

string b;

string jSonContent = @"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}";
</code>```

I want a instead of summary and b instead of modified. It works if I replace summary but gives errors if I replace both.

The edited code is, string jSonContent = @"{""fields"":{""summary"":"+ "\""+ a+ "\"" +" , ""description"": "+ "\""+ b+ "\"" +"}}"; It's not giving any error, summary field is getting updated, but the description field is not.

Please revert. Thanks!

答:
Use string fromat $""

String format allow you to replace values from your variables into a string. E.g.

```<code>string name = "Bruno";
string result = $"My name is {name}";
Console.WriteLine(result);
</code>```

The output will be

```<code>My name is Bruno
</code>```

In your case you just have to escape the json brackets with a double bracket {{

```<code>string a = "this is a sumary";
string b = "this is a description";
string jSonContent = $"{{\"fields\":{{\"summary\":\"{a}\" , \"description\": \"{b}\"}}}}";

Console.WriteLine(jSonContent);
</code>```

the output is

```<code>{"fields":{"summary":"this is a sumary" , "description": "this is a description"}}
</code>```

However I strongly advise to not build your json strings manually, use Json.NET or any other NuGet Packages.

Body:
string a;

string b;

string jSonContent = @"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}";

I want a instead of summary and b instead of modified. It works if I replace summary but gives errors if I replace both.

The edited code is, string jSonContent = @"{""fields"":{""summary"":"+ "\""+ a+ "\"" +" , ""description"": "+ "\""+ b+ "\"" +"}}"; It's not giving any error, summary field is getting updated, but the description field is not.

Please revert. Thanks!

Body:
Use string fromat $""

String format allow you to replace values from your variables into a string. E.g.

string name = "Bruno";
string result = $"My name is {name}";
Console.WriteLine(result);

The output will be

My name is Bruno

In your case you just have to escape the json brackets with a double bracket {{

string a = "this is a sumary";
string b = "this is a description";
string jSonContent = $"{{\"fields\":{{\"summary\":\"{a}\" , \"description\": \"{b}\"}}}}";

Console.WriteLine(jSonContent);

the output is

{"fields":{"summary":"this is a sumary" , "description": "this is a description"}}

However I strongly advise to not build your json strings manually, use Json.NET or any other NuGet Packages.


答:
You have written wrong statement

test[0].Invoice[0].Cost.NO[0]

It should be as below

```<code> test[0].Cost[0].NO
</code>```

Because Invoice and Cost are properties of same json object.

try out this

  var test = [{ "Invoice": { "NO": "869", "$$hashKey": "object:186" }, "Cost": [{ "NO": 183, "Amnt": 100 }, { "NO": 184, "Amnt": 200 }] }, { "Invoice": { "NO": "698", "$$hashKey": "object:189" }, "Cost": [{ "NO": 110, "Amnt": 150 }, { "NO": 142, "Amnt": 263 }] }];

  console.log(test[0].Cost[0]);
 console.log(test[0].Cost[0].NO);

 ```

Title: How to access the nested JSON objects

Body:
I want to access nested JSON object values by iterating.

I tried console.log(test[0].Invoice[0].Cost.NO[0]); but it's not working.

var test = [{
  "Invoice": {
    "NO": "869",
    "$$hashKey": "object:186"
  },
  "Cost": [{
    "NO": 183,
    "Amnt": 100
  }, {
    "NO": 184,
    "Amnt": 200
  }]
}, {
  "Invoice": {
    "NO": "698",
    "$$hashKey": "object:189"
  },
  "Cost": [{
    "NO": 110,
    "Amnt": 150
  }, {
    "NO": 142,
    "Amnt": 263
  }]
}];

console.log(test[0].Invoice[0].Cost.NO[0]);

Body:
You have written wrong statement

test[0].Invoice[0].Cost.NO[0]

It should be as below

 test[0].Cost[0].NO

Because Invoice and Cost are properties of same json object.

try out this

  var test = [{ "Invoice": { "NO": "869", "$$hashKey": "object:186" }, "Cost": [{ "NO": 183, "Amnt": 100 }, { "NO": 184, "Amnt": 200 }] }, { "Invoice": { "NO": "698", "$$hashKey": "object:189" }, "Cost": [{ "NO": 110, "Amnt": 150 }, { "NO": 142, "Amnt": 263 }] }];

  console.log(test[0].Cost[0]);
 console.log(test[0].Cost[0].NO);


问:
.php downloads instead of opening in Chrome and FF
I'm using sftp to reach my folder on a server at uni. Both chrome and firefox would download my simple test.php instead of opening the page.

Is there any suggestion where should I look with the preferences to change this? (Ubuntu 16.04)

答: What's the webserver? You can start to read here: http://php.net/manual/en/install.php</p>


问:
Firebug programmatic breakpoint?
Is there any way to set a programmatic breakpoint in JavaScript, so that Firebug will stop executing code and I can continue step by step debug inside the Firebug.

Something similar to what is done in python like:

```<code>import pdb; pdb.set_trace()
</code>```

答: If I'm understanding you correctly, you can use the debugger keyword.

Title: Firebug programmatic breakpoint?

Body:
Is there any way to set a programmatic breakpoint in JavaScript, so that Firebug will stop executing code and I can continue step by step debug inside the Firebug.

Something similar to what is done in python like:

import pdb; pdb.set_trace()


问:
How to make checkbox selected during rendering
I have already look and applied lots of the solution methods on web i.e. Check/Uncheck checkbox with javascript? but my problem is make the checkbox to be checked after page load. I use $(window).load(function () and $(document).ready(function () but none of them working. However, if I can set checked property in html of checkbox the problem will be solved. But I cannot set this property via a Javascript variable. I also tried by jQuery but the problem is related to setting this property after rendering of checkbox. Any idea to fix the problem?

```<code><input type="checkbox" class="form-check-input" id="chkAll" >

//Although the checkboz is already rendered at this stage I cannot set it
$(window).load(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});
</code>```

and

```<code>//As the checkbox is not rendering during page load this method is useless
$(document).ready(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});
</code>```

答:
Do it.</p>

```<code>$('element').prop('checked', true);
</code>```

Body:
I have already look and applied lots of the solution methods on web i.e. Check/Uncheck checkbox with javascript? but my problem is make the checkbox to be checked after page load. I use $(window).load(function () and $(document).ready(function () but none of them working. However, if I can set checked property in html of checkbox the problem will be solved. But I cannot set this property via a Javascript variable. I also tried by jQuery but the problem is related to setting this property after rendering of checkbox. Any idea to fix the problem?

<input type="checkbox" class="form-check-input" id="chkAll" >

//Although the checkboz is already rendered at this stage I cannot set it
$(window).load(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});

and

//As the checkbox is not rendering during page load this method is useless
$(document).ready(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});

Body:
Do it.

$('element').prop('checked', true);


问:
How to load Leaflet layer attribution from server?
I have my own Leaflet tile layer extension

```<code>L.TileLayer.Foo = L.TileLayer.extend({
    options: {
        ...
    },
    initialize: function (apiKey, options) {
        ...
        L.TileLayer.prototype.initialize.call(this, url, mergedOptions);
    },
    getAttribution: function() {
        return "hello!";
    }
});
</code>```

Basically, Leaflet will at some point call getAttribution of all layers, and build attribution control. But what if I want to load attribution text (which shall getAttribution return) from server (based on apiKey provided to initialize)?

I dont see any asynchronous way (something to call from ajax success callback) in docs

答:
Leaflet doesn't have that kind of functionality. You need to implement AJAX call by yourself, then add attribution manually in xhr callback. So inside getAttribution will be something like:

```<code>AjaxCall.then(function(responce){
   leafletMap.attributionControl.addAttribution(responce.data.Attribution);
});
</code>```

Body:
I have my own Leaflet tile layer extension

L.TileLayer.Foo = L.TileLayer.extend({
    options: {
        ...
    },
    initialize: function (apiKey, options) {
        ...
        L.TileLayer.prototype.initialize.call(this, url, mergedOptions);
    },
    getAttribution: function() {
        return "hello!";
    }
});

Basically, Leaflet will at some point call getAttribution of all layers, and build attribution control. But what if I want to load attribution text (which shall getAttribution return) from server (based on apiKey provided to initialize)?

I dont see any asynchronous way (something to call from ajax success callback) in docs

Body:
Leaflet doesn't have that kind of functionality. You need to implement AJAX call by yourself, then add attribution manually in xhr callback. So inside getAttribution will be something like:

AjaxCall.then(function(responce){
   leafletMap.attributionControl.addAttribution(responce.data.Attribution);
});


问:
For loop and see variable name as a string in R
I want to create a for loop in R, but it should depend on the last letter in 17 variables, and I have trouble finding out how to make the function see the variable name as a string.

The code I have now:

```<code>fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00a))
fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00b))
fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00c))
</code>```

As you can see, i just keep on repeating the code for each variable from the letter a to r, so i want to create a for loop, which can change the last letter of the variable q_81_SQ00a to the letters a-r.

```<code>for (i in c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r')) {

  fisher.test(data.family$proband.unrelated, data.family$q_81_SQ00'i'))

}
</code>```

I get the warning "unexpected symbol" for several places in the code.
Thanks in advance!

答:
By the comments, it seems you have some trouble with some of the Fisher tests. To see which go right and wrong, you could add the try function around the Fisher test.

```<code>lapply(letters[1:18], function(x){
    try(fisher.test(table(data.family$proband.unrelated,
                data.family[[paste0("q_81_SQ00", x)]])))
})
</code>```

Body:
I want to create a for loop in R, but it should depend on the last letter in 17 variables, and I have trouble finding out how to make the function see the variable name as a string.

The code I have now:

fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00a))
fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00b))
fisher.test(table( data.family$proband.unrelated, data.family$q_81_SQ00c))

As you can see, i just keep on repeating the code for each variable from the letter a to r, so i want to create a for loop, which can change the last letter of the variable q_81_SQ00a to the letters a-r.

for (i in c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r')) {

  fisher.test(data.family$proband.unrelated, data.family$q_81_SQ00'i'))

}

I get the warning "unexpected symbol" for several places in the code.
Thanks in advance!

Body:
By the comments, it seems you have some trouble with some of the Fisher tests. To see which go right and wrong, you could add the try function around the Fisher test.

lapply(letters[1:18], function(x){
    try(fisher.test(table(data.family$proband.unrelated,
                data.family[[paste0("q_81_SQ00", x)]])))
})


问:
Querying array of objects in typescript
I have an array of JSON objects

```<code>array = [{name: "will", age: "18"}
         {name: "Elliott", age: "21"}
        ]
</code>```

Is there a way to get the "age" for any given "name" (as you would do with a SQL statement when querying a database?

答:
```<code>let queryName = 'will';
array.forEach((obj) => {
    if (obj.name === queryName) {
        console.log(obj.name, obj.age); // will 18
    }
});
</code>```

Title: Querying array of objects in typescript

Body:
I have an array of JSON objects

array = [{name: "will", age: "18"}
         {name: "Elliott", age: "21"}
        ]

Is there a way to get the "age" for any given "name" (as you would do with a SQL statement when querying a database?


问:
ping multiple sub nets / bash
I'm trying to ping multiple sub nets
what I'm doing now is simply repeating the loop
but I believe should be much simpler solution to do it in one loop</p>

```<code>for i in 192.168.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 192.168.0.0 Scanned"
echo "starting 10.0.0.0 network"
for i in 10.0.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 10.0.0.0 Scanned"
</code>```

答:
Could do this</p>

```<code>for i in '192.168.0.' '10.0.0.';do
    echo "starting $i.0 network"
    for j in $i{1..254};do
        echo $1 >> live_host_list $j & disown
    done
    echo "net $i.0 Scanned"
done
</code>```

Title: ping multiple sub nets / bash

Body:
I'm trying to ping multiple sub nets
what I'm doing now is simply repeating the loop
but I believe should be much simpler solution to do it in one loop

for i in 192.168.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 192.168.0.0 Scanned"
echo "starting 10.0.0.0 network"
for i in 10.0.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 10.0.0.0 Scanned"

Body:
Could do this

for i in '192.168.0.' '10.0.0.';do
    echo "starting $i.0 network"
    for j in $i{1..254};do
        echo $1 >> live_host_list $j & disown
    done
    echo "net $i.0 Scanned"
done


问:
Getting several captions or titles within a Matlab legend
I have the following script for producing a kind of scatter plot for several experiments.
The experiments gave two results, on the one hand the vector s on the other hand the vectors C2007, C2012, O2012 and O2015. These 4 vectors show different times of the exerpiments. The exerpiments itself are labeled as test1, test2, test3 and so on in the celln.

The following image shows the output from the script:

Two things are the problem: On the one hand the legend is too long, but using Columnlegend uses too much space. On the other hand the strings like "test1, "test2" etc. are repeated and not categorized under the used shape which stands for the different times (like C2007, C2012, O2012, O2015). Therefore it'd be nice if there would be a possibility to make it more obvious that the following points in the legend belong to the vector. To show what I really want to have I made a sketch with Paint:

First possibility:

This would solve the problem that the shapes are not categorized but still the legend is too long.

Therefore a completly different approach would be too use a shape which is not in the graph to show which color belongs to which test and then just show which shape belongs to which experiment date, again a small draft with Paint to show what I have imagined to do:

Sadly, I do not know how to achieve this kind of behaviour in this context, such as having specific colors (from the color vector) and specific shapes. Any help is really appreciated

```<code>close all;

s = [67,3,7,21,2,58,19,5]
colors = [0 0 0; 1 0 0 ;1 0 0.5; 1 0 1; 1 0.5 0; 1 0.5 0.5; 1 0.7 0; 0.7 0.7 0.5];
n = {'test1','test2','test3', 'test4', 'test5','test6','test7', 'test8'}

C2007 = [1.8, NaN, 7.2,3.8,2.44,2.1,7,NaN];
C2012 = [NaN, 6, 5.9, 2.5, NaN, 5.8, 8.1, NaN];
O2012 = [4,9.5,8.8, NaN, NaN, 1.2,4.5, NaN];
O2015 = [NaN, NaN, NaN, NaN, NaN, 2.8 4.4, 7.1];

figure;

for i=1:length(s)
   hplot1 = plot(s(i),C2007(i),'*','LineWidth',100,'Color',colors(i,:),'DisplayName',char(n(i)));
   legOBJ1 = legend('-DynamicLegend')
   hold all;
end

for i=1:length(s)
   hplot2 = plot(s(i),C2012(i),'+','LineWidth',100,'Color',colors(i,:),'DisplayName',char(n(i)));
   legend('-DynamicLegend')
end

for i=1:length(s)
   hplot3 = plot(s(i),O2012(i),'o','LineWidth',100,'Color',colors(i,:),'DisplayName',char(n(i)));
   legend('-DynamicLegend')
end

for i=1:length(s)
   hplot4 = plot(s(i),O2015(i),'^','LineWidth',100,'Color',colors(i,:),'DisplayName',char(n(i)));
   legend('-DynamicLegend')
end

grid on
</code>```

答:
The following code will provide a hackish way to achieve the second, better point.

To do so, points were plotted with the wanted features outside the shown figure. For making a caption the color of the line was set white , so one is not able to see it in the legend.

```<code>close all;

s = [67,3,7,21,2,58,19,5]
colors = [0 0 0; 1 0 0 ;1 0 0.5; 1 0 1; 1 0.5 0; 1 0.5 0.5; 1 0.7 0; 0.7 0.7 0.5];
n = {'test1','test2','test3', 'test4', 'test5','test6','test7', 'test8'}

C2007 = [1.8, NaN, 7.2,3.8,2.44,2.1,7,NaN];
C2012 = [NaN, 6, 5.9, 2.5, NaN, 5.8, 8.1, NaN];
O2012 = [4,9.5,8.8, NaN, NaN, 1.2,4.5, NaN];
O2015 = [NaN, NaN, NaN, NaN, NaN, 2.8 4.4, 7.1];

figure;

for i=1:length(s)
   hplot1 = plot(s(i),C2007(i),'*','LineWidth',100,'Color',colors(i,:));
   hold on;
end

for i=1:length(s)
   hplot2 = plot(s(i),C2012(i),'+','LineWidth',100,'Color',colors(i,:));
end

for i=1:length(s)
   hplot3 = plot(s(i),O2012(i),'o','LineWidth',100,'Color',colors(i,:));

end

for i=1:length(s)
   hplot4 = plot(s(i),O2015(i),'^','LineWidth',100,'Color',colors(i,:));

end

grid on

%Just stupid plots for overview
h1 = plot(-5,-5,'Color',[1 1 1]) %white dot, so that it will not be shown on
                                 %legend
h2 = plot(-5,-5,'*','LineWidth',100,'Color',[0.5 0.5 0.5]);
h3 = plot(-5,0,'+','LineWidth',100,'Color',[0.5 0.5 0.5]);
h4 = plot(-5,-5,'o','LineWidth',100,'Color',[0.5 0.5 0.5]);
h5 = plot(-5,-5,'^','LineWidth',100,'Color',[0.5 0.5 0.5]);
h6 = plot(-5,-5,'Color',[1 1 1])

for i=1:length(colors)
    hh(i) = plot(0,0,'-','Color',colors(i,:),'LineWidth',10);
end

%set boundaries to not show hack
xlim([0 100]);
ylim([0 12]);
legend([h1,h2,h3,h4,h5,h6,hh(1),hh(2),hh(3),hh(4),hh(5),hh(6),hh(7),hh(8)],{'Timing:','C2007','C2012','O2012','O2015','Tests: ', 'test1','test2','test3', 'test4', 'test5','test6','test7', 'test8'})
</code>```

Body:
I have the following script for producing a kind of scatter plot for several experiments.
The experiments gave two results, on the one hand the vector s on the other hand the vectors C2007, C2012, O2012 and O2015. These 4 vectors show different times of the exerpiments. The exerpiments itself are labeled as test1, test2, test3 and so on in the celln.

The following image shows the output from the script:

Two things are the problem: On the one hand the legend is too long, but using Columnlegend uses too much space. On the other hand the strings like "test1, "test2" etc. are repeated and not categorized under the used shape which stands for the different times (like C2007, C2012, O2012, O2015). Therefore it'd be nice if there would be a possibility to make it more obvious that the following points in the legend belong to the vector. To show what I really want to have I made a sketch with Paint:

First possibility:

This would solve the problem that the shapes are not categorized but still the legend is too long.

Therefore a completly different approach would be too use a shape which is not in the graph to show which color belongs to which test and then just show which shape belongs to which experiment date, again a small draft with Paint to show what I have imagined to do:

Sadly, I do not know how to achieve this kind of behaviour in this context, such as having specific colors (from the color vector) and specific shapes. Any help is really appreciated

close all;

s = [67,3,7,21,2,58,19,5]
colors = [0 0 0; 1 0 0 ;1 0 0.5; 1 0 1; 1 0.5 0; 1 0.5 0.5; 1 0.7 0; 0.7 0.7 0.5];
n = {'test1','test2','test3', 'test4', 'test5','test6','test7', 'test8'}

C2007 = [1.8, NaN, 7.2,3.8,2.44,2.1,7,NaN];
C2012 = [NaN, 6, 5.9, 2.5, NaN, 5.8, 8.1, NaN];
O2012 = [4,9.5,8.8, NaN, NaN, 1.2,4.5, NaN];
O2015 = [NaN, NaN, NaN, NaN, NaN, 2.8 4.4, 7.1];

figure;

for i=1:length(s)
   hplot1 = plot(s(i),C2007(i),'*','LineWidth',100,'Color',colors(i,:),'DisplayName',char(n(i)));
   legOBJ1 = legend('-DynamicLegend')
   hold all;
end

for i=1:length(s)
   hplot2 = plot(s(i),C2012(i),'+','LineWidth',100,'Color',colors(i,:),'DisplayName',char(n(i)));
   legend('-DynamicLegend')
end

for i=1:length(s)
   hplot3 = plot(s(i),O2012(i),'o','LineWidth',100,'Color',colors(i,:),'DisplayName',char(n(i)));
   legend('-DynamicLegend')
end

for i=1:length(s)
   hplot4 = plot(s(i),O2015(i),'^','LineWidth',100,'Color',colors(i,:),'DisplayName',char(n(i)));
   legend('-DynamicLegend')
end

grid on

Body:
The following code will provide a hackish way to achieve the second, better point.

To do so, points were plotted with the wanted features outside the shown figure. For making a caption the color of the line was set white , so one is not able to see it in the legend.

close all;

s = [67,3,7,21,2,58,19,5]
colors = [0 0 0; 1 0 0 ;1 0 0.5; 1 0 1; 1 0.5 0; 1 0.5 0.5; 1 0.7 0; 0.7 0.7 0.5];
n = {'test1','test2','test3', 'test4', 'test5','test6','test7', 'test8'}

C2007 = [1.8, NaN, 7.2,3.8,2.44,2.1,7,NaN];
C2012 = [NaN, 6, 5.9, 2.5, NaN, 5.8, 8.1, NaN];
O2012 = [4,9.5,8.8, NaN, NaN, 1.2,4.5, NaN];
O2015 = [NaN, NaN, NaN, NaN, NaN, 2.8 4.4, 7.1];

figure;

for i=1:length(s)
   hplot1 = plot(s(i),C2007(i),'*','LineWidth',100,'Color',colors(i,:));
   hold on;
end

for i=1:length(s)
   hplot2 = plot(s(i),C2012(i),'+','LineWidth',100,'Color',colors(i,:));
end

for i=1:length(s)
   hplot3 = plot(s(i),O2012(i),'o','LineWidth',100,'Color',colors(i,:));

end

for i=1:length(s)
   hplot4 = plot(s(i),O2015(i),'^','LineWidth',100,'Color',colors(i,:));

end

grid on

%Just stupid plots for overview
h1 = plot(-5,-5,'Color',[1 1 1]) %white dot, so that it will not be shown on
                                 %legend
h2 = plot(-5,-5,'*','LineWidth',100,'Color',[0.5 0.5 0.5]);
h3 = plot(-5,0,'+','LineWidth',100,'Color',[0.5 0.5 0.5]);
h4 = plot(-5,-5,'o','LineWidth',100,'Color',[0.5 0.5 0.5]);
h5 = plot(-5,-5,'^','LineWidth',100,'Color',[0.5 0.5 0.5]);
h6 = plot(-5,-5,'Color',[1 1 1])

for i=1:length(colors)
    hh(i) = plot(0,0,'-','Color',colors(i,:),'LineWidth',10);
end

%set boundaries to not show hack
xlim([0 100]);
ylim([0 12]);
legend([h1,h2,h3,h4,h5,h6,hh(1),hh(2),hh(3),hh(4),hh(5),hh(6),hh(7),hh(8)],{'Timing:','C2007','C2012','O2012','O2015','Tests: ', 'test1','test2','test3', 'test4', 'test5','test6','test7', 'test8'})