问:
How do I pass a pointer to a structure in a function?
I wonder how to replace *Type  by ? What address has the structure inside?

```<code>//mycode.go

package main

import "fmt"

func out(k *Type) {
    fmt.Println(k)
}

func main() {

    type DataIP struct{ Title, Desc string }

    Data := DataIP{
        "Hello!",
        "Hello GO!",
    }
    out(&Data)
}
</code>```

答:
You need to define the type DataIP outside of main() that the type is in the scope of the package and not just inside of the main function:

```<code>package main

import "fmt"

type DataIP struct{ Title, Desc string }

func out(k *DataIP) {
    fmt.Println(k)
}

func main() {

    Data := DataIP{
        "Hello!",
        "Hello GO!",
    }
    out(&Data)
}
</code>```

https://play.golang.org/p/cUS6ttcUy-

Body:
I wonder how to replace *Type  by ? What address has the structure inside?

//mycode.go

package main

import "fmt"

func out(k *Type) {
    fmt.Println(k)
}

func main() {

    type DataIP struct{ Title, Desc string }

    Data := DataIP{
        "Hello!",
        "Hello GO!",
    }
    out(&Data)
}

Body:
You need to define the type DataIP outside of main() that the type is in the scope of the package and not just inside of the main function:

package main

import "fmt"

type DataIP struct{ Title, Desc string }

func out(k *DataIP) {
    fmt.Println(k)
}

func main() {

    Data := DataIP{
        "Hello!",
        "Hello GO!",
    }
    out(&Data)
}

https://play.golang.org/p/cUS6ttcUy-


来源: stackexchange

问:
Setting the value for 'android: layout_below' property to a resource id from a different layout xml file
I have a blueprint which looks as thus:

I have the tablayout widget specified in xml like this:

```<code><android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@color/tabBg"
    android:minHeight="?attr/actionBarSize"
    app:tabTextColor="@color/grey"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
</code>```

I set it up with a ViewPager scrolling to swipe views for each tab. Now in one of the views - Tab 3, I need to arrange my components below the @id/tabLayout

This is the content of tab3.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/secondtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tabLayout"
        android:background="@android:color/white"
        android:text="second"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/thirdtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/secondtext"
        android:background="@android:color/white"
        android:text="third"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>
</code>```

Both the second and third textviews are displayed behind the tabLayout, they are covered/hidden by the tabLayout. How do i specify the textviews to display right under the tabLayout so the text is visible?

答:
A RelativeLayout, like any other layout, is only responsible for laying out it's direct children. Therefore, the android:layout_below and similar attributes, can only work for two views within the same RelativeLayout parent.

In this case, you'd have to add it to the ViewPager. Then the TextViews can be just at the top of their container, as that is now below the TabBar.

If this is no good for your other tabs. You can do one of:

- Have the TabBar be a fixed height and set that as margin to the textviews

- Query the height of TabBar at runtime an apply it as padding or margin in tab3.

ContentLicense: CC BY-SA 3.0

Body:
I have a blueprint which looks as thus:

I have the tablayout widget specified in xml like this:

<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@color/tabBg"
    android:minHeight="?attr/actionBarSize"
    app:tabTextColor="@color/grey"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

I set it up with a ViewPager scrolling to swipe views for each tab. Now in one of the views - Tab 3, I need to arrange my components below the @id/tabLayout

This is the content of tab3.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/secondtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tabLayout"
        android:background="@android:color/white"
        android:text="second"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/thirdtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/secondtext"
        android:background="@android:color/white"
        android:text="third"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Both the second and third textviews are displayed behind the tabLayout, they are covered/hidden by the tabLayout. How do i specify the textviews to display right under the tabLayout so the text is visible?


问:
How to avoid to enter repeated number in input text form?
I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,

sample code,

```<code>var mobNumber = $('#phNo').val();

if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
  alert('Please enter valid phone number');
}
</code>```

答:
You can try like this, </p>

```<code>var phone = "11111111";
            var phonecount = phone.length;
            var countLength = 0;
            for (var i in phone)
            {
                if(phone.substring(0,1)==phone[i])
                {
                    countLength = countLength + 1;
                }
            }
            if (countLength == phonecount)
            alert("Please enter valid phone number");
</code>```

Body:
I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,

sample code,

var mobNumber = $('#phNo').val();

if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
  alert('Please enter valid phone number');
}

Body:
You can try like this,

var phone = "11111111";
            var phonecount = phone.length;
            var countLength = 0;
            for (var i in phone)
            {
                if(phone.substring(0,1)==phone[i])
                {
                    countLength = countLength + 1;
                }
            }
            if (countLength == phonecount)
            alert("Please enter valid phone number");


问:
Why doesn't 'step into' debugging work with my Eclipse 4.5.2? (Step filters deactivated)
I want to step through some classes of the Oracle JDK implementation using the Eclipse debugger.

So I downloaded the current JDK from Oracle (jdk1.8.0_77), installed Eclipse via the Windows installer and wrote a simple HelloWorld class.

However, when using the 'Step into' debugging command steps over the lines that invocate JDK methods like System.out.println.

I configured Eclipse to use the JRE that is contained within the JDK instead of the standard JRE and ensured that step filters are neither set in the preferences nor applied in the debug view as explained in these answers:

Eclipse step into debugging

How can I step into a core java class method in Eclipse?

So why doesn't 'Step into (F5)' step into the source?

Thanks in advance!

答:
For me it worked by going to Debug Configurations -> JRE -> Alternate JRE -> choose jdk installation instead of default jre, and then run the debug with that configuration.
 I am using Eclipse Neon 2


问:
AutoLayout can’t display correctly in iOS10 with Xcode8
I use autolayout in a project of mine.All the constraints are blue and it can display correctly in configuration bar.But when I run my project on Simulator the constraints are wrong and it can't display correctly.I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.I really want to know how to solve the problem.It makes me very annoyed.I hope someone can help me.

Thank you very much!

(Picture2 is what displays in simulator.The last picture is the constraints.)

答:
remove all current constrains from this view controller by clicking on issue icon -> clear constrains (in the second section)

drag the items to the place you want on the view.

select an item

open align -> set horizontally in container (current canvas value ) by clicking on the black arrow beside number 0
align menu
Then set vertically in container (current canvas value)

open Pin icon -> set value to width and set value to height
pin menu

in the same pin menu check aspect ratio (in the second section )


问:
is it possible to track "Add to cart" event without using google tag manager
I have already try to track Add to cart Button using Google tag manager.

But I want to do it without using google tag manager.

i don't know it's possible or not.if you guys have any suggest let me know

thank's

答:
It is possible, obviously, since click tracking precedes Google Tag Manager. However you would need to add a bit of javascript code to your page.

If your button looks like this:

```<code><button type="button">Add to Cart</button>
</code>```

then the simplest way would be to add an onclick event handler to the button. An "event handler" is a way to execute Javascript in response to a user action - and despite a similar name it is not related to Google Analytics events, which is what you would use to send the data to Google Analytics:

```<code>   <button onclick="ga('send', 'event', {'eventCategory':'button', 'eventAction':'add2Cart','transport':'beacon'})" type="button">Add to Cart</button>
</code>```

The data should show up in the behavior section of your Google Analytics Account in the "events" section. Event Category and Action are mandatory, optionally you might specify a label and a value (where value is an integer and is used to monetize relevant actions that are not sales).

I assume your add to cart button navigates away from the current page, so it might be a good idea to specify beacon as the transport method. This makes it more likely that your data is being sent away before the page unloads. Other than that the syntax suggested by IgneeI64 is just as valid.

Again, you have two types of event here that should not be confused, a JavaScript event which is a feature of the programming language, and the Google Analytics event which is a convention on how to store data that is not an actual pageview.

Body:
It is possible, obviously, since click tracking precedes Google Tag Manager. However you would need to add a bit of javascript code to your page.

If your button looks like this:

<button type="button">Add to Cart</button>

then the simplest way would be to add an onclick event handler to the button. An "event handler" is a way to execute Javascript in response to a user action - and despite a similar name it is not related to Google Analytics events, which is what you would use to send the data to Google Analytics:

   <button onclick="ga('send', 'event', {'eventCategory':'button', 'eventAction':'add2Cart','transport':'beacon'})" type="button">Add to Cart</button>

The data should show up in the behavior section of your Google Analytics Account in the "events" section. Event Category and Action are mandatory, optionally you might specify a label and a value (where value is an integer and is used to monetize relevant actions that are not sales).

I assume your add to cart button navigates away from the current page, so it might be a good idea to specify beacon as the transport method. This makes it more likely that your data is being sent away before the page unloads. Other than that the syntax suggested by IgneeI64 is just as valid.

Again, you have two types of event here that should not be confused, a JavaScript event which is a feature of the programming language, and the Google Analytics event which is a convention on how to store data that is not an actual pageview.


问:
PHP values from select into array for json
Hey i am trying to add my selected resultset into an array to send it as a response to my angularjs function

this is my code

```<code>include 'dbconnect.php';

global $mysqli;

$sql = "SELECT `id`, `name`, `stock`, `pzn` FROM `pda_articles`";

$result = mysqli_query($mysqli, $sql) OR die(mysqli_error($mysqli));

$data = array();

if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    print json_encode($data);
} else {
    echo "no";
}
</code>```

$data[] = $row should work but it doesnt.. $data[] = $row['id'] works but i have no idea how to add the other columns...

maybe you could help me

this is my output with console.log

Thanks :)

答:
you should build the array and populate it with  keys and data then use array push</p>

```<code>$data = array();
while($row = mysqli_fetch_assoc($result)) {
        $col['id'] = $row['id'];
        $col['name'] = $row['name'];
        $col['stock'] = $row['stock'];
        array_push($data,$col);

}
    echo json_encode($data);
</code>```

Body:
Hey i am trying to add my selected resultset into an array to send it as a response to my angularjs function

this is my code

include 'dbconnect.php';

global $mysqli;

$sql = "SELECT `id`, `name`, `stock`, `pzn` FROM `pda_articles`";

$result = mysqli_query($mysqli, $sql) OR die(mysqli_error($mysqli));

$data = array();

if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    print json_encode($data);
} else {
    echo "no";
}

$data[] = $row should work but it doesnt.. $data[] = $row['id'] works but i have no idea how to add the other columns...

maybe you could help me

this is my output with console.log

Thanks :)

Body:
you should build the array and populate it with  keys and data then use array push

$data = array();
while($row = mysqli_fetch_assoc($result)) {
        $col['id'] = $row['id'];
        $col['name'] = $row['name'];
        $col['stock'] = $row['stock'];
        array_push($data,$col);

}
    echo json_encode($data);


问:
How to add Chains feature of constraint layout with design in android studio
I have two images in constraint layout. I want to use chains feature with design page in android studio but I can't find icon or menu that represent Chains feature.</p>

答:
Update (2019 august 23)

The small buttons shown on the screenshots are now available on the right click menu, Google updated the UI for more easy layout operations.

How to add Chains feature of ConstraintLayout with Android Studio's 'Layout Editor'?

The chain style can be controlled by "chain" button right below the view:

Click on it few times to toggle between all 3 modes:

spread (the default one)

spread_inside

packed

Let's see some examples

centering views which are connected together using chain

drag and drop three buttons into the Android Studio's 'Layout Editor'

Select those buttons together by dragging mouse

Pack them vertically using the 'pack' button in 'Layout Editor'

Align them center horizontally using 'Align-Center horizontally' button

Align them center vertically using the 'Align-Center vertically' button

Here we used the pack option. similar to this, you can try spread and spread inside options of chain to see the difference. cheers :)

ContentLicense: CC BY-SA 4.0


答:
Your plot is not blank, because of small numbers in x1 and x2 and ggplot axes you cant see them.

So in order to see them in plot I've rounded all numbers in x1 and x2 to two decimals.

Firstly I've converted true to data frame and then rounded all numbers.

```<code>true <-  as.data.frame(true)
number <- sapply(true, is.numeric)
true[number ] <- lapply(true[number ], round, 2)
</code>```

Then I've ploted using your code

```<code>p6 <- ggplot(true, aes(x1, x2)) +
  geom_raster(aes(fill = risk))
p6
</code>```

And the output:

Note if you don't like to round up your numbers you could use scale_x_continuous(limits = c()) and scale_y_continuous(limits = c()) in order your data would become visible.

Title: geom_raster(): Simple example

Body:
I don't have a problem with geom_raster() when following the old faithful example, but I have not been successful at making my own plot from simulated data. For example, given the following data

R>true

x1     x2    risk
.82    .80   2.44
.87    -.72  -.57
-.42   .97   1.52
.66    .89   2.44
.28   -.83   -1.38

I build a ggplot with the following:

R> p <- ggplot(true, aes(x1, x2)) +
 geom_raster(aes(fill = risk))

R> p

This gives me a blank plot. I am not sure why this is.

This is the output as requested:

> dput(true)
structure(list(x1 = c(0.829612086992711, 0.874150826595724, -0.427720930427313,
0.660895252134651, 0.283491037786007, 0.0381918982602656, 0.473176629282534,
-0.730666805524379, 0.313984580803663, 0.410129568073899, -0.0845164475031197,
0.438224503304809, 0.869344494305551, -0.489142351318151, -0.0754143549129367,
0.880029045511037, 0.956452856771648, -0.765025276690722, -0.0500058368779719,
0.120665492489934), x2 = c(0.808062774594873, -0.722579664550722,
0.977783457841724, 0.89333646511659, -0.835124883800745, 0.0284235686995089,
-0.219593065790832, 0.811476261820644, -0.10606074379757, 0.672008519992232,
0.475191235542297, 0.622110282536596, -0.22378343436867, 0.370339458808303,
-0.992103322409093, 0.665832160506397, -0.985331706237048, -0.584682054352015,
0.813202815596014, 0.223557286895812), x3 = c(-0.240881518926471,
-0.128456830047071, -0.925137934274971, 0.947079827543348, -0.136497502215207,
0.915153193287551, 0.775509811006486, 0.279957538936287, 0.941933220718056,
0.237676414661109, -0.333145577460527, -0.306503503583372, -0.20302917715162,
0.569385551381856, -0.922127017751336, 0.497590772341937, 0.35455366037786,
-0.657471339218318, -0.477824072353542, 0.0288258693180978),
    x4 = c(0.351214549038559, 0.965634395834059, 0.519088535103947,
    0.132976848166436, 0.699379437137395, -0.62105212919414,
    -0.457426770590246, 0.656316970475018, 0.386409640777856,
    -0.518910520710051, -0.914022407960147, -0.719041811767966,
    -0.567229169886559, -0.041202871594578, -0.605179315432906,
    0.438711675349623, -0.984230522532016, -0.249020070768893,
    0.0288154166191816, -0.996858891565353), x5 = c(0.163208005018532,
    -0.684189583640546, -0.281943388283253, 0.291263756807894,
    0.551646725274622, 0.127293683122844, -0.532593202777207,
    -0.820038967300206, -0.828775870148093, -0.389563261065632,
    0.334853029344231, -0.999522206839174, -0.582860086113214,
    0.866068254690617, 0.851289497222751, 0.468188602011651,
    -0.333856033161283, 0.0301266596652567, 0.487949292641133,
    0.238318480085582), risk = c(2.44573763618246, -0.57100850250572,
    1.52784598525614, 2.44756818236783, -1.38675872981548, 0.0950390356592834,
    0.03399049770087, 0.892285718116909, 0.101863093208522, 1.75414660805836,
    0.865866023581475, 1.682445068378, 0.421777625568211, 0.251536566298455,
    -2.05962099973112, 2.21169336652383, -1.01421055570245, -1.93438938539475,
    1.57639979431406, 0.567780066281557), time = c(12.9241509784045,
    0.754603959518346, 0.677189139459449, 2.07339828770144, 0.109777657032991,
    1.39996365414718, 0.167462659974731, 1.09586349933275, 0.463151062910805,
    2.32239195497809, 1.52799525778206, 13.5096449131547, 2.39962724414737,
    3.03968330607599, 0.1532054718408, 5.79336751789379, 0.633832566535867,
    0.0149323120147296, 2.12249155520952, 1.74580444108114),
    is_censored = c(0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 1L, 0L,
    0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L)), .Names = c("x1", "x2",
"x3", "x4", "x5", "risk", "time", "is_censored"), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -20L))
> sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.10.5 (Yosemite)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] gridExtra_2.2.1 dplyr_0.5.0     purrr_0.2.2     readr_1.0.0     tidyr_0.6.1     tibble_1.2
[7] ggplot2_2.2.1   tidyverse_1.1.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.9      plyr_1.8.4       forcats_0.2.0    tools_3.3.1      digest_0.6.12    evaluate_0.10
 [7] jsonlite_1.2     lubridate_1.6.0  gtable_0.2.0     nlme_3.1-131     lattice_0.20-34  psych_1.6.12
[13] DBI_0.5-1        yaml_2.1.14      parallel_3.3.1   haven_1.0.0      stringr_1.2.0    httr_1.2.1
[19] knitr_1.15.1     xml2_1.1.1       hms_0.3          rprojroot_1.2    R6_2.2.0         readxl_0.1.1
[25] rmarkdown_1.3    foreign_0.8-67   reshape2_1.4.2   modelr_0.1.0     magrittr_1.5     backports_1.0.5
[31] htmltools_0.3.5  scales_0.4.1     assertthat_0.1   mnormt_1.5-5     rvest_0.3.2      colorspace_1.3-2
[37] labeling_0.3     stringi_1.1.2    lazyeval_0.2.0   munsell_0.4.3    broom_0.4.2

The following code reproduces the problem better than the previous example:

true <- list(x1 = c(0.829612086992711, 0.874150826595724, -0.427720930427313,
0.660895252134651, 0.283491037786007, 0.0381918982602656, 0.473176629282534,
-0.730666805524379, 0.313984580803663, 0.410129568073899, -0.0845164475031197,
0.438224503304809, 0.869344494305551, -0.489142351318151, -0.0754143549129367,
0.880029045511037, 0.956452856771648, -0.765025276690722, -0.0500058368779719,
0.120665492489934), x2 = c(0.808062774594873, -0.722579664550722,
0.977783457841724, 0.89333646511659, -0.835124883800745, 0.0284235686995089,
-0.219593065790832, 0.811476261820644, -0.10606074379757, 0.672008519992232,
0.475191235542297, 0.622110282536596, -0.22378343436867, 0.370339458808303,
-0.992103322409093, 0.665832160506397, -0.985331706237048, -0.584682054352015,
0.813202815596014, 0.223557286895812), risk = c(2.44573763618246, -0.57100850250572,
    1.52784598525614, 2.44756818236783, -1.38675872981548, 0.0950390356592834,
    0.03399049770087, 0.892285718116909, 0.101863093208522, 1.75414660805836,
    0.865866023581475, 1.682445068378, 0.421777625568211, 0.251536566298455,
    -2.05962099973112, 2.21169336652383, -1.01421055570245, -1.93438938539475,
    1.57639979431406, 0.567780066281557))
true <- as_tibble(true)
true

p6 <- ggplot(true, aes(x1, x2)) +
 geom_raster(aes(fill = risk))
p6

Body:
Your plot is not blank, because of small numbers in x1 and x2 and ggplot axes you cant see them.

So in order to see them in plot I've rounded all numbers in x1 and x2 to two decimals.

Firstly I've converted true to data frame and then rounded all numbers.

true <-  as.data.frame(true)
number <- sapply(true, is.numeric)
true[number ] <- lapply(true[number ], round, 2)

Then I've ploted using your code

p6 <- ggplot(true, aes(x1, x2)) +
  geom_raster(aes(fill = risk))
p6

And the output:

Note if you don't like to round up your numbers you could use scale_x_continuous(limits = c()) and scale_y_continuous(limits = c()) in order your data would become visible.


问:
After exclude module 'answer-shim' in the android gradle for io.branch.sdk couldn't build with proguard
When try to build the release build with proguard enable getting below warning and couldn't build the APK successfully.</p>

```<code>Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEvent
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.AnswersOptionalLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEventLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.AnswersOptionalLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEventLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEvent
Warning:there were 14 unresolved references to classes or interfaces.
Warning:Exception while processing task java.io.IOException: Please correct the above warnings first.
Error:java.lang.RuntimeException: Job failed, see logs for details
Error:java.io.IOException: Please correct the above warnings first.
</code>```

答:
If you want to exclude Crashlytics from Proguard you can use these 2 lines

-keep class com.crashlytics.** { *; }
-dontwarn com.crashlytics.**

Check out Fabric's Proguard page

Body:
When try to build the release build with proguard enable getting below warning and couldn't build the APK successfully.

Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEvent
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.AnswersOptionalLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEventLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.AnswersOptionalLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEventLogger
Warning:io.branch.referral.ExtendedAnswerProvider: can't find referenced class com.crashlytics.android.answers.shim.KitEvent
Warning:there were 14 unresolved references to classes or interfaces.
Warning:Exception while processing task java.io.IOException: Please correct the above warnings first.
Error:java.lang.RuntimeException: Job failed, see logs for details
Error:java.io.IOException: Please correct the above warnings first.


问:
Why does this sort in Java not work?
I'm trying to implement a short sorting algorithm, but it simply doesn't work. Anyone with more experience in programming got any tips? The array is not sorted, several values are coming up multiple times in the end print. Why?</p>

```<code>public static void main(String[] args) {
    // Sort the data
    int[] array = {1,5,2,3,6,2,29,-2,23,3};

    for (int i = 0; i<array.length-1; i++) {

        if (array[i] > array[i+1]) {
            array[i+1] = array[i];
            array[i] = array[i+1];
        }
    }

    // Print the data.
    for (int i = 0; i<array.length; i++) {
        System.out.print(i+ ", ");
    }
}
</code>```

答:
you need to add temporel variable and return to the start of array after every swap </p>

```<code>public static void main(String[] args) {
        // Sort the data
        int[] array = {1,5,2,3,6,2,29,-2,23,3};
      int temp;
        for (int i = 0; i<array.length-1; i++) {

            if (array[i] > array[i+1]) {
                temp=array[i+1];  //temporel
                array[i+1] = array[i];
                array[i] = temp;
                i=0;     //to return to the start of the array
            }
        }

        // Print the data.
        for (int i = 0; i<array.length; i++) {
            System.out.print(i+ ", ");
        }
    }
</code>```

Title: Why does this sort in Java not work?

Body:
I'm trying to implement a short sorting algorithm, but it simply doesn't work. Anyone with more experience in programming got any tips? The array is not sorted, several values are coming up multiple times in the end print. Why?

public static void main(String[] args) {
    // Sort the data
    int[] array = {1,5,2,3,6,2,29,-2,23,3};

    for (int i = 0; i<array.length-1; i++) {

        if (array[i] > array[i+1]) {
            array[i+1] = array[i];
            array[i] = array[i+1];
        }
    }

    // Print the data.
    for (int i = 0; i<array.length; i++) {
        System.out.print(i+ ", ");
    }
}

Body:
you need to add temporel variable and return to the start of array after every swap

public static void main(String[] args) {
        // Sort the data
        int[] array = {1,5,2,3,6,2,29,-2,23,3};
      int temp;
        for (int i = 0; i<array.length-1; i++) {

            if (array[i] > array[i+1]) {
                temp=array[i+1];  //temporel
                array[i+1] = array[i];
                array[i] = temp;
                i=0;     //to return to the start of the array
            }
        }

        // Print the data.
        for (int i = 0; i<array.length; i++) {
            System.out.print(i+ ", ");
        }
    }


问:
c(++) union Data structure
I'm programming for a µC, i have following data Structure:

```<code>typedef struct
{
  RF12Head head;

  typedef union
  {
    uint8_t raw[40];

    typedef struct
    {
      node_id nodeId;
      uint8_t hierachyDepth;
    } MessageNodeFound;
  } data;

} RF12Message;
</code>```

A RF12Message contains a header an an data part.
Now i want to have different message formats.

I want to be able to do something like this:

```<code>RF12Message msg;

memset(&msg.data.raw, 0xEF, sizeof(msg.data.raw)); // fill in directly

//or indirectly:

msg.data.MessageNodeFound.nodeId = 3;
msg.data.MessageNodeFound.hierachyDepth = 2;
</code>```

but the compiler aways throws an error: "invalid use of 'RF12Message::data'", why?

thank you!

答:
The problem is your typedef statements. RF12Message::data is not a union of 40 uint8_ts and a MessageNodeFound; it is a datatype consisting of those things.

A similar problem will affect your declaration of MessageNodeFound. Remove both typedefs, and I think it should work.

ContentLicense: CC BY-SA 2.5

Title: c(++) union Data structure

Body:
I'm programming for a µC, i have following data Structure:

typedef struct
{
  RF12Head head;

  typedef union
  {
    uint8_t raw[40];

    typedef struct
    {
      node_id nodeId;
      uint8_t hierachyDepth;
    } MessageNodeFound;
  } data;

} RF12Message;

A RF12Message contains a header an an data part.
Now i want to have different message formats.

I want to be able to do something like this:

RF12Message msg;

memset(&msg.data.raw, 0xEF, sizeof(msg.data.raw)); // fill in directly

//or indirectly:

msg.data.MessageNodeFound.nodeId = 3;
msg.data.MessageNodeFound.hierachyDepth = 2;

but the compiler aways throws an error: "invalid use of 'RF12Message::data'", why?

thank you!


问:
json file images won't load in ionic page
I am trying to load some images from a file on a server to display on a list.  I get 404 not found error
after asking in forums, I get that the request URL is wrong, it looks inside the localhost not inside the json file.

https://filehost.net/db54d37849f75ddd

in the code I have a service which returns a response.  I use that response in a controller and to the view. I get other information but no images
if anybody has a solution that would be really great.

答:
please attach also some code, in this way it is easier to help you. About the problem, do have correct form of $http GET request? I mean does your get request points to correct address on server? something like this
`
// Simple GET request example:

```<code>$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
</code>```

`

you can check more here Angular $http

Body:
please attach also some code, in this way it is easier to help you. About the problem, do have correct form of $http GET request? I mean does your get request points to correct address on server? something like this
`
// Simple GET request example:

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

`

you can check more here Angular $http


问:
What is the relationship between a thread and its parent stack?
pthreads all have their own stack and share the heap. They inherit various aspects of the parent at creation time (sig masks, fpenv etc.). There seems to be little said about the relationship between the child thread and the parents stack.

So can I pass the address of something on the parent stack to a child thread via pthread_create and expect this to work? Is the child thread able to see the stack of the parent process? Does the childs stack get populated with a copy of the parent stack at creation time?

It's useful to me to know what is guaranteed by the standard and what practically works.

答:
So can I pass the address of something on the parent stack to a child thread via pthread_create and expect this to work?

Yes. You can pass the address of something on parent thread's stack and expect it to work. But, please be aware that for any thread, the stack is active only till the thread is active. So, if your program is such that the child thread will be active even after the parent ceases to exist, you are in for trouble. Expect Undefined Behavior in that case.

Is the child thread able to see the stack of the parent process?

Child will be able to access a memory passed through pthread_create even if the memory is from parent's stack. But, if it is not passed through pthread_create, I don't think it will have access otherwise.

Does the childs stack get populated with a copy of the parent stack at creation time?

No. There is no copy of parent stack which is passed on to child.


问:
Lexical analysis using lex
Before I will show what I have done here is the assignment I have tried to do(I'm new so im not really sure if im doing it allright).

```<code>1.  Implement lexical analyzer (using FLEX), as follows:
- Lexical analyzer supplies services next_token(), back_token()
- Lexical analyzer reads text from the input file and identifies tokens. This
   happens when function   next_token() is called.
- When a token is identified in the input text, it should be stored in a data
   structure. For each token, the following attributes are saved:
   * token type
   * token lexeme
   * number of the line in the input text in which this token was found.
- Blanks, tabs, new lines – are not tokens, and should be ignored
- For each token, print (on a separate line) its type (e.g. rel_op , number , etc.)
   and lexeme
- Each operation, keyword, separation sign and each type of number should be
   implemented as a token of a different kind
- Kinds of tokens are coded with integer numbers, for example:
        # define  ID_tok  1
        # define COMMA_tok  2
</code>```

using Flex I have written this:

```<code>%{
#include<stdio.h>
int line=1;
# define  ID_tok  1
# define COMMA_tok  2
#define REL_OP_tok 3
#define NUMBER_tok 4
#define KEYWORDS_tok 5
%}
binary_ar_op "*"|"/"|"+"|"-"
rel_op "=="|"!="|">"|"<"|"<="|">="
id      [a-z][a-z0-9]*
number    ["+"|"-"]?[0-9]*("."[0-9]+)?
keywords "prabegin"|"parend"|"task"|"begin"|"end"|"integer"|"real"|"do"|"until"|"od"|"send"|"accept"

%%
\n   {line++;  printf("\n%d:",line);}

{binary_ar_op}+ {printf( "An binary_ar_op: %s (%d) at line(%d)\n", yytext,
                   atoi( yytext ),line);}

{rel_op}+ {printf( "An rel_op: %s (%d) at line(%d)\n", yytext,
                   atoi( yytext ),line);}

{id}+ {printf( "An id: %s (%d) at line(%d)\n", yytext,
                   atoi( yytext ),line);}

{number}+ {printf( "An number: %s (%d) at line(%d)\n", yytext,
                   atoi( yytext ),line);}
%%
int yywrap()
{
return 1;
}
main()
{
printf("Enter a string of data\n");
yylex();
}
</code>```

As you can see I already defined all the types I was suppost to, I do not understand how to implement next and back, some guideness whould be great,also I saved the line number , but I guess they mean other then what I wrote,
I also dont understand the define part they wrote about.

I know that this question seems odd, but I got this assignment without any guidness or explanation before, so I'm learning it on my own and I dont really understand all(Although I know the theory, thank you!).

答:
I did something very similar in our company project(s).

About tokens

I make enumerations for them and...

About next_token()

My intention was to store the whole token related information into an object with:

the acutal token (an enumeration value)

the lexeme (a std::string)

the file position (consisting of a file name pointer, the line, and the column).

Additionally, I wanted to use smart pointers with these generated objects, not to mention, they should be C++ objects.

This is what I realized:

It is easy to redefine the yylex() function. Thus, you can even rename it and change its signature.

It is very difficult (if not impossible) to put this together with yacc/bison. The main issue was that data is passed from lex (generated code) to yacc/bison (generated code) using a C union (%union if I remember right). A C union and C++ objects -- that doesn't work well. (One object in C union may work but multiple definitely not.)

For my luck, the 2nd issue was actually not existing for me because I use flex but write (meanwhile generate) recursive descent parsers (directly in C++).

So, how to solve the 1st issue? This is from my code:

```<code>/// redefines proto for generated yylex function.
#define YY_DECL \
  RF::YAMS::Sim::ActionScript::RefToken \
  RF::YAMS::Sim::ActionScript::Compiler::lex(yyscan_t yyscanner)
</code>```

This is the flex man page where you find the documentation. To find explanation how to redefine the yylex function, please, search on this website for "YY_DECL".

My parser calls lex() whenever it needs a new token.

Notes:

In my case, I renamed yylex() and even made it a method of my parser class. (I did this to simplify access of lexer to private parser variables.)

I provided ful scope operators because the generated lex code does not consider any namespace I use in my C++ code.

The yyscan_t yyscanner parameter has to be there because I generate re-entrant scanners. You have to decide whether or not it should be there. (Instead you could provide other arguments also.)

The returned RefToken is a smart pointer to the produced token. (Smart pointers makes it very easy to produce and consume tokens in different "places" without the danger of memory leaks.)

If the generated lexer shall be combined with a bison-generated parser it is probably not as easy. In this case, I would use static variables and organize queues to pass values from lexer to parser. This would work but is, of course, not as elegant and save as the above method.

About back_token()

Once you have a parser which consumes the tokens you may do with them whatever you want. In my case, one of the requirements was an option for back-tracking. Thus, from time to time I have to push back tokens to input. For this, I simply stack them in the parser. If a new token is required I check 1st whether this stack is empty. If not the uppermost token is popped else the lex() method is called to obtain a really new token. I guess a similar solution could be used to implement back_token() in your case.

About blanks

There are actually two types of rules (i.e. rule actions) in my lexer:

actions which end up with return new Token(...);

actions which end up with break;

The latter I use to consume separators (i.e. blanks etc.) and even comments (the parser even does not see them). This works because the lexer is actually nothing else than a switch() wrapped in a for() loop. (I learnt this "trick" from the flex doc. where it is mentioned explicitly somewhere.)

What else...

Beside of YY_DECL, I redefined YY_INPUT also. I did this to use the lexer with C++ std::stream (instead of yyin).

IMHO flex does provide a very comprehensive manual. However, whenever I'm in doubt I look into the C file generated by flex. There are these horrible int arrays for the finite automaton which I usually simply ignore. The rest is the infra-structure around them, and you will find your C actions (written in the lex rules) somewhere embedded. Examining the code around may make things clearer.

Title: Lexical analysis using lex

Body:
Before I will show what I have done here is the assignment I have tried to do(I'm new so im not really sure if im doing it allright).

1.  Implement lexical analyzer (using FLEX), as follows:
- Lexical analyzer supplies services next_token(), back_token()
- Lexical analyzer reads text from the input file and identifies tokens. This
   happens when function   next_token() is called.
- When a token is identified in the input text, it should be stored in a data
   structure. For each token, the following attributes are saved:
   * token type
   * token lexeme
   * number of the line in the input text in which this token was found.
- Blanks, tabs, new lines – are not tokens, and should be ignored
- For each token, print (on a separate line) its type (e.g. rel_op , number , etc.)
   and lexeme
- Each operation, keyword, separation sign and each type of number should be
   implemented as a token of a different kind
- Kinds of tokens are coded with integer numbers, for example:
        # define  ID_tok  1
        # define COMMA_tok  2

using Flex I have written this:

%{
#include<stdio.h>
int line=1;
# define  ID_tok  1
# define COMMA_tok  2
#define REL_OP_tok 3
#define NUMBER_tok 4
#define KEYWORDS_tok 5
%}
binary_ar_op "*"|"/"|"+"|"-"
rel_op "=="|"!="|">"|"<"|"<="|">="
id      [a-z][a-z0-9]*
number    ["+"|"-"]?[0-9]*("."[0-9]+)?
keywords "prabegin"|"parend"|"task"|"begin"|"end"|"integer"|"real"|"do"|"until"|"od"|"send"|"accept"

%%
\n   {line++;  printf("\n%d:",line);}

{binary_ar_op}+ {printf( "An binary_ar_op: %s (%d) at line(%d)\n", yytext,
                   atoi( yytext ),line);}

{rel_op}+ {printf( "An rel_op: %s (%d) at line(%d)\n", yytext,
                   atoi( yytext ),line);}

{id}+ {printf( "An id: %s (%d) at line(%d)\n", yytext,
                   atoi( yytext ),line);}

{number}+ {printf( "An number: %s (%d) at line(%d)\n", yytext,
                   atoi( yytext ),line);}
%%
int yywrap()
{
return 1;
}
main()
{
printf("Enter a string of data\n");
yylex();
}

As you can see I already defined all the types I was suppost to, I do not understand how to implement next and back, some guideness whould be great,also I saved the line number , but I guess they mean other then what I wrote,
I also dont understand the define part they wrote about.

I know that this question seems odd, but I got this assignment without any guidness or explanation before, so I'm learning it on my own and I dont really understand all(Although I know the theory, thank you!).

Body:
I did something very similar in our company project(s).

About tokens

I make enumerations for them and...

About next_token()

My intention was to store the whole token related information into an object with:

the acutal token (an enumeration value)

the lexeme (a std::string)

the file position (consisting of a file name pointer, the line, and the column).

Additionally, I wanted to use smart pointers with these generated objects, not to mention, they should be C++ objects.

This is what I realized:

It is easy to redefine the yylex() function. Thus, you can even rename it and change its signature.

It is very difficult (if not impossible) to put this together with yacc/bison. The main issue was that data is passed from lex (generated code) to yacc/bison (generated code) using a C union (%union if I remember right). A C union and C++ objects -- that doesn't work well. (One object in C union may work but multiple definitely not.)

For my luck, the 2nd issue was actually not existing for me because I use flex but write (meanwhile generate) recursive descent parsers (directly in C++).

So, how to solve the 1st issue? This is from my code:

/// redefines proto for generated yylex function.
#define YY_DECL \
  RF::YAMS::Sim::ActionScript::RefToken \
  RF::YAMS::Sim::ActionScript::Compiler::lex(yyscan_t yyscanner)

This is the flex man page where you find the documentation. To find explanation how to redefine the yylex function, please, search on this website for "YY_DECL".

My parser calls lex() whenever it needs a new token.

Notes:

In my case, I renamed yylex() and even made it a method of my parser class. (I did this to simplify access of lexer to private parser variables.)

I provided ful scope operators because the generated lex code does not consider any namespace I use in my C++ code.

The yyscan_t yyscanner parameter has to be there because I generate re-entrant scanners. You have to decide whether or not it should be there. (Instead you could provide other arguments also.)

The returned RefToken is a smart pointer to the produced token. (Smart pointers makes it very easy to produce and consume tokens in different "places" without the danger of memory leaks.)

If the generated lexer shall be combined with a bison-generated parser it is probably not as easy. In this case, I would use static variables and organize queues to pass values from lexer to parser. This would work but is, of course, not as elegant and save as the above method.

About back_token()

Once you have a parser which consumes the tokens you may do with them whatever you want. In my case, one of the requirements was an option for back-tracking. Thus, from time to time I have to push back tokens to input. For this, I simply stack them in the parser. If a new token is required I check 1st whether this stack is empty. If not the uppermost token is popped else the lex() method is called to obtain a really new token. I guess a similar solution could be used to implement back_token() in your case.

About blanks

There are actually two types of rules (i.e. rule actions) in my lexer:

actions which end up with return new Token(...);

actions which end up with break;

The latter I use to consume separators (i.e. blanks etc.) and even comments (the parser even does not see them). This works because the lexer is actually nothing else than a switch() wrapped in a for() loop. (I learnt this "trick" from the flex doc. where it is mentioned explicitly somewhere.)

What else...

Beside of YY_DECL, I redefined YY_INPUT also. I did this to use the lexer with C++ std::stream (instead of yyin).

IMHO flex does provide a very comprehensive manual. However, whenever I'm in doubt I look into the C file generated by flex. There are these horrible int arrays for the finite automaton which I usually simply ignore. The rest is the infra-structure around them, and you will find your C actions (written in the lex rules) somewhere embedded. Examining the code around may make things clearer.


问:
How to display all available variants in python?
If I have this simple code, how can I display all available variants ?

```<code>#Display all possible variants until reach input sum with coins of 2 and 5
#Not fixed: Output only first result !

#Input
summ = int(input("Enter sum: "))
two = 2
five = 5

#Calculations/Checks/Output
for i in range(0, two+1):
    for j in range(0, five+1):
        if (i*2 + j*5 == summ):
            print(i, "*2 + ", j, "*5 = ", summ)

#End
</code>```

For example:

```<code>Input: 17

Output:
1*2 + 3*5 = 17
6*2 + 1*5 = 17
</code>```

But the code displays only the first result?

How can I fix this ?

答:
You can use itertools, and a generator:

```<code>In [17]: def correct_sum_i(i, val):
    ...:     sum_perm = [comb for comb in itertools.combinations_with_replacement([2,5],i) if sum(comb) == val]
    ...:     return sum_perm[0] if sum_perm else None
    ...:

In [18]: val = 14

In [19]: next(correct_sum_i(i,val) for i in range(1000) if correct_sum_i(i, val))
Out[19]: (2, 2, 5, 5)
</code>```

Edit: You probably also want to check for pathological cases where this is not possible, like 1,3 etc....

Edit: all sums

```<code>In [50]: def all_sums(char_set, sum_value):
    ...:     def correct_sum_i(i):
    ...:
    ...:         sum_perm = [comb for comb in itertools.combinations_with_replacement(char_set,i) if sum(comb) == sum_value]
    ...:         return sum_perm if sum_perm else None
    ...:
    ...:     assert min(char_set)  > 0
    ...:
    ...:     return list(correct_sum_i(i) for i in range(int(sum_value / min(char_set))+ 1) if correct_sum_i(i))
    ...:

In [51]: print (all_sums([2,5], 20))
[[(5, 5, 5, 5)], [(2, 2, 2, 2, 2, 5, 5)], [(2, 2, 2, 2, 2, 2, 2, 2, 2, 2)]]
</code>```

this also gives you the desired behaviour for your case:

```<code>In [53]: print (all_sums([2,5], 17))
[[(2, 5, 5, 5)], [(2, 2, 2, 2, 2, 2, 5)]]
</code>```

Body:
If I have this simple code, how can I display all available variants ?

#Display all possible variants until reach input sum with coins of 2 and 5
#Not fixed: Output only first result !

#Input
summ = int(input("Enter sum: "))
two = 2
five = 5

#Calculations/Checks/Output
for i in range(0, two+1):
    for j in range(0, five+1):
        if (i*2 + j*5 == summ):
            print(i, "*2 + ", j, "*5 = ", summ)

#End

For example:

Input: 17

Output:
1*2 + 3*5 = 17
6*2 + 1*5 = 17

But the code displays only the first result?

How can I fix this ?

Body:
You can use itertools, and a generator:

In [17]: def correct_sum_i(i, val):
    ...:     sum_perm = [comb for comb in itertools.combinations_with_replacement([2,5],i) if sum(comb) == val]
    ...:     return sum_perm[0] if sum_perm else None
    ...:

In [18]: val = 14

In [19]: next(correct_sum_i(i,val) for i in range(1000) if correct_sum_i(i, val))
Out[19]: (2, 2, 5, 5)

Edit: You probably also want to check for pathological cases where this is not possible, like 1,3 etc....

Edit: all sums

In [50]: def all_sums(char_set, sum_value):
    ...:     def correct_sum_i(i):
    ...:
    ...:         sum_perm = [comb for comb in itertools.combinations_with_replacement(char_set,i) if sum(comb) == sum_value]
    ...:         return sum_perm if sum_perm else None
    ...:
    ...:     assert min(char_set)  > 0
    ...:
    ...:     return list(correct_sum_i(i) for i in range(int(sum_value / min(char_set))+ 1) if correct_sum_i(i))
    ...:

In [51]: print (all_sums([2,5], 20))
[[(5, 5, 5, 5)], [(2, 2, 2, 2, 2, 5, 5)], [(2, 2, 2, 2, 2, 2, 2, 2, 2, 2)]]

this also gives you the desired behaviour for your case:

In [53]: print (all_sums([2,5], 17))
[[(2, 5, 5, 5)], [(2, 2, 2, 2, 2, 2, 5)]]


问:
Perl too slow concurrent download with both HTTP::Async & Net::Async::HTTP
I'm trying to GET about 7 dozens of urls in parallel with scripts: the first is below, with HTTP::Async, and the second one is on pastebin, with Net::Async::HTTP.
The problem is that I'm getting pretty same timing results - about 8..14 seconds for all urls list. It's inacceptable slow compared to curl+xargs started from shell, which gets all in less than 3 seconds with 10-20 "threads".
For example, Devel::Timer in first script shows that max queue length is even less than 6 ($queue->in_progress_count<=5, $queue->to_send_count=0 allways). So, it's looks like foreach with $queue->add is executing too slow, and I don't know why.
Pretty same situation I got with Net::Async::HTTP (second script on pastebin), which is even slower than the first.

So, please, does anybody know, what I'm doing wrong? How can I get concurrent download speed at least compared to curl+xargs started from shell?

```<code>#!/usr/bin/perl -w
use utf8;
use strict;
use POSIX qw(ceil);
use XML::Simple;
use Data::Dumper;
use HTTP::Request;
use HTTP::Async;
use Time::HiRes qw(usleep time);
use Devel::Timer;

#settings
use constant passwd => 'ultramegahypapassword';
use constant agent => 'supa agent dev.alpha';
use constant timeout => 10;
use constant slots => 10;
use constant debug => 1;

my @qids;
my @xmlz;
my $queue = HTTP::Async->new(slots => slots,max_request_time => 10, timeout => timeout, poll_interval => 0.0001);
my %responses;
my @urlz = (
'http://testpodarki.afghanet/api/products/4577',
'http://testpodarki.afghanet/api/products/4653',
'http://testpodarki.afghanet/api/products/4652',
'http://testpodarki.afghanet/api/products/4571',
'http://testpodarki.afghanet/api/products/4572',
'http://testpodarki.afghanet/api/products/4666',
'http://testpodarki.afghanet/api/products/4576',
'http://testpodarki.afghanet/api/products/4574',
'http://testpodarki.afghanet/api/products/4651',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[3294]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[3294]',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/product_option_values/188',
'http://testpodarki.afghanet/api/product_option_values/191',
'http://testpodarki.afghanet/api/product_option_values/187',
'http://testpodarki.afghanet/api/product_option_values/190',
'http://testpodarki.afghanet/api/product_option_values/189',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4653]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4653]',
'http://testpodarki.afghanet/api/images/products/4577/12176',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4652]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4652]',
'http://testpodarki.afghanet/api/images/products/4653/12390',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/images/products/4652/12388',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/images/products/3294/8965',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/images/products/4571/12159',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4666]',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4666]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/images/products/4572/12168',
'http://testpodarki.afghanet/api/product_option_values/185',
'http://testpodarki.afghanet/api/product_option_values/182',
'http://testpodarki.afghanet/api/product_option_values/184',
'http://testpodarki.afghanet/api/product_option_values/183',
'http://testpodarki.afghanet/api/product_option_values/186',
'http://testpodarki.afghanet/api/images/products/4666/12413',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/images/products/4576/12174',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4651]',
'http://testpodarki.afghanet/api/images/products/4574/12171',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4651]',
'http://testpodarki.afghanet/api/images/products/4651/12387'
);

my $timer = Devel::Timer->new();

foreach my $el (@urlz) {
    my $request = HTTP::Request->new(GET => $el);
    $request->header(User_Agent => agent);
    $request->authorization_basic(passwd,'');
    push @qids,$queue->add($request);
    $timer->mark("pushed [$el], to_send=".$queue->to_send_count().", to_return=".$queue->to_return_count().", in_progress=".$queue->in_progress_count());
}

$timer->mark('requestz pushed');

while ($queue->in_progress_count) {
    usleep(2000);
    $queue->poke();
}

$timer->mark('requestz complited');

process_responses();

$timer->mark('responzez processed');

foreach my $q (@xmlz) {
#    print ">>>>>>".Dumper($q)."<<<<<<<<\n";
}

$timer->report();
print "\n\n";
</code>```

答:
My best results with HTTP::Async are well over 4 and up to over 5 seconds. As I understand this approach isn't required, and here is a simple forking example that takes a little over 2 and at most below 3 seconds.

It uses Parallel::ForkManager and LWP::UserAgent for downloads.

```<code>use warnings;
use strict;
use Path::Tiny;
use LWP::UserAgent;
use Parallel::ForkManager;

my @urls = @{ get_urls('https://pastebin.com/raw/VyhMEB3w') };

my $pm = new Parallel::ForkManager(60);  # max of 60 processes at a time
my $ua = LWP::UserAgent->new;
print "Downloading ", scalar @urls, " files.\n";

my $dir = 'downloaded_files/';
mkdir $dir if not -d $dir;
my $cnt = 0;
foreach my $link (@urls)
{
    my $file = "$dir/file_" . ++$cnt . '.txt';

    $pm->start and next;                        # child process

    # add code needed for actual pages (authorization etc)
    my $response = $ua->get($link);
    if ($response->is_success) {
        path($file)->spew_utf8($response->decoded_content);
    }
    else { warn $response->status_line }

    $pm->finish;                                # child exit
}
$pm->wait_all_children;

sub get_urls {
    my $resp = LWP::UserAgent->new->get($_[0]);
    return [ grep /^http:/, split /\s*'?,?\s*\n\s*'?/, $resp->decoded_content ];
};
</code>```

The files are written using Path::Tiny. Its path builds an object and spew routines write the file.

For reference, the sequential downloads take around 26 seconds.

With the maximum number of processes set to 30 this takes over 4 seconds, and with 60 it is a little over 2 seconds, about the same as with (up to) 90. There are 70 urls in this test.

Tested at a 4-core laptop with a decent network connection. (Here the CPU isn't all that important.)  The tests were run repeatedly, at multiple times and on multiple days.

A comparison with the approach from the question

The best HTTP::Async results are slower than the above by around a factor of two. They are with 30-40 "slots" since for higher numbers the time goes up, what puzzles (me). The module uses select to multiplex, via Net::HTTP::NB (a non-blocking version of Net::HTTP). While select "does not scale well" this regards hundreds of sockets and I'd expect to be able to use more than 40 on this network bound problem. The simple forked approach does.

Also, select is considered to be a slow method to monitor sockets while forks don't even need that, as each process has its own url. (This may result in module's overhead when there are many connections?)  Fork's inherent overhead is fixed and dwarfed by network access. If we were after (many) hundreds of downloads the system may get strained by processes, but select wouldn't fare well either.

Finally, select based methods download strictly one file at a time,
and the effect is seen by printing as requests are added -- we can see the delay. The forked downloads go in parallel (in this case all 70 at the same time  without a problem). Then there'll be a network or disk bottleneck but that is tiny in comparison to the gain.

Update: I pushed this to double the number of sites and processes, saw no signs of OS/CPU strain, and retained the average speed.

So I'd say, if you need to shave off every second use forks. But if this is not critical and there are other benefits of HTTP::Async (or such) then be content with (just a bit) longer downloads.

The HTTP::Async code that performs well ended up being simply

```<code>foreach my $link ( @urls ) {
    $async->add( HTTP::Request->new(GET => $link) );
}
while ( my $response = $async->wait_for_next_response ) {
    # write file (or process otherwise)
}
</code>```

I have also tried to tweak headers and timings. (This included dropping keep-alive as suggested, by $request->header(Connection => 'close'), to no effect.)

Body:
I'm trying to GET about 7 dozens of urls in parallel with scripts: the first is below, with HTTP::Async, and the second one is on pastebin, with Net::Async::HTTP.
The problem is that I'm getting pretty same timing results - about 8..14 seconds for all urls list. It's inacceptable slow compared to curl+xargs started from shell, which gets all in less than 3 seconds with 10-20 "threads".
For example, Devel::Timer in first script shows that max queue length is even less than 6 ($queue->in_progress_count<=5, $queue->to_send_count=0 allways). So, it's looks like foreach with $queue->add is executing too slow, and I don't know why.
Pretty same situation I got with Net::Async::HTTP (second script on pastebin), which is even slower than the first.

So, please, does anybody know, what I'm doing wrong? How can I get concurrent download speed at least compared to curl+xargs started from shell?

#!/usr/bin/perl -w
use utf8;
use strict;
use POSIX qw(ceil);
use XML::Simple;
use Data::Dumper;
use HTTP::Request;
use HTTP::Async;
use Time::HiRes qw(usleep time);
use Devel::Timer;

#settings
use constant passwd => 'ultramegahypapassword';
use constant agent => 'supa agent dev.alpha';
use constant timeout => 10;
use constant slots => 10;
use constant debug => 1;

my @qids;
my @xmlz;
my $queue = HTTP::Async->new(slots => slots,max_request_time => 10, timeout => timeout, poll_interval => 0.0001);
my %responses;
my @urlz = (
'http://testpodarki.afghanet/api/products/4577',
'http://testpodarki.afghanet/api/products/4653',
'http://testpodarki.afghanet/api/products/4652',
'http://testpodarki.afghanet/api/products/4571',
'http://testpodarki.afghanet/api/products/4572',
'http://testpodarki.afghanet/api/products/4666',
'http://testpodarki.afghanet/api/products/4576',
'http://testpodarki.afghanet/api/products/4574',
'http://testpodarki.afghanet/api/products/4651',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[3294]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[3294]',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4577]',
'http://testpodarki.afghanet/api/product_option_values/188',
'http://testpodarki.afghanet/api/product_option_values/191',
'http://testpodarki.afghanet/api/product_option_values/187',
'http://testpodarki.afghanet/api/product_option_values/190',
'http://testpodarki.afghanet/api/product_option_values/189',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4653]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4653]',
'http://testpodarki.afghanet/api/images/products/4577/12176',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4652]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4652]',
'http://testpodarki.afghanet/api/images/products/4653/12390',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4571]',
'http://testpodarki.afghanet/api/images/products/4652/12388',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/images/products/3294/8965',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4572]',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/images/products/4571/12159',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4666]',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4666]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4576]',
'http://testpodarki.afghanet/api/images/products/4572/12168',
'http://testpodarki.afghanet/api/product_option_values/185',
'http://testpodarki.afghanet/api/product_option_values/182',
'http://testpodarki.afghanet/api/product_option_values/184',
'http://testpodarki.afghanet/api/product_option_values/183',
'http://testpodarki.afghanet/api/product_option_values/186',
'http://testpodarki.afghanet/api/images/products/4666/12413',
'http://testpodarki.afghanet/api/combinations/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4574]',
'http://testpodarki.afghanet/api/product_option_values/177',
'http://testpodarki.afghanet/api/product_option_values/181',
'http://testpodarki.afghanet/api/images/products/4576/12174',
'http://testpodarki.afghanet/api/product_option_values/176',
'http://testpodarki.afghanet/api/product_option_values/180',
'http://testpodarki.afghanet/api/product_option_values/179',
'http://testpodarki.afghanet/api/product_option_values/175',
'http://testpodarki.afghanet/api/product_option_values/178',
'http://testpodarki.afghanet/api/specific_prices/?display=full&filter[id_product]=[4651]',
'http://testpodarki.afghanet/api/images/products/4574/12171',
'http://testpodarki.afghanet/api/stock_availables/?display=full&filter[id_product]=[4651]',
'http://testpodarki.afghanet/api/images/products/4651/12387'
);

my $timer = Devel::Timer->new();

foreach my $el (@urlz) {
    my $request = HTTP::Request->new(GET => $el);
    $request->header(User_Agent => agent);
    $request->authorization_basic(passwd,'');
    push @qids,$queue->add($request);
    $timer->mark("pushed [$el], to_send=".$queue->to_send_count().", to_return=".$queue->to_return_count().", in_progress=".$queue->in_progress_count());
}

$timer->mark('requestz pushed');

while ($queue->in_progress_count) {
    usleep(2000);
    $queue->poke();
}

$timer->mark('requestz complited');

process_responses();

$timer->mark('responzez processed');

foreach my $q (@xmlz) {
#    print ">>>>>>".Dumper($q)."<<<<<<<<\n";
}

$timer->report();
print "\n\n";

Body:
My best results with HTTP::Async are well over 4 and up to over 5 seconds. As I understand this approach isn't required, and here is a simple forking example that takes a little over 2 and at most below 3 seconds.

It uses Parallel::ForkManager and LWP::UserAgent for downloads.

use warnings;
use strict;
use Path::Tiny;
use LWP::UserAgent;
use Parallel::ForkManager;

my @urls = @{ get_urls('https://pastebin.com/raw/VyhMEB3w') };

my $pm = new Parallel::ForkManager(60);  # max of 60 processes at a time
my $ua = LWP::UserAgent->new;
print "Downloading ", scalar @urls, " files.\n";

my $dir = 'downloaded_files/';
mkdir $dir if not -d $dir;
my $cnt = 0;
foreach my $link (@urls)
{
    my $file = "$dir/file_" . ++$cnt . '.txt';

    $pm->start and next;                        # child process

    # add code needed for actual pages (authorization etc)
    my $response = $ua->get($link);
    if ($response->is_success) {
        path($file)->spew_utf8($response->decoded_content);
    }
    else { warn $response->status_line }

    $pm->finish;                                # child exit
}
$pm->wait_all_children;

sub get_urls {
    my $resp = LWP::UserAgent->new->get($_[0]);
    return [ grep /^http:/, split /\s*'?,?\s*\n\s*'?/, $resp->decoded_content ];
};

The files are written using Path::Tiny. Its path builds an object and spew routines write the file.

For reference, the sequential downloads take around 26 seconds.

With the maximum number of processes set to 30 this takes over 4 seconds, and with 60 it is a little over 2 seconds, about the same as with (up to) 90. There are 70 urls in this test.

Tested at a 4-core laptop with a decent network connection. (Here the CPU isn't all that important.)  The tests were run repeatedly, at multiple times and on multiple days.

A comparison with the approach from the question

The best HTTP::Async results are slower than the above by around a factor of two. They are with 30-40 "slots" since for higher numbers the time goes up, what puzzles (me). The module uses select to multiplex, via Net::HTTP::NB (a non-blocking version of Net::HTTP). While select "does not scale well" this regards hundreds of sockets and I'd expect to be able to use more than 40 on this network bound problem. The simple forked approach does.

Also, select is considered to be a slow method to monitor sockets while forks don't even need that, as each process has its own url. (This may result in module's overhead when there are many connections?)  Fork's inherent overhead is fixed and dwarfed by network access. If we were after (many) hundreds of downloads the system may get strained by processes, but select wouldn't fare well either.

Finally, select based methods download strictly one file at a time,
and the effect is seen by printing as requests are added -- we can see the delay. The forked downloads go in parallel (in this case all 70 at the same time  without a problem). Then there'll be a network or disk bottleneck but that is tiny in comparison to the gain.

Update: I pushed this to double the number of sites and processes, saw no signs of OS/CPU strain, and retained the average speed.

So I'd say, if you need to shave off every second use forks. But if this is not critical and there are other benefits of HTTP::Async (or such) then be content with (just a bit) longer downloads.

The HTTP::Async code that performs well ended up being simply

foreach my $link ( @urls ) {
    $async->add( HTTP::Request->new(GET => $link) );
}
while ( my $response = $async->wait_for_next_response ) {
    # write file (or process otherwise)
}

I have also tried to tweak headers and timings. (This included dropping keep-alive as suggested, by $request->header(Connection => 'close'), to no effect.)


问:
Custom exception with Guava Preconditions
It's very simple question, I often use com.google.common.base.Preconditions in my projects to validate arguments and parameters, for example:

Preconditions.checkNotNull(parameter, "message");

Preconditions.checkArgument(parameter > 0, "message");

this code may produce IllegalArgumentException or NPE. But very often I need throw own exception.
How can I do it by this library? Or maybe you can advise another one?
thank you in advance!

UPDATE: I understand, that I can to create own simple utility class, but I'm interested to find ready-made solutions. Please, let me know, if somebody know it's possible.

答:
You could always make something like that for you own (I don't know why the guys from guava did not add it yet):</p>

```<code>public static void check(final boolean expression, RuntimeException exceptionToThrow) {
    if (!expression) {
        throw checkNotNull(exceptionToThrow);
    }
}

public static void check(final boolean expression, Supplier<? extends RuntimeException> exceptionToThrowSupplier) {
    if (!expression) {
        throw checkNotNull(exceptionToThrowSupplier).get();
    }
}
</code>```

Body:
You could always make something like that for you own (I don't know why the guys from guava did not add it yet):

public static void check(final boolean expression, RuntimeException exceptionToThrow) {
    if (!expression) {
        throw checkNotNull(exceptionToThrow);
    }
}

public static void check(final boolean expression, Supplier<? extends RuntimeException> exceptionToThrowSupplier) {
    if (!expression) {
        throw checkNotNull(exceptionToThrowSupplier).get();
    }
}


问:
Include different fonts in an HTML document
I have to add a folder with a font family that has different styles (bold, light, etc.), the fonts are in .ot, .ttf and .woff. The font family and the main folder where the fonts are is called HKExplorerSoft.

How should I add these fonts to the projects and how can I use them later in my CSS? I understand I have to create a @font-face rule, something like:

```<code>@font-face {
  font-family: 'HKExplorerSoft';
  src: url('assets/HKExplorerSoft/hkexplorersoft-black-webfont.woff');
}
</code>```

But that doesn't work or I'm not sure how to use this in the CSS later.

答:
with use this way</p>

```<code>.className{
  font-family: 'HKExplorerSoft';
}
</code>```

Body:
I have to add a folder with a font family that has different styles (bold, light, etc.), the fonts are in .ot, .ttf and .woff. The font family and the main folder where the fonts are is called HKExplorerSoft.

How should I add these fonts to the projects and how can I use them later in my CSS? I understand I have to create a @font-face rule, something like:

@font-face {
  font-family: 'HKExplorerSoft';
  src: url('assets/HKExplorerSoft/hkexplorersoft-black-webfont.woff');
}

But that doesn't work or I'm not sure how to use this in the CSS later.

Body:
with use this way

.className{
  font-family: 'HKExplorerSoft';
}


问:
Creating a spinning pie chart (wheel) android
I have created an Pie chart which I want to spin randomly and stop on click.

Then my android program needs to read which value is above.

I already got this:

```<code>    PieDataSet dataSet = new PieDataSet(yvalues, "");

    ArrayList<String> xVals = new ArrayList<String>();
    ArrayList<Integer> colors = new ArrayList<Integer>();
    pieChart.setDrawHoleEnabled(false);
    pieChart.animateXY(1400, 1400);

    pieChart.getLegend().setEnabled(false);
    pieChart.setDrawSliceText(false);
    dataSet.setDrawValues(false);
    xVals.add("Correct");
    xVals.add("Wrong");
    colors.add(Color.rgb(115, 255, 134));
    colors.add(Color.rgb(255, 115, 115));
    dataSet.setColors(colors);
    pieChart.setDescription("");

    PieData data = new PieData(xVals, dataSet);

    data.setValueFormatter(new PercentFormatter());
    data.setValueTextSize(18f);
    data.setValueTextColor(Color.BLACK);
    pieChart.setData(data);
    pieChart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            pieChart.spin( 500,0,-360f, Easing.EasingOption.EaseInOutQuad);
        }
    });
</code>```

I don't know how to spin this chart on click and stop it randomly.

Then I need to get the value of the chart which is spinned.

答:
You can use this library.
(Easy and simple implementation of PieChart with Scatter)
This library will fulfill all the requirements you have mentioned above.

https://android-arsenal.com/details/1/4492

Body:
I have created an Pie chart which I want to spin randomly and stop on click.

Then my android program needs to read which value is above.

I already got this:

    PieDataSet dataSet = new PieDataSet(yvalues, "");

    ArrayList<String> xVals = new ArrayList<String>();
    ArrayList<Integer> colors = new ArrayList<Integer>();
    pieChart.setDrawHoleEnabled(false);
    pieChart.animateXY(1400, 1400);

    pieChart.getLegend().setEnabled(false);
    pieChart.setDrawSliceText(false);
    dataSet.setDrawValues(false);
    xVals.add("Correct");
    xVals.add("Wrong");
    colors.add(Color.rgb(115, 255, 134));
    colors.add(Color.rgb(255, 115, 115));
    dataSet.setColors(colors);
    pieChart.setDescription("");

    PieData data = new PieData(xVals, dataSet);

    data.setValueFormatter(new PercentFormatter());
    data.setValueTextSize(18f);
    data.setValueTextColor(Color.BLACK);
    pieChart.setData(data);
    pieChart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            pieChart.spin( 500,0,-360f, Easing.EasingOption.EaseInOutQuad);
        }
    });

I don't know how to spin this chart on click and stop it randomly.

Then I need to get the value of the chart which is spinned.


问:
Should i be using the uvm_component/object_utils macros
I see a lot of articles which talk about whether you should be using field macros.

General guideline is:

```<code>`uvm_do... macro:
</code>```

Can be used, but try to avoid if you are lazy.

```<code>`uvm_field... macro:
</code>```

Avoid like the plague.

Sure, people also tell not to use

```<code>`uvm_component_param_utils...
`uvm_object_param_utils...
</code>```

But i cannot seem to find what anyone thinks about the

```<code>`uvm_component_utils...
`uvm_object_utils...
</code>```

Should they be avoided? Or they can be used without much issues?

Thanks :)

答:
I taught my first ever UVM course this week (with the Doulos CTO - John Aynsley - sitting in as backup). In his assessment of my performance, he said this about macros, which I'm sure he won't mind me repeating:

`uvm_component_utils and friends - a good thing

`uvm_do and friends - a bit naughty

Field macros - evil

Body:
I see a lot of articles which talk about whether you should be using field macros.

General guideline is:

`uvm_do... macro:

Can be used, but try to avoid if you are lazy.

`uvm_field... macro:

Avoid like the plague.

Sure, people also tell not to use

`uvm_component_param_utils...
`uvm_object_param_utils...

But i cannot seem to find what anyone thinks about the

`uvm_component_utils...
`uvm_object_utils...

Should they be avoided? Or they can be used without much issues?

Thanks :)


问:
Passing an object to custom view in Google maps SDK
I have custom view (a nib with its class) that I show when user taps on map marker. I also have an array of objects from where I'd like to show data of selected object when user taps on one of the markers. I create markers from the same array in a separate method. How to I get my element in array (to show additional data) when user taps the marker ? Or is there another way to get the object from array based on pressed marker. Apart from regexing based on lon and lat etc ?</p>

答:
GMSMapViewDelegate has the delegate function which lets you to return
  your customView as info window.

```<code>optional public func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView?
</code>```

You have to subclass GSMarker which takes your model in init.

```<code>class MapItem:GMSMarker {
    var model: Model!  //your data model
    init(data: Model) {
        super.init()
        // pass cordinate
        self.position = CLLocationCoordinate2D(latitude: data.latitude!, longitude: data.longitude!)
        // pass Model
        self.model = data
    }
}

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
    // Wrap GSMarker to your custom marker which is MapItem here
    let customMarker = marker as! MapItem
      // pass your model to CustomView(marker info window) in init
    let customView = CustomView(markerModel: customMarker.model)
    return customView
}
</code>```

Body:
GMSMapViewDelegate has the delegate function which lets you to return
  your customView as info window.

optional public func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView?

You have to subclass GSMarker which takes your model in init.

class MapItem:GMSMarker {
    var model: Model!  //your data model
    init(data: Model) {
        super.init()
        // pass cordinate
        self.position = CLLocationCoordinate2D(latitude: data.latitude!, longitude: data.longitude!)
        // pass Model
        self.model = data
    }
}

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
    // Wrap GSMarker to your custom marker which is MapItem here
    let customMarker = marker as! MapItem
      // pass your model to CustomView(marker info window) in init
    let customView = CustomView(markerModel: customMarker.model)
    return customView
}


问:
How to make protractor press the ESCAPE key?
I've tried this:

```<code>browser.actions().sendKeys(protractor.Key.ESCAPE).perform();
</code>```

but nothing happens.

I'm using this with SPACE Key and this works fine.

```<code>browser.actions().sendKeys(protractor.Key.SPACE).perform();
</code>```

答:
There could be several reasons for it, but first of all, according to the documentation of Protractor you need to execute the sendKeys() on an ElementFinder, so if the focus is on for example an input field you can do this

```<code>element(by.css('#-your-input-id')).sendKeys(protractor.Key.ESCAPE);
</code>```

You can also do it on the body like this ($ = shorthand for by.css):

```<code>$('body').sendKeys(protractor.Key.ESCAPE);
</code>```

Secondly there could be a problem with the UserInteraction API of your webdriver. In the past there were a lot of problems with the Firefox and Safari driver and with some versions of Chromedriver.

Hope this helps

Body:
I've tried this:

browser.actions().sendKeys(protractor.Key.ESCAPE).perform();

but nothing happens.

I'm using this with SPACE Key and this works fine.

browser.actions().sendKeys(protractor.Key.SPACE).perform();

Body:
There could be several reasons for it, but first of all, according to the documentation of Protractor you need to execute the sendKeys() on an ElementFinder, so if the focus is on for example an input field you can do this

element(by.css('#-your-input-id')).sendKeys(protractor.Key.ESCAPE);

You can also do it on the body like this ($ = shorthand for by.css):

$('body').sendKeys(protractor.Key.ESCAPE);

Secondly there could be a problem with the UserInteraction API of your webdriver. In the past there were a lot of problems with the Firefox and Safari driver and with some versions of Chromedriver.

Hope this helps


问:
Mysql connecting issue in django 1.9
I am getting the following error when trying to connect mysql db

```<code>[Fri Mar 31 09:04:54.154874 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] mod_wsgi (pid=16451): Target WSGI script '/home/abhadran/network_python3/netmap/netmap/wsgi.py' cannot be loaded as Python module.
[Fri Mar 31 09:04:54.154920 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] mod_wsgi (pid=16451): Exception occurred processing WSGI script '/home/abhadran/network_python3/netmap/netmap/wsgi.py'.
[Fri Mar 31 09:04:54.154942 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] Traceback (most recent call last):
[Fri Mar 31 09:04:54.154960 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/abhadran/network_python3/netmap/netmap/wsgi.py", line 21, in <module>
[Fri Mar 31 09:04:54.156034 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     application = get_wsgi_application()
[Fri Mar 31 09:04:54.156062 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
[Fri Mar 31 09:04:54.156125 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     django.setup()
[Fri Mar 31 09:04:54.156140 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
[Fri Mar 31 09:04:54.156170 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     apps.populate(settings.INSTALLED_APPS)
[Fri Mar 31 09:04:54.156182 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
[Fri Mar 31 09:04:54.156290 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     app_config.import_models(all_models)
[Fri Mar 31 09:04:54.156310 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models
[Fri Mar 31 09:04:54.156373 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     self.models_module = import_module(models_module_name)
[Fri Mar 31 09:04:54.156392 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
[Fri Mar 31 09:04:54.156462 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     __import__(name)
[Fri Mar 31 09:04:54.156478 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module>
[Fri Mar 31 09:04:54.156614 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
[Fri Mar 31 09:04:54.156636 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 49, in <module>
[Fri Mar 31 09:04:54.156715 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     class AbstractBaseUser(models.Model):
[Fri Mar 31 09:04:54.156732 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/base.py", line 108, in __new__
[Fri Mar 31 09:04:54.157044 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     new_class.add_to_class('_meta', Options(meta, app_label))
[Fri Mar 31 09:04:54.157061 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/base.py", line 307, in add_to_class
[Fri Mar 31 09:04:54.157078 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     value.contribute_to_class(cls, name)
[Fri Mar 31 09:04:54.157098 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/options.py", line 263, in contribute_to_class
[Fri Mar 31 09:04:54.157316 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
[Fri Mar 31 09:04:54.157335 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/__init__.py", line 36, in __getattr__
[Fri Mar 31 09:04:54.157383 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     return getattr(connections[DEFAULT_DB_ALIAS], item)
[Fri Mar 31 09:04:54.157398 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/utils.py", line 212, in __getitem__
[Fri Mar 31 09:04:54.157479 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     backend = load_backend(db['ENGINE'])
[Fri Mar 31 09:04:54.157492 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/utils.py", line 116, in load_backend
[Fri Mar 31 09:04:54.157505 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     return import_module('%s.base' % backend_name)
[Fri Mar 31 09:04:54.157513 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
[Fri Mar 31 09:04:54.157523 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     __import__(name)
[Fri Mar 31 09:04:54.157529 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 28, in <module>
[Fri Mar 31 09:04:54.157625 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
[Fri Mar 31 09:04:54.157650 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] ImproperlyConfigured: Error loading MySQLdb module: this is MySQLdb version (1, 3, 10, 'final', 0), but _mysql is version (1, 2, 3, 'final', 0)
</code>```

I am using django 1.9 version with python3.5.3. I have python installtion manually . Is this problem because of that??. Even after unistalling mysql client I am getting the above error.

pip freeze

```<code>configparser2==4.0.0
Django==1.9.12
django-tastypie==0.13.3
mod-wsgi==4.5.15
python-dateutil==2.6.0
python-mimeparse==1.6.0
requests==2.13.0
six==1.10.0
</code>```

答:
Can you try this instead?

```<code>pip install MySQL-python
</code>```

That's how I get MySQL to work with Django (using 1.8.8 version though).

Title: Mysql connecting issue in django 1.9

Body:
I am getting the following error when trying to connect mysql db

[Fri Mar 31 09:04:54.154874 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] mod_wsgi (pid=16451): Target WSGI script '/home/abhadran/network_python3/netmap/netmap/wsgi.py' cannot be loaded as Python module.
[Fri Mar 31 09:04:54.154920 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] mod_wsgi (pid=16451): Exception occurred processing WSGI script '/home/abhadran/network_python3/netmap/netmap/wsgi.py'.
[Fri Mar 31 09:04:54.154942 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] Traceback (most recent call last):
[Fri Mar 31 09:04:54.154960 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/abhadran/network_python3/netmap/netmap/wsgi.py", line 21, in <module>
[Fri Mar 31 09:04:54.156034 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     application = get_wsgi_application()
[Fri Mar 31 09:04:54.156062 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
[Fri Mar 31 09:04:54.156125 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     django.setup()
[Fri Mar 31 09:04:54.156140 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
[Fri Mar 31 09:04:54.156170 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     apps.populate(settings.INSTALLED_APPS)
[Fri Mar 31 09:04:54.156182 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
[Fri Mar 31 09:04:54.156290 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     app_config.import_models(all_models)
[Fri Mar 31 09:04:54.156310 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models
[Fri Mar 31 09:04:54.156373 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     self.models_module = import_module(models_module_name)
[Fri Mar 31 09:04:54.156392 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
[Fri Mar 31 09:04:54.156462 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     __import__(name)
[Fri Mar 31 09:04:54.156478 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module>
[Fri Mar 31 09:04:54.156614 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
[Fri Mar 31 09:04:54.156636 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 49, in <module>
[Fri Mar 31 09:04:54.156715 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     class AbstractBaseUser(models.Model):
[Fri Mar 31 09:04:54.156732 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/base.py", line 108, in __new__
[Fri Mar 31 09:04:54.157044 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     new_class.add_to_class('_meta', Options(meta, app_label))
[Fri Mar 31 09:04:54.157061 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/base.py", line 307, in add_to_class
[Fri Mar 31 09:04:54.157078 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     value.contribute_to_class(cls, name)
[Fri Mar 31 09:04:54.157098 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/models/options.py", line 263, in contribute_to_class
[Fri Mar 31 09:04:54.157316 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
[Fri Mar 31 09:04:54.157335 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/__init__.py", line 36, in __getattr__
[Fri Mar 31 09:04:54.157383 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     return getattr(connections[DEFAULT_DB_ALIAS], item)
[Fri Mar 31 09:04:54.157398 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/utils.py", line 212, in __getitem__
[Fri Mar 31 09:04:54.157479 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     backend = load_backend(db['ENGINE'])
[Fri Mar 31 09:04:54.157492 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/utils.py", line 116, in load_backend
[Fri Mar 31 09:04:54.157505 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     return import_module('%s.base' % backend_name)
[Fri Mar 31 09:04:54.157513 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
[Fri Mar 31 09:04:54.157523 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     __import__(name)
[Fri Mar 31 09:04:54.157529 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]   File "/home/webdev01/pythonev3/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 28, in <module>
[Fri Mar 31 09:04:54.157625 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314]     raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
[Fri Mar 31 09:04:54.157650 2017] [wsgi:error] [pid 16451] [remote 173.1.101.95:62314] ImproperlyConfigured: Error loading MySQLdb module: this is MySQLdb version (1, 3, 10, 'final', 0), but _mysql is version (1, 2, 3, 'final', 0)

I am using django 1.9 version with python3.5.3. I have python installtion manually . Is this problem because of that??. Even after unistalling mysql client I am getting the above error.

pip freeze

configparser2==4.0.0
Django==1.9.12
django-tastypie==0.13.3
mod-wsgi==4.5.15
python-dateutil==2.6.0
python-mimeparse==1.6.0
requests==2.13.0
six==1.10.0

Body:
Can you try this instead?

pip install MySQL-python

That's how I get MySQL to work with Django (using 1.8.8 version though).


问:
Appending to XML with XMLStreamWriter
Basically the app writes the contents of a Collection to XML. I'm using XMLStreamWriter (XMLOutputFactory.newInstance().createXMLStreamWriter(...)) for this purpose.

Works great except for the fact that I can't get how to append data to an existing file. Don't really like the idea of reading all of it first, appending the data in memory and then overwriting. Or is it the only way?

答: Simply appending to an XML file will result in malformed XML.  You should build the DOM and attach what new elements you need.</p>

OwnerDisplayName: gsmd

Title: Appending to XML with XMLStreamWriter

OwnerDisplayName: Phil