问:
I Couldn't split the values .... Im wondering why (var = amt1) values are not giving space
I Couldn't split the values. I'm wondering why in the (var = amt1) values are not giving space. therefore in the alert(amt1) getting values like 100$200$300$. I should supposed to get 100$ 200$ 300$.

```<code>jQuery(document).ready(function(){
  jQuery("#pa_ssl").one('change',function(){
    var amt1 = jQuery("form.cart_group").find(".component.paged:eq(0)").find("span.woocommerce-Price-amount.amount").text();
    alert(amt1);//i need (100$ 200$ 300$) insteat of (100$200$300$)

    var single_amt = amt1.split("Rs.");
    var amount1 = single_amt[1];
    alert(amount1);

    jQuery(".component_inner .composited_product_details_wrapper").append("Rs." + amount1 + "<br/>");
  });
});
</code>```

答:
Working fine!</p>

```<code>jQuery(document).ready(function(){
jQuery("#pa_ssl").one('change',function(){

var amt1 = jQuery("form.cart_group").find(".component.paged:eq(0)").find(".woocommerce-variation-price span.woocommerce-Price-amount.amount").text();
var single_amt = amt1.split("Rs.");
var amount1 = single_amt[0];

jQuery(".component_inner .composited_product_details_wrapper").append("Rs." +amount1+"<br/>");

});
});
</code>```

Body:
I Couldn't split the values. I'm wondering why in the (var = amt1) values are not giving space. therefore in the alert(amt1) getting values like 100$200$300$. I should supposed to get 100$ 200$ 300$.

jQuery(document).ready(function(){
  jQuery("#pa_ssl").one('change',function(){
    var amt1 = jQuery("form.cart_group").find(".component.paged:eq(0)").find("span.woocommerce-Price-amount.amount").text();
    alert(amt1);//i need (100$ 200$ 300$) insteat of (100$200$300$)

    var single_amt = amt1.split("Rs.");
    var amount1 = single_amt[1];
    alert(amount1);

    jQuery(".component_inner .composited_product_details_wrapper").append("Rs." + amount1 + "
");
  });
});

Body:
Working fine!

jQuery(document).ready(function(){
jQuery("#pa_ssl").one('change',function(){

var amt1 = jQuery("form.cart_group").find(".component.paged:eq(0)").find(".woocommerce-variation-price span.woocommerce-Price-amount.amount").text();
var single_amt = amt1.split("Rs.");
var amount1 = single_amt[0];

jQuery(".component_inner .composited_product_details_wrapper").append("Rs." +amount1+"<br/>");

});
});


来源: stackexchange

问:
default input border shows differently on div
If I create an input box without any styles (<input>) and then inspect the computed css in devtools I see it has border 2px inset rgb(238, 238, 238)

However if I create a div with the same border it looks very different:

<input>

```

Why is that ? and what kind of border will give me the same one as the input ?

答:
Like this?

<input>

```

ContentLicense: CC BY-SA 3.0

Body:
If I create an input box without any styles (<input>) and then inspect the computed css in devtools I see it has border 2px inset rgb(238, 238, 238)

However if I create a div with the same border it looks very different:

<input>

Why is that ? and what kind of border will give me the same one as the input ?

Body:
Like this?

<input>
<br><br>
<div style="border: 1px solid rgba(0, 0, 0, 0.4); height:15px; width: 169px; "></div>


问:
Yii2 is it possible to run rest action within the app itself?
I have created a REST project in yii2 and i have some yaml data that should be stored in the database. These are crowd data, that is authorized people can add new yaml files and our app will parse those data and store in database.

But these data might change in the future (i.e. add/delete columns) which would rely on version of the REST api (v1.0, v2.0 etc)

Thus i would like to call the appropriate rest action to do it.

I know there is the function $controller->run() but how do i use it to make a POST or a PUT request?

Is there any alternative to using yii httpclient?

Thanks

答:
If I am not wrong, you want to execute different action depending on the version of the API.

For that, you can create modules inside your frontend/backend directory and name the modules as per your versions. Whenever you have a new version create a new module and upgrade the version name. Thus you always get the proper versioning. So v1, v2.. will be modules in your project.

The good thing about this is that you can have same action name in different modules under same controller name. Thus if in version 1 you have 5 columns and the api is like /v1/data then you can have 7 columns in version 2 and the api can be like /v2/data.

For more details on modules: http://www.yiiframework.com/doc-2.0/guide-structure-modules.html


问:
What is the Regex for decimal numbers in Java?
I am not quite sure of what is the correct regex for the period in Java. Here are some of my attempts. Sadly, they all meant any character.

```<code>String regex = "[0-9]*[.]?[0-9]*";
String regex = "[0-9]*['.']?[0-9]*";
String regex = "[0-9]*["."]?[0-9]*";
String regex = "[0-9]*[\.]?[0-9]*";
String regex = "[0-9]*[\\.]?[0-9]*";
String regex = "[0-9]*.?[0-9]*";
String regex = "[0-9]*\.?[0-9]*";
String regex = "[0-9]*\\.?[0-9]*";
</code>```

But what I want is the actual "." character itself. Anyone have an idea?

What I'm trying to do actually is to write out the regex for a non-negative real number (decimals allowed). So the possibilities are: 12.2, 3.7, 2., 0.3, .89, 19

```<code>String regex = "[0-9]*['.']?[0-9]*";
Pattern pattern = Pattern.compile(regex);

String x = "5p4";
Matcher matcher = pattern.matcher(x);
System.out.println(matcher.find());
</code>```

The last line is supposed to print false but prints true anyway. I think my regex is wrong though.

答:
Update

To match non negative decimal number you need this regex:

```<code>^\d*\.\d+|\d+\.\d*$
</code>```

or in java syntax : "^\\d*\\.\\d+|\\d+\\.\\d*$"

```<code>String regex = "^\\d*\\.\\d+|\\d+\\.\\d*$"
String string = "123.43253";

if(string.matches(regex))
    System.out.println("true");
else
    System.out.println("false");
</code>```

Explanation for your original regex attempts:

```<code>[0-9]*\.?[0-9]*
</code>```

with java escape it becomes :

```<code>"[0-9]*\\.?[0-9]*";
</code>```

if you need to make the dot as mandatory you remove the ? mark:

```<code>[0-9]*\.[0-9]*
</code>```

but this will accept just a dot without any number as well... So, if you want the validation to consider number as mandatory you use + ( which means one or more) instead of *(which means zero or more). That case it becomes:

```<code>[0-9]+\.[0-9]+
</code>```

Body:
I am not quite sure of what is the correct regex for the period in Java. Here are some of my attempts. Sadly, they all meant any character.

String regex = "[0-9]*[.]?[0-9]*";
String regex = "[0-9]*['.']?[0-9]*";
String regex = "[0-9]*["."]?[0-9]*";
String regex = "[0-9]*[\.]?[0-9]*";
String regex = "[0-9]*[\\.]?[0-9]*";
String regex = "[0-9]*.?[0-9]*";
String regex = "[0-9]*\.?[0-9]*";
String regex = "[0-9]*\\.?[0-9]*";

But what I want is the actual "." character itself. Anyone have an idea?

What I'm trying to do actually is to write out the regex for a non-negative real number (decimals allowed). So the possibilities are: 12.2, 3.7, 2., 0.3, .89, 19

String regex = "[0-9]*['.']?[0-9]*";
Pattern pattern = Pattern.compile(regex);

String x = "5p4";
Matcher matcher = pattern.matcher(x);
System.out.println(matcher.find());

The last line is supposed to print false but prints true anyway. I think my regex is wrong though.

Body:
Update

To match non negative decimal number you need this regex:

^\d*\.\d+|\d+\.\d*$

or in java syntax : "^\\d*\\.\\d+|\\d+\\.\\d*$"

String regex = "^\\d*\\.\\d+|\\d+\\.\\d*$"
String string = "123.43253";

if(string.matches(regex))
    System.out.println("true");
else
    System.out.println("false");

Explanation for your original regex attempts:

[0-9]*\.?[0-9]*

with java escape it becomes :

"[0-9]*\\.?[0-9]*";

if you need to make the dot as mandatory you remove the ? mark:

[0-9]*\.[0-9]*

but this will accept just a dot without any number as well... So, if you want the validation to consider number as mandatory you use + ( which means one or more) instead of *(which means zero or more). That case it becomes:

[0-9]+\.[0-9]+


问:
Calculate value based on amount of green against blue and red
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

```<code>var red:int = 53;
var green:int = 150;
var blue:int = 28;
</code>```

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

```<code>var red:int = 0;
var green:int = 255;
var blue:int = 0;
</code>```

Would receive the highest score(10) and:

```<code>var red:int = 255;
var green:int = 0;
var blue:int = 255;
</code>```

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

答:
Unfortunately I'm not doog at Action script so can provide a real code but I think I have some ideas that might help you. AFAIU your problem is that you want to measure "greenishess" of the given RGB color taking into account all 3 components such that

green would get 100% raiting

red or blue or magenta would get 0%

white (equal mix of all 3) would get something in the middle

If I needed to devise such a scheme I'd switch from RGB to some different coloring scheme such as YUV or rather HSL/HSV. Actually the "H" component aka Hue seems to be what you need. Accodring to the wiki

Hue is one of the main properties (called color appearance parameters) of a color, defined technically (in the CIECAM02 model), as "the degree to which a stimulus can be described as similar to or different from stimuli that are described as red, green, blue, and yellow"

To calculate Hue you first need to determine Max and Min components and difference between them:

```<code> M = max(R, G, B)
 m = min(R, G, B)
 C = M - m
</code>```

then

```<code>If Red is the Max, then Hue = (G - B)/C
If Green is the Max, then Hue = 2.0 + (B - R)/C
If Blue is the Max, then Hue = 4.0 + (R - G)/C
</code>```

This produces values in [-1, 5] range. You might convert it to more conventional degrees multiplying it by 60 and wrapping arround to fir [0, 360] but this is not important as this is just a linear scale. So using the Hue calculated as defined earlier you can measure "greenishess" of the color by the Hue value being close to 2 (or in degrees to 120).

Notice that from this formula "greenishess" for colors close to green (i.e. one where the green is the Max component) is calculated as

```<code>"greenishess" = abs(B - R)/(G - min(B,R))
</code>```

which makes sense to me. The part where B = R specifies saturation of the color and only "excess" of R or B over the other shifts the color from the "pure" green to yellow or blue.

Note also, that you'll have to assign some arbitrary "greenishess" value to all "gray" colors from black to white as C would be 0 and you can't divide by 0.

Lastly you don't have to use Hue directly. You can build a more complicated formula basing on it. For example, you may put some cut off points to assign 0% rating to pure Red and Blue i.e. to everything beyond [0; 4] range (or [0; 240] in degrees). By default Hue would assign 0% only to Magenta which is {Red = 255, Green = 0, Blue = 255}. Something like

```<code>"greenishness" = [2 - abs(min(4, max(0, Hue)) - 2)] / 2 * 100%
</code>```

You also might "curve" the measurement by applying some non-linear transformation.

Body:
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

var red:int = 53;
var green:int = 150;
var blue:int = 28;

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

var red:int = 0;
var green:int = 255;
var blue:int = 0;

Would receive the highest score(10) and:

var red:int = 255;
var green:int = 0;
var blue:int = 255;

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

Body:
Unfortunately I'm not doog at Action script so can provide a real code but I think I have some ideas that might help you. AFAIU your problem is that you want to measure "greenishess" of the given RGB color taking into account all 3 components such that

green would get 100% raiting

red or blue or magenta would get 0%

white (equal mix of all 3) would get something in the middle

If I needed to devise such a scheme I'd switch from RGB to some different coloring scheme such as YUV or rather HSL/HSV. Actually the "H" component aka Hue seems to be what you need. Accodring to the wiki

Hue is one of the main properties (called color appearance parameters) of a color, defined technically (in the CIECAM02 model), as "the degree to which a stimulus can be described as similar to or different from stimuli that are described as red, green, blue, and yellow"

To calculate Hue you first need to determine Max and Min components and difference between them:

 M = max(R, G, B)
 m = min(R, G, B)
 C = M - m

then

If Red is the Max, then Hue = (G - B)/C
If Green is the Max, then Hue = 2.0 + (B - R)/C
If Blue is the Max, then Hue = 4.0 + (R - G)/C

This produces values in [-1, 5] range. You might convert it to more conventional degrees multiplying it by 60 and wrapping arround to fir [0, 360] but this is not important as this is just a linear scale. So using the Hue calculated as defined earlier you can measure "greenishess" of the color by the Hue value being close to 2 (or in degrees to 120).

Notice that from this formula "greenishess" for colors close to green (i.e. one where the green is the Max component) is calculated as

"greenishess" = abs(B - R)/(G - min(B,R))

which makes sense to me. The part where B = R specifies saturation of the color and only "excess" of R or B over the other shifts the color from the "pure" green to yellow or blue.

Note also, that you'll have to assign some arbitrary "greenishess" value to all "gray" colors from black to white as C would be 0 and you can't divide by 0.

Lastly you don't have to use Hue directly. You can build a more complicated formula basing on it. For example, you may put some cut off points to assign 0% rating to pure Red and Blue i.e. to everything beyond [0; 4] range (or [0; 240] in degrees). By default Hue would assign 0% only to Magenta which is {Red = 255, Green = 0, Blue = 255}. Something like

"greenishness" = [2 - abs(min(4, max(0, Hue)) - 2)] / 2 * 100%

You also might "curve" the measurement by applying some non-linear transformation.


问:
Xamarin CalendarContract
I'm creating a calendar in xamarin forms using DependencyService and creating events with this code:

```<code>ContentResolver cr = ((Activity)Forms.Context).ContentResolver;
ContentValues values = new ContentValues();
var uri = CalendarContract.Calendars.ContentUri;

values.Put(CalendarContract.Events.InterfaceConsts.CalendarId, Id);
values.Put(CalendarContract.Events.InterfaceConsts.Title, title);
values.Put(CalendarContract.Events.InterfaceConsts.Description, description);
values.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(year, month, day, hour, minute));
values.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(year, month, day, hour, minute));
values.Put(CalendarContract.Events.InterfaceConsts.AllDay, allday ? "1" : "0");
values.Put(CalendarContract.Events.InterfaceConsts.HasAlarm, hasalarm ? "1" : "0");
values.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "GMT+" + zone + ":00");
values.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "GMT+" + zone + ":00");

cr.Insert(CalendarContract.Events.ContentUri, values);
</code>```

What I exactly want is to add those events to a self-created calendar. How do I create a calendar first and then add the above events into it?

答:
For the layout I use CalendarView and a ListView to show the events for the selected date.
https://developer.xamarin.com/api/type/Android.Widget.CalendarView/
https://developer.xamarin.com/api/type/Android.Widget.ListView/

To populate the events I use Adapter. These are my function that are called when the date changed.

```<code>var eventsUri = CalendarContract.Events.ContentUri;
string[] eventsProjection = {
                CalendarContract.Events.InterfaceConsts.Id,
                CalendarContract.Events.InterfaceConsts.Title,
                CalendarContract.Events.InterfaceConsts.Dtstart,
                CalendarContract.Events.InterfaceConsts.Description
             };
string selection = CalendarContract.Events.InterfaceConsts.Dtstart + " >= ? AND " + CalendarContract.Events.InterfaceConsts.Dtstart + "<= ?";
string[] sourceColumns = {
                    CalendarContract.Events.InterfaceConsts.Title,
                    CalendarContract.Events.InterfaceConsts.Dtstart
                };
int[] targetResources = { Resource.Id.eventTitle, Resource.Id.eventStartDate };
var adapter = new SimpleCursorAdapter(context, Resource.Layout.EventListItem, cursor, sourceColumns, targetResources);
adapter.ViewBinder = new ViewBinder();
listview.Adapter = adapter;
</code>```

Title: Xamarin CalendarContract

Body:
I'm creating a calendar in xamarin forms using DependencyService and creating events with this code:

ContentResolver cr = ((Activity)Forms.Context).ContentResolver;
ContentValues values = new ContentValues();
var uri = CalendarContract.Calendars.ContentUri;

values.Put(CalendarContract.Events.InterfaceConsts.CalendarId, Id);
values.Put(CalendarContract.Events.InterfaceConsts.Title, title);
values.Put(CalendarContract.Events.InterfaceConsts.Description, description);
values.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(year, month, day, hour, minute));
values.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(year, month, day, hour, minute));
values.Put(CalendarContract.Events.InterfaceConsts.AllDay, allday ? "1" : "0");
values.Put(CalendarContract.Events.InterfaceConsts.HasAlarm, hasalarm ? "1" : "0");
values.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "GMT+" + zone + ":00");
values.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "GMT+" + zone + ":00");

cr.Insert(CalendarContract.Events.ContentUri, values);

What I exactly want is to add those events to a self-created calendar. How do I create a calendar first and then add the above events into it?

Body:
For the layout I use CalendarView and a ListView to show the events for the selected date.
https://developer.xamarin.com/api/type/Android.Widget.CalendarView/
https://developer.xamarin.com/api/type/Android.Widget.ListView/

To populate the events I use Adapter. These are my function that are called when the date changed.

var eventsUri = CalendarContract.Events.ContentUri;
string[] eventsProjection = {
                CalendarContract.Events.InterfaceConsts.Id,
                CalendarContract.Events.InterfaceConsts.Title,
                CalendarContract.Events.InterfaceConsts.Dtstart,
                CalendarContract.Events.InterfaceConsts.Description
             };
string selection = CalendarContract.Events.InterfaceConsts.Dtstart + " >= ? AND " + CalendarContract.Events.InterfaceConsts.Dtstart + "<= ?";
string[] sourceColumns = {
                    CalendarContract.Events.InterfaceConsts.Title,
                    CalendarContract.Events.InterfaceConsts.Dtstart
                };
int[] targetResources = { Resource.Id.eventTitle, Resource.Id.eventStartDate };
var adapter = new SimpleCursorAdapter(context, Resource.Layout.EventListItem, cursor, sourceColumns, targetResources);
adapter.ViewBinder = new ViewBinder();
listview.Adapter = adapter;


问:
How to reuse a method from another step definition class Appium/Cucumber/Java
Trying to reuse a method in another class, initialising the class like this:

```<code>public class SettingsStepDefs {
public Scenario scenario;

@Autowired
public AndroidBase androidBase;
public GenericStepDefs genericStepDefs;

@Before
public void before(Scenario scenario) {
    this.scenario = scenario;
    genericStepDefs = new GenericStepDefs();
</code>```

and then later using the method

```<code>genericStepDefs.iTapDone();
</code>```

However i am getting a Null pointer exception on the line above.

The code in iTapDone() is functional, if I copy the line and use it on SettingsStepDefs, it works.

Thank you in advance.

答:
You need to share an instance of GenericStepDefs between the steps. Since the variable genericStepDefs isn't set, you will get a NullPointerException.

You seem to be using Spring since you use the annotation @Autowired. Look into sharing state with Spring for Cucumber. It is done by setting up Spring for Cucumber-JVM. The dependency

```<code><dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-spring</artifactId>
    <version>1.2.5</version>
</dependency>
</code>```

is needed.

Body:
Trying to reuse a method in another class, initialising the class like this:

public class SettingsStepDefs {
public Scenario scenario;

@Autowired
public AndroidBase androidBase;
public GenericStepDefs genericStepDefs;

@Before
public void before(Scenario scenario) {
    this.scenario = scenario;
    genericStepDefs = new GenericStepDefs();

and then later using the method

genericStepDefs.iTapDone();

However i am getting a Null pointer exception on the line above.

The code in iTapDone() is functional, if I copy the line and use it on SettingsStepDefs, it works.

Thank you in advance.

Body:
You need to share an instance of GenericStepDefs between the steps. Since the variable genericStepDefs isn't set, you will get a NullPointerException.

You seem to be using Spring since you use the annotation @Autowired. Look into sharing state with Spring for Cucumber. It is done by setting up Spring for Cucumber-JVM. The dependency

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-spring</artifactId>
    <version>1.2.5</version>
</dependency>

is needed.


问:
Designing ASP MVC routing - listing child objects of specific objects with pagination and filtering
I have been looking at the feasibility of porting over an intranet web app from ASP DOTNET to ASP MVC. I have not yet decided whether or not this kind of framework would be suitable for the application.

One consideration is what the routing would look like...

The main use of the application is to CRUD 7 main types of objects, which, for illustration, include representations of customers, locations and persons. A customer can have multiple locations (< 10), which can each have many persons (maybe 1000s). Pages will either focus on the details or editing (often by multipage wizards -- another post though) of specific objects, or the listing out (with filtering) of sets of objects (eg persons) related to a particular object (eg a customer).

Just considering customers, beyond CRUD I will want to be able to list the various objects related to a specific customer (like locations and persons), page them, and also filter them by certain properties or keywords from a textbox. Currently, to view a customer's persons you would go to /customer?guid=1234#persons where there is a RadControls data grid containing all the persons (large request but bandwidth is not bottleneck).

So what would you recommend for routes?

Easy:

Customer/Edit/[GUID]

Harder:

Customer/List/[GUID]/Persons/[Page]?filter=xyz&paramX=YZ

or

Customer/List/Persons/customer=guid&...

or ...

答:
If you don't have an issue with your urls changing then maybe you could look at a REST style url for the functionality your provide (even though you're not returning Xml or JSON).

Customer/Persons/GUID/xyz/yz/

Nonetheless the option you provided last is better since it is more intuitive then the previous one.

I should add that you can use ASP.NET routing in a ASP.NET Webforms application as well. So there is no need to re-write your app in ASP.NET MVC.

If you're used to using the WebForms controls then you're better off using WebForms.

ContentLicense: CC BY-SA 2.5


问:
Calculate the percentage for python dictionary
I want to calculate the percentage of the occurrences of the values in a dictionary. d.values/sum(d.values)*100 it gives error: unsupported operand type(s) for /: 'list' and 'int' you cannot divide the whole list with any integer. I think, and I tried with  d=(Counter([Counter(i)['1'] for i in  f.readlines()])) at the time of counting you can calculate the percentage but it didn't work. If anyone has an idea, please let me known.

```<code>from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))
    print d

    p = d.values()
    X = np.arange(len(d))
    pl.bar(X, p, align='center',width=0.25)
    a = np.array(d.items())
    pl.xticks(X,d.keys())
    a = a[np.argsort(a[:,0])]
    #print a
    ymax=max(d.values())+1
    pl.ylim(0, 70000)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures")
    plt.title("Adder@1")
    pl.show()
</code>```

答:
For any dictionary d, whose values are integers, the percentage of the total represented by each item can be calculated and printed as follows:

```<code>s = sum(d.values())
for k, v in d.items():
    pct = v * 100.0 / s
    print(k, pct)
</code>```

numpy is overkill for this, and it's optimized for arrays rather than dictionaries.

Body:
I want to calculate the percentage of the occurrences of the values in a dictionary. d.values/sum(d.values)*100 it gives error: unsupported operand type(s) for /: 'list' and 'int' you cannot divide the whole list with any integer. I think, and I tried with  d=(Counter([Counter(i)['1'] for i in  f.readlines()])) at the time of counting you can calculate the percentage but it didn't work. If anyone has an idea, please let me known.

from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))
    print d

    p = d.values()
    X = np.arange(len(d))
    pl.bar(X, p, align='center',width=0.25)
    a = np.array(d.items())
    pl.xticks(X,d.keys())
    a = a[np.argsort(a[:,0])]
    #print a
    ymax=max(d.values())+1
    pl.ylim(0, 70000)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures")
    plt.title("Adder@1")
    pl.show()

Body:
For any dictionary d, whose values are integers, the percentage of the total represented by each item can be calculated and printed as follows:

s = sum(d.values())
for k, v in d.items():
    pct = v * 100.0 / s
    print(k, pct)

numpy is overkill for this, and it's optimized for arrays rather than dictionaries.


问:
Qt WebEngine set socks5 proxy
I want to set socks5 proxy for my Qt WebEngine app. I use PyQt5.8 , QT5.8.

I set up a socks5 server by danted v1.4.1. I test my socks5 server and it worked good. But when I use it in my app, danted log errors:

error after reading 3 bytes in 0 seconds: client offered no acceptable authentication method

This is my code:

```<code>def set_proxy():
    from PyQt5.QtNetwork import QNetworkProxy
    proxy = QNetworkProxy()

    from six.moves.urllib import parse as urlparse
    string_proxy = "socks5://username:password@ip:port"
    urlinfo = urlparse.urlparse(string_proxy)
    proxy = QNetworkProxy()
    if urlinfo.scheme == 'socks5':
        proxy.setType(QNetworkProxy.Socks5Proxy)
    else:
        proxy.setType(QNetworkProxy.NoProxy)
    if urlinfo.hostname != None:
        proxy.setHostName(urlinfo.hostname)
    if urlinfo.port != None:
        proxy.setPort(urlinfo.port)
    if urlinfo.username != None:
        proxy.setUser(urlinfo.username)
    else:
        proxy.setUser('')
    if urlinfo.password != None:
        proxy.setPassword(urlinfo.password)
    else:
        proxy.setPassword('')
    QNetworkProxy.setApplicationProxy(proxy)
</code>```

Can anyone help me?

update on 2017/03/29

add proxyAuthenticationRequired signal

```<code>def set_proxy(string_proxy):
    proxy = QNetworkProxy()
    urlinfo = urlparse.urlparse(string_proxy)
    if urlinfo.scheme == 'socks5':
        proxy.setType(QNetworkProxy.Socks5Proxy)
    elif urlinfo.scheme == 'http':
        proxy.setType(QNetworkProxy.HttpProxy)
    else:
        proxy.setType(QNetworkProxy.NoProxy)
    proxy.setHostName(urlinfo.hostname)
    proxy.setPort(urlinfo.port)
    proxy.setUser(urlinfo.username)
    proxy.setPassword(urlinfo.password)
    QNetworkProxy.setApplicationProxy(proxy)

def handleProxyAuthReq(url, auth, proxyhost):
    auth.setUser(username)
    auth.setPassword(password)

webView = QtWebEngineWidgets.QWebEngineView()
#proxy_string = "http://username:password@ip:port"
proxy_string = "socks5://username:password@ip:port"
set_proxy(proxy_string)
webView.page().proxyAuthenticationRequired.connect(handleProxyAuthReq)
</code>```

I test it by my Http proxy and it worded. But when I use Socks5 proxy, the proxyAuthenticationRequired signal can not be emited.

答:
QtWebEngine does not handle the username/password information from QNetworkProxy:

All other proxy settings such as QNetworkProxy::rawHeader(), QNetworkProxy::user(), or QNetworkProxy::password() are ignored.

You'll need to handle proxyAuthenticationRequired and handle authentication there.

update on 2017/03/30

Looks like Chromium does not support authentication with SOCKS proxies.

Title: Qt WebEngine set socks5 proxy

Body:
I want to set socks5 proxy for my Qt WebEngine app. I use PyQt5.8 , QT5.8.

I set up a socks5 server by danted v1.4.1. I test my socks5 server and it worked good. But when I use it in my app, danted log errors:

error after reading 3 bytes in 0 seconds: client offered no acceptable authentication method

This is my code:

def set_proxy():
    from PyQt5.QtNetwork import QNetworkProxy
    proxy = QNetworkProxy()

    from six.moves.urllib import parse as urlparse
    string_proxy = "socks5://username:password@ip:port"
    urlinfo = urlparse.urlparse(string_proxy)
    proxy = QNetworkProxy()
    if urlinfo.scheme == 'socks5':
        proxy.setType(QNetworkProxy.Socks5Proxy)
    else:
        proxy.setType(QNetworkProxy.NoProxy)
    if urlinfo.hostname != None:
        proxy.setHostName(urlinfo.hostname)
    if urlinfo.port != None:
        proxy.setPort(urlinfo.port)
    if urlinfo.username != None:
        proxy.setUser(urlinfo.username)
    else:
        proxy.setUser('')
    if urlinfo.password != None:
        proxy.setPassword(urlinfo.password)
    else:
        proxy.setPassword('')
    QNetworkProxy.setApplicationProxy(proxy)

Can anyone help me?

update on 2017/03/29

add proxyAuthenticationRequired signal

def set_proxy(string_proxy):
    proxy = QNetworkProxy()
    urlinfo = urlparse.urlparse(string_proxy)
    if urlinfo.scheme == 'socks5':
        proxy.setType(QNetworkProxy.Socks5Proxy)
    elif urlinfo.scheme == 'http':
        proxy.setType(QNetworkProxy.HttpProxy)
    else:
        proxy.setType(QNetworkProxy.NoProxy)
    proxy.setHostName(urlinfo.hostname)
    proxy.setPort(urlinfo.port)
    proxy.setUser(urlinfo.username)
    proxy.setPassword(urlinfo.password)
    QNetworkProxy.setApplicationProxy(proxy)

def handleProxyAuthReq(url, auth, proxyhost):
    auth.setUser(username)
    auth.setPassword(password)

webView = QtWebEngineWidgets.QWebEngineView()
#proxy_string = "http://username:password@ip:port"
proxy_string = "socks5://username:password@ip:port"
set_proxy(proxy_string)
webView.page().proxyAuthenticationRequired.connect(handleProxyAuthReq)

I test it by my Http proxy and it worded. But when I use Socks5 proxy, the proxyAuthenticationRequired signal can not be emited.


问:
jQuery - header flashes on and off
Hello guys here is my jQuery:

```<code><script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
    $( document ).ready(function() {
        $(window).scroll(function(){
            scroll = $(window).scrollTop();
            if (scroll > 100 && scroll < 300){
                $('#header').fadeOut();
            }

            if (scroll > 300){
                $('#header').fadeIn();
            }
        });
    });
</script>
</code>```

The #header is hidden by default, and I want it to unhide further down the page, but if I change any of the numbers in that jQuery the header will just flash on and off. I don't understand the code well enough to understand why that's happening.

答: i agree with @Adam Barker,also you can stop the animate queue:$('#header').stop(true).fadeIn();</p>

Title: jQuery - header flashes on and off

Body:
Hello guys here is my jQuery:

The #header is hidden by default, and I want it to unhide further down the page, but if I change any of the numbers in that jQuery the header will just flash on and off. I don't understand the code well enough to understand why that's happening.


问:
How do I use regexes properly in the matches() function (java)?
I am trying to make a registration form in Java that accepts a string in the form of: ok@ok.ok, right now, I have -

```<code>(email.matches("[^a-zA-Z0-9]+")
</code>```

which I need it to also accept @, _,-,. symbols but am unsure how to add it into the regex shown earlier.

As well as this I am aware that there is a way to separate to accept an amount of characters, and then read a specific symbol, (in my case it would be "@" and "." for the email) but am unable to implement it, something along the lines of

```<code>(email.matches("[^a-zA-Z0-9]{1-99}[1][@][^a-zA-Z0-9]{1-99}[1][.][^a-zA-Z0-9]+")
</code>```

Thanks

答:
You could try the following:

```<code>[^@]+@[^.]+\\..+
</code>```

Explanation:

```<code>[^@]+ - match everything up until the @ character
@     - match the @ character
[^.]+ - match everything up until the . character
\\.   - match the . character
.+    - match the rest
</code>```

In case you would like to access the different parts of the email address, i.e., what was provided before and after the @ sign, you can additionally wrap those parts of the expression in parenthesis (search for "groups" in the context of regular expressions to learn more about that).

Body:
I am trying to make a registration form in Java that accepts a string in the form of: ok@ok.ok, right now, I have -

(email.matches("[^a-zA-Z0-9]+")

which I need it to also accept @, _,-,. symbols but am unsure how to add it into the regex shown earlier.

As well as this I am aware that there is a way to separate to accept an amount of characters, and then read a specific symbol, (in my case it would be "@" and "." for the email) but am unable to implement it, something along the lines of

(email.matches("[^a-zA-Z0-9]{1-99}[1][@][^a-zA-Z0-9]{1-99}[1][.][^a-zA-Z0-9]+")

Thanks

Body:
You could try the following:

[^@]+@[^.]+\\..+

Explanation:

[^@]+ - match everything up until the @ character
@     - match the @ character
[^.]+ - match everything up until the . character
\\.   - match the . character
.+    - match the rest

In case you would like to access the different parts of the email address, i.e., what was provided before and after the @ sign, you can additionally wrap those parts of the expression in parenthesis (search for "groups" in the context of regular expressions to learn more about that).


问:
Read path in level compaction strategy in Cassandra
I want to know whether a read request goes from higher levels(L3, L4, having more sstables) to lower levels(L0, L1, having lesser sstables) or the other way round.

The problem with read requests going from higher levels to lower levels is that  a row in higher level sstable may contain obsolete data if the same row in a lower level sstable have been updated and not yet compacted to the higher level. Is that understanding correct?

On the other hand, going from lower level to higher levels won't ensure 90% read guarantee from a single sstable. In most cases, it will read all the levels.

答:
It does go from lower levels to higher levels... more or less. A mutation from HH, read repair, or sstables streamed over from an anti-entropy repair can put old rows in the lower levels which will mess that up a bit. TWCS handles that a bit better (but still really not great).

It will read at most one per level (exception L0 which is STCS), and walk the sstables in order of the sstables age (which tends to correspond with level). Once it has all the columns it wont have to read any older sstables so it can stop because it knows that even if theres any data in older sstables it is obsolete and will lose in the LWW conflict.

There are some situations around counters, unfrozen UDTS, and tombstones where it will have to read all the sstables though.

The 90% comes from the cases where there are no updates to partitions. Because theres also a bloom filter with 10% false positive rate (default for lcs) it will 90% (ish) hit only the one sstable.

With update heavy or wide rows like time series, one sstable in each level will likely have the requested partition. In which case it will have to walk all the levels. For those it will use the sstables min/max timestamps and min/max clustering index to only read whats necessary. In terms of filtering the min/max sstable partition, and clustering is actually the first thing done.

The metric from nodetool tablehistograms "sstables per read" is actually the number of sstables up for reading between the partition/clustering filtering and before the bloom filter check (since that may have to read from disk). So you can use that metric to see how many sstables are actually being considered and has disk seeks.


问:
Sending mail with attachments programmatically in ASP.NET
I am dynamically generating a number of different types of files based upon a GridView in ASP.NET - an Excel spreadsheet and a HTML file. I am doing so using this code (this is just for the Excel spreadsheet):

```<code>  Response.Clear();
  Response.AddHeader("content-disposition", "attachment;filename=InvoiceSummary" + Request.QueryString["id"] + ".xls");
  Response.Charset = "";

  Response.ContentType = "application/vnd.xls";
  System.IO.StringWriter stringWrite = new System.IO.StringWriter();
  System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
  contents.RenderControl(htmlWrite);
  //GridView1.RenderControl(htmlWrite);
  Response.Write(stringWrite.ToString());
  Response.End();
</code>```

I would like to give users the options of emailing the generated file as an attachment to either an email address they specify or one linked with their account on the database. But I don't want the user to have to save the file, then attach it in a form - I'd like to automatically attach the generated file. Is this possible, and how easy is it?

Of course, I'll be using the System.Net.Mail class to send mail...if it's possible anyway!

答:
Here is an working example of what I mentioned earlier, there is a little extra logic in the code to parse the GridView to a Table.</p>

```<code>        //Table to store our GridView Data
        Table table = new Table();

        //Parse our GridView into Table, stored in a StringBuilder
        StringBuilder sb = new StringBuilder();
        using (StringWriter sw = new StringWriter(sb))
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  header
                if (GridView1.HeaderRow != null)
                {
                    table.Rows.Add(GridView1.HeaderRow);
                }

                //  details
                foreach (GridViewRow row in GridView1.Rows)
                {
                    table.Rows.Add(row);
                }

                //  footer
                if (GridView1.FooterRow != null)
                {
                    table.Rows.Add(GridView1.FooterRow);
                }

                //  render table
                table.RenderControl(htw);
            }
        }

        using (MemoryStream memoryStream = new MemoryStream())
        {
            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                //Convert StringBuilder to MemoryStream
                writer.Write(sb.ToString());
                writer.Flush();

                //Create Message
                MailMessage message = new MailMessage();
                message.To.Add(new MailAddress("you@address.com", "You"));
                message.From = new MailAddress("me@address.com", "Me");
                message.Subject = "The Subject";

                //Create Attachment
                Attachment attachment = new Attachment(memoryStream, "InvoiceSummary.xls", "application/vnd.xls");

                //Attach Attachment to Email
                message.Attachments.Add(attachment);

                //Open SMTP connection to server and send
                SmtpClient smtp = new SmtpClient();
                smtp.Port = 25;
                smtp.Send(message);
            }
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am dynamically generating a number of different types of files based upon a GridView in ASP.NET - an Excel spreadsheet and a HTML file. I am doing so using this code (this is just for the Excel spreadsheet):

  Response.Clear();
  Response.AddHeader("content-disposition", "attachment;filename=InvoiceSummary" + Request.QueryString["id"] + ".xls");
  Response.Charset = "";

  Response.ContentType = "application/vnd.xls";
  System.IO.StringWriter stringWrite = new System.IO.StringWriter();
  System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
  contents.RenderControl(htmlWrite);
  //GridView1.RenderControl(htmlWrite);
  Response.Write(stringWrite.ToString());
  Response.End();

I would like to give users the options of emailing the generated file as an attachment to either an email address they specify or one linked with their account on the database. But I don't want the user to have to save the file, then attach it in a form - I'd like to automatically attach the generated file. Is this possible, and how easy is it?

Of course, I'll be using the System.Net.Mail class to send mail...if it's possible anyway!

Body:
Here is an working example of what I mentioned earlier, there is a little extra logic in the code to parse the GridView to a Table.

        //Table to store our GridView Data
        Table table = new Table();

        //Parse our GridView into Table, stored in a StringBuilder
        StringBuilder sb = new StringBuilder();
        using (StringWriter sw = new StringWriter(sb))
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  header
                if (GridView1.HeaderRow != null)
                {
                    table.Rows.Add(GridView1.HeaderRow);
                }

                //  details
                foreach (GridViewRow row in GridView1.Rows)
                {
                    table.Rows.Add(row);
                }

                //  footer
                if (GridView1.FooterRow != null)
                {
                    table.Rows.Add(GridView1.FooterRow);
                }

                //  render table
                table.RenderControl(htw);
            }
        }

        using (MemoryStream memoryStream = new MemoryStream())
        {
            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                //Convert StringBuilder to MemoryStream
                writer.Write(sb.ToString());
                writer.Flush();

                //Create Message
                MailMessage message = new MailMessage();
                message.To.Add(new MailAddress("you@address.com", "You"));
                message.From = new MailAddress("me@address.com", "Me");
                message.Subject = "The Subject";

                //Create Attachment
                Attachment attachment = new Attachment(memoryStream, "InvoiceSummary.xls", "application/vnd.xls");

                //Attach Attachment to Email
                message.Attachments.Add(attachment);

                //Open SMTP connection to server and send
                SmtpClient smtp = new SmtpClient();
                smtp.Port = 25;
                smtp.Send(message);
            }
        }


问:
Define number of parameters in AspectJ pointcut
I'd like to define a pointcut where the only important point is that the amount of parameters of the target method. For example, I have the following pointcut definition;

```<code>@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)
           && execution(* pkg..*.*(pkg.Obj1, pkg.Obj2, pkg.Obj3))")
</code>```

I do not wish to hardcode the expected parameter types, but I only wish to get the methods with only three parameters for this pointcut. How do I achieve this with only the information that there should be three parameters for the above pointcut, without specifying the details of parameters?

For example I want it to match;

```<code>// in package pkg.*
@RequestMapping
public test(ObjX objX, ObjY objY, ObjZ objZ) {
   //etc
}
</code>```

but not match the following;

```<code>// also in package pkg.*
@RequestMapping
public test(ObjX obj) {
   //etc
}
</code>```

or

```<code>// also in package pkg.*
@RequestMapping
public test(ObjX objX, ObjY objY) {
   //etc
}
</code>```

or

```<code>// also in package pkg.*
@RequestMapping
public test(ObjX objX, ObjY objY, ObjZ objZ, ObjQ objQ) {
   //etc
}
</code>```

答:
I've found it, the way to achieve this is to give * as the parameters;

```<code>@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)
           && execution(* xxx.yyy.zzz..*.*(*, *, *))")
</code>```

With the similar usage of * for return type, other class & method names.

Body:
I'd like to define a pointcut where the only important point is that the amount of parameters of the target method. For example, I have the following pointcut definition;

@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)
           && execution(* pkg..*.*(pkg.Obj1, pkg.Obj2, pkg.Obj3))")

I do not wish to hardcode the expected parameter types, but I only wish to get the methods with only three parameters for this pointcut. How do I achieve this with only the information that there should be three parameters for the above pointcut, without specifying the details of parameters?

For example I want it to match;

// in package pkg.*
@RequestMapping
public test(ObjX objX, ObjY objY, ObjZ objZ) {
   //etc
}

but not match the following;

// also in package pkg.*
@RequestMapping
public test(ObjX obj) {
   //etc
}

or

// also in package pkg.*
@RequestMapping
public test(ObjX objX, ObjY objY) {
   //etc
}

or

// also in package pkg.*
@RequestMapping
public test(ObjX objX, ObjY objY, ObjZ objZ, ObjQ objQ) {
   //etc
}

Body:
I've found it, the way to achieve this is to give * as the parameters;

@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)
           && execution(* xxx.yyy.zzz..*.*(*, *, *))")

With the similar usage of * for return type, other class & method names.


问:
Getting error in button position change in swift 3
I'm using the below-mentioned code for changing the position of button in swift 3 for 6s but I got the error like this Value of type '(Any) -> ()' has no member 'frame'. I'm stuck here</p>

```<code>if screenHeight == 667{

  //  self.forgetPasswordBtn.frame = CGRect(x: 0, y: 25, width: screenWidth, height: 30)
        nextBtn.frame.origin = CGRect(x:0,y:0)

    }
</code>```

答:
```<code>    button.frame.origin = CGPoint(x: 0.0, y: 0.0)
</code>```

it works for me ,can you show detail for the error ?

Body:
I'm using the below-mentioned code for changing the position of button in swift 3 for 6s but I got the error like this Value of type '(Any) -> ()' has no member 'frame'. I'm stuck here

if screenHeight == 667{

  //  self.forgetPasswordBtn.frame = CGRect(x: 0, y: 25, width: screenWidth, height: 30)
        nextBtn.frame.origin = CGRect(x:0,y:0)

    }

Body:
    button.frame.origin = CGPoint(x: 0.0, y: 0.0)

it works for me ,can you show detail for the error ?


答:
Actually you can not set the origin like this , you have to set frame of your button. And after all origin is the CGPoint not CGRect. So change you code with below and try.

```<code>nextBtn.frame = CGRect(x: 0, y: 0, width: nextBtn.frame.size.width, height: nextBtn.frame.size.height)
</code>```

Title: Getting error in button position change in swift 3

Body:
Actually you can not set the origin like this , you have to set frame of your button. And after all origin is the CGPoint not CGRect. So change you code with below and try.

nextBtn.frame = CGRect(x: 0, y: 0, width: nextBtn.frame.size.width, height: nextBtn.frame.size.height)


问:
Postgresql how to find item between datetime and in time zone
How could I query for a list of Products created_at between 12:01am Pacific on January 20 2015 and 11:59pm Pacific January 25 2015. All times stored in database are in UTC.

Would it be something along the lines of

```<code>SELECT * FROM products
WHERE  products.created_at >= '2015-01-20 00:01:00'  AT TIME ZONE 'PST'
AND    products.created_at <=  '2015-01-25 23:59:00'  AT TIME ZONE 'PST'
</code>```

答:
You could specify the UTC offset in your timestamps. US/Pacific is 8 hours behind UTC during Standard Time. So:</p>

```<code>SELECT * FROM products
WHERE  products.created_at >= '2015-01-20 00:01:00-08'
AND    products.created_at <=  '2015-01-25 23:59:00-08';
</code>```

Body:
How could I query for a list of Products created_at between 12:01am Pacific on January 20 2015 and 11:59pm Pacific January 25 2015. All times stored in database are in UTC.

Would it be something along the lines of

SELECT * FROM products
WHERE  products.created_at >= '2015-01-20 00:01:00'  AT TIME ZONE 'PST'
AND    products.created_at <=  '2015-01-25 23:59:00'  AT TIME ZONE 'PST'

Body:
You could specify the UTC offset in your timestamps. US/Pacific is 8 hours behind UTC during Standard Time. So:

SELECT * FROM products
WHERE  products.created_at >= '2015-01-20 00:01:00-08'
AND    products.created_at <=  '2015-01-25 23:59:00-08';


问:
New Prism Project - Use MEF or Unity?
I'm starting a new personal Prism 4 project. The Reference Implementation currently uses Unity.

I'd like to know if I should use MEF instead, or just keep to Unity.

I know a few discussions have mentioned that these two are different, and they do overlap, but will I be missing out if I simply choose Unity all the way?

答:
Also check out the documentation:

Key Decision: Choosing a Dependency Injection Container

The Prism Library provides two options
  for dependency injection containers:
  Unity or MEF. Prism is extensible,
  thereby allowing other containers to
  be used instead with a little bit of
  work. Both Unity and MEF provide the
  same basic functionality for
  dependency injection, even though they
  work very differently.

Some of the capabilities provided by both containers include the following:

They both register types with the container.

They both register instances with the container.

They both imperatively create instances of registered types.

They both inject instances of registered types into constructors.

They both inject instances of registered types into properties.

They both have declarative attributes for marking types and dependencies that need to be managed.

They both resolve dependencies in an object graph.

Unity provides several
capabilities that MEF does not:

It resolves concrete types without registration.

It resolves open generics.

It uses interception to capture calls to objects and add additional functionality to the target object.

MEF provides several
capabilities that Unity does not:

It discovers assemblies in a directory.

It uses XAP file download and assembly discovery.

It recomposes properties and collections as new types are discovered.

It automatically exports derived types.

It is deployed with the .NET Framework.

Title: New Prism Project - Use MEF or Unity?


问:
Avoid custom route duplication for Single Table Inheritance
I have a couple of types of Users (Mover and Movee) created using Simple Table Inheritance.  I am following a similar approach of passing in type in my routes as
STI, one controller.  But I find myself redefining the same custom routes in the base class and two subclasses.

Here is how the models look:

```<code>User
    name
    email
    address

Movee < User
    has_many: moves

Mover < User
</code>```

The moves under Movee will have its set of addresses.  The Mover will have an address as well as defined in the User model.  When the User first gets created, they just need the name and email, and the default user is of type Movee.

Then you can go to a page to update your address, this will turn you from a Movee to a Mover.

A Mover can re-update the address.  I have defined a custom edit_address action in the user model, since you can update the address as both a Movee (to turn yourself into a Mover), or as a Mover (if you need to re-update your the address).

user.rb

```<code>     def edit
     end

     def edit_address
     end

     def update_address
       @user.update(user_address_params)
       @user.type = "Mover"
       @user.save
     end

     def update
       @user.update(user_params)
     end

     def user_params
       params.require(params[:type].to_sym).permit(
            :first_name, :last_name,
            :type)
     end

     def user_address_params
       params.require(params[:type].to_sym).permit(:address)
     end
</code>```

The params hash for the edit_address action will look like

```<code>{
  movee: { address:  "some address"}
  type: "movee"
}
</code>```

In the navbar, I am pointing to a generic edit user path:

```<code><li><a href="<%= edit_address_user_path(current_user) %>"> Update Address</a></li>
</code>```

Now the routes duplication:

routes.rb

```<code>  resources :shmoovee,  path: :users, controller: :users, type: "shmoovee" do
    member do
      get :edit_address
      patch :update_address
    end
  end

  resources :shmoover,  path: :users, controller: :users, type: "shmoover" do
    member do
      get :edit_address
      patch :update_address
    end
  end

  resources :users do
    member do
      get :edit_address
      patch :update_address
    end
  end
</code>```

Question: Is there a way around the route duplications?  I need the subclass routes in order to pass in the type to resolve the strong params, but I also need the base class route in order to have the generic route helper edit_address_user_path used in the view.

答:
This is the routes I ended up with using routing-concerns:</p>

```<code>  concern :addressable do
    member do
      get :edit_address
      patch :update_address
    end
  end

  resources :shmoovee,  path: :users, controller: :users, type: "shmoovee", concerns: :addressable

  resources :shmoover,  path: :users, controller: :users, type: "shmoover", concerns: :addressable

  resources :users do
    concerns :addressable
    # other user routes
  end
</code>```

Body:
I have a couple of types of Users (Mover and Movee) created using Simple Table Inheritance.  I am following a similar approach of passing in type in my routes as
STI, one controller.  But I find myself redefining the same custom routes in the base class and two subclasses.

Here is how the models look:

User
    name
    email
    address

Movee < User
    has_many: moves

Mover < User

The moves under Movee will have its set of addresses.  The Mover will have an address as well as defined in the User model.  When the User first gets created, they just need the name and email, and the default user is of type Movee.

Then you can go to a page to update your address, this will turn you from a Movee to a Mover.

A Mover can re-update the address.  I have defined a custom edit_address action in the user model, since you can update the address as both a Movee (to turn yourself into a Mover), or as a Mover (if you need to re-update your the address).

user.rb

     def edit
     end

     def edit_address
     end

     def update_address
       @user.update(user_address_params)
       @user.type = "Mover"
       @user.save
     end

     def update
       @user.update(user_params)
     end

     def user_params
       params.require(params[:type].to_sym).permit(
            :first_name, :last_name,
            :type)
     end

     def user_address_params
       params.require(params[:type].to_sym).permit(:address)
     end

The params hash for the edit_address action will look like

{
  movee: { address:  "some address"}
  type: "movee"
}

In the navbar, I am pointing to a generic edit user path:

<a href="<%= edit_address_user_path(current_user) %>"> Update Address

Now the routes duplication:

routes.rb

  resources :shmoovee,  path: :users, controller: :users, type: "shmoovee" do
    member do
      get :edit_address
      patch :update_address
    end
  end

  resources :shmoover,  path: :users, controller: :users, type: "shmoover" do
    member do
      get :edit_address
      patch :update_address
    end
  end

  resources :users do
    member do
      get :edit_address
      patch :update_address
    end
  end

Question: Is there a way around the route duplications?  I need the subclass routes in order to pass in the type to resolve the strong params, but I also need the base class route in order to have the generic route helper edit_address_user_path used in the view.

Body:
This is the routes I ended up with using routing-concerns:

  concern :addressable do
    member do
      get :edit_address
      patch :update_address
    end
  end

  resources :shmoovee,  path: :users, controller: :users, type: "shmoovee", concerns: :addressable

  resources :shmoover,  path: :users, controller: :users, type: "shmoover", concerns: :addressable

  resources :users do
    concerns :addressable
    # other user routes
  end


问:
How to convert "/Date(1490065200000)/" to "21/03/2017"?
Please check in jsfiddle.

Code:

```<code>$( document ).ready(function() {
  var str = moment("/Date(1490065200000)/"); //Convert to "21/03/2017"
  console.log(str.toString());
});
</code>```

Here docs: https://momentjs.com/docs/#/parsing/asp-net-json-date/

Any Solution ?

答:
Hope i help you.

```<code>var str = moment("/Date(1490065200000)/").format("DD/MM/YYYY");
console.log(str);
</code>```

Body:
Please check in jsfiddle.

Code:

$( document ).ready(function() {
  var str = moment("/Date(1490065200000)/"); //Convert to "21/03/2017"
  console.log(str.toString());
});

Here docs: https://momentjs.com/docs/#/parsing/asp-net-json-date/

Any Solution ?

Body:
Hope i help you.

var str = moment("/Date(1490065200000)/").format("DD/MM/YYYY");
console.log(str);


问:
heatmap.2 does not show the color key
My codes:

```<code>heatmap.2(cor_r, cellnote = sym2, notecol = "black", key = T, keysize = 0.5, key.par = list, Rowv = as.dendrogram(hclust.signs), Colv = as.dendrogram(hclust.areas), trace = "none", margins = c(10,10), col = my_palette, breaks = col_breaks, lmat=rbind(4:3,2:1))
</code>```

Two problems:

No color key is shown.

When I rerun the codes, RStudio is broken down.

答: Though don't know why, "breaks = col_breaks" is the reason. Deleting this part will get everything right.</p>

Title: heatmap.2 does not show the color key

Body:
My codes:

heatmap.2(cor_r, cellnote = sym2, notecol = "black", key = T, keysize = 0.5, key.par = list, Rowv = as.dendrogram(hclust.signs), Colv = as.dendrogram(hclust.areas), trace = "none", margins = c(10,10), col = my_palette, breaks = col_breaks, lmat=rbind(4:3,2:1))

Two problems:

No color key is shown.

When I rerun the codes, RStudio is broken down.


问:
Cocoa Touch: What to release, when to release it?
I'm trying hard to understand when and what I must relase in Cocoa Touch as it doesn't have garbage collection.

This code block is from apples iphone sample PeriodicElements and they release anElement and rawElementArray but not thePath, firstLetter, existingArray and tempArray?

I would have thought that at least tempArray and existingArray should be released.

Could some brainy person please explain to me why?

Thanks :)

```<code>- (void)setupElementsArray {
NSDictionary *eachElement;

// create dictionaries that contain the arrays of element data indexed by
// name
self.elementsDictionary = [NSMutableDictionary dictionary];
// physical state
self.statesDictionary = [NSMutableDictionary dictionary];
// unique first characters (for the Name index table)
self.nameIndexesDictionary = [NSMutableDictionary dictionary];

// create empty array entries in the states Dictionary or each physical state
[statesDictionary setObject:[NSMutableArray array] forKey:@"Solid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Liquid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Gas"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Artificial"];

// read the element data from the plist
NSString *thePath = [[NSBundle mainBundle]  pathForResource:@"Elements" ofType:@"plist"];
NSArray *rawElementsArray = [[NSArray alloc] initWithContentsOfFile:thePath];

// iterate over the values in the raw elements dictionary
for (eachElement in rawElementsArray)
{
    // create an atomic element instance for each
    AtomicElement *anElement = [[AtomicElement alloc] initWithDictionary:eachElement];

    // store that item in the elements dictionary with the name as the key
    [elementsDictionary setObject:anElement forKey:anElement.name];

    // add that element to the appropriate array in the physical state dictionary
    [[statesDictionary objectForKey:anElement.state] addObject:anElement];

    // get the element's initial letter
    NSString *firstLetter = [anElement.name substringToIndex:1];
    NSMutableArray *existingArray;

    // if an array already exists in the name index dictionary
    // simply add the element to it, otherwise create an array
    // and add it to the name index dictionary with the letter as the key
    if (existingArray = [nameIndexesDictionary valueForKey:firstLetter])
    {
    [existingArray addObject:anElement];
    } else {
        NSMutableArray *tempArray = [NSMutableArray array];
        [nameIndexesDictionary setObject:tempArray forKey:firstLetter];
        [tempArray addObject:anElement];
    }

    // release the element, it is held by the various collections
    [anElement release];

}
// release the raw element data
[rawElementsArray release];

// create the dictionary containing the possible element states
// and presort the states data
self.elementPhysicalStatesArray = [NSArray arrayWithObjects:@"Solid",@"Liquid",@"Gas",@"Artificial",nil];
[self presortElementsByPhysicalState];

// presort the dictionaries now
// this could be done the first time they are requested instead

[self presortElementInitialLetterIndexes];

self.elementsSortedByNumber = [self presortElementsByNumber];
self.elementsSortedBySymbol = [self presortElementsBySymbol];
</code>```

}

答:
They create rawElementsArray by sending +alloc to the class, therefore this object is owned by the code in the sample above and must be released. Similarly with anElement. Note that thePath and tempArray are not created by sending +alloc, +new or -copy messages, therefore the calling code is not responsible for the lifetime of those objects. Please have a look at this collection of Cocoa memory management articles:

http://iamleeg.blogspot.com/2008/12/cocoa-memory-management.html

OwnerDisplayName: BJ McKay

Body:
I'm trying hard to understand when and what I must relase in Cocoa Touch as it doesn't have garbage collection.

This code block is from apples iphone sample PeriodicElements and they release anElement and rawElementArray but not thePath, firstLetter, existingArray and tempArray?

I would have thought that at least tempArray and existingArray should be released.

Could some brainy person please explain to me why?

Thanks :)

- (void)setupElementsArray {
NSDictionary *eachElement;

// create dictionaries that contain the arrays of element data indexed by
// name
self.elementsDictionary = [NSMutableDictionary dictionary];
// physical state
self.statesDictionary = [NSMutableDictionary dictionary];
// unique first characters (for the Name index table)
self.nameIndexesDictionary = [NSMutableDictionary dictionary];

// create empty array entries in the states Dictionary or each physical state
[statesDictionary setObject:[NSMutableArray array] forKey:@"Solid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Liquid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Gas"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Artificial"];

// read the element data from the plist
NSString *thePath = [[NSBundle mainBundle]  pathForResource:@"Elements" ofType:@"plist"];
NSArray *rawElementsArray = [[NSArray alloc] initWithContentsOfFile:thePath];

// iterate over the values in the raw elements dictionary
for (eachElement in rawElementsArray)
{
    // create an atomic element instance for each
    AtomicElement *anElement = [[AtomicElement alloc] initWithDictionary:eachElement];

    // store that item in the elements dictionary with the name as the key
    [elementsDictionary setObject:anElement forKey:anElement.name];

    // add that element to the appropriate array in the physical state dictionary
    [[statesDictionary objectForKey:anElement.state] addObject:anElement];

    // get the element's initial letter
    NSString *firstLetter = [anElement.name substringToIndex:1];
    NSMutableArray *existingArray;

    // if an array already exists in the name index dictionary
    // simply add the element to it, otherwise create an array
    // and add it to the name index dictionary with the letter as the key
    if (existingArray = [nameIndexesDictionary valueForKey:firstLetter])
    {
    [existingArray addObject:anElement];
    } else {
        NSMutableArray *tempArray = [NSMutableArray array];
        [nameIndexesDictionary setObject:tempArray forKey:firstLetter];
        [tempArray addObject:anElement];
    }

    // release the element, it is held by the various collections
    [anElement release];

}
// release the raw element data
[rawElementsArray release];

// create the dictionary containing the possible element states
// and presort the states data
self.elementPhysicalStatesArray = [NSArray arrayWithObjects:@"Solid",@"Liquid",@"Gas",@"Artificial",nil];
[self presortElementsByPhysicalState];

// presort the dictionaries now
// this could be done the first time they are requested instead

[self presortElementInitialLetterIndexes];

self.elementsSortedByNumber = [self presortElementsByNumber];
self.elementsSortedBySymbol = [self presortElementsBySymbol];

}


问:
How to set a dialog position to show at the center of the application?
How to set dialog's position that came from .ShowDialog(); to show at the center of the main window?

This is the way I try to set position.

```<code>private void Window_Loaded(object sender, RoutedEventArgs e)
{
    PresentationSource source = PresentationSource.FromVisual(this);
    if (source != null)
    {
        Left = ??
        Top = ??
    }
}
</code>```

答:
You can try to get a hold of the MainWindow in the Loaded event like this</p>

```<code>private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Application curApp = Application.Current;
    Window mainWindow = curApp.MainWindow;
    this.Left = mainWindow.Left + (mainWindow.Width - this.ActualWidth) / 2;
    this.Top = mainWindow.Top + (mainWindow.Height - this.ActualHeight) / 2;
}
</code>```

Body:
How to set dialog's position that came from .ShowDialog(); to show at the center of the main window?

This is the way I try to set position.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    PresentationSource source = PresentationSource.FromVisual(this);
    if (source != null)
    {
        Left = ??
        Top = ??
    }
}

Body:
You can try to get a hold of the MainWindow in the Loaded event like this

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Application curApp = Application.Current;
    Window mainWindow = curApp.MainWindow;
    this.Left = mainWindow.Left + (mainWindow.Width - this.ActualWidth) / 2;
    this.Top = mainWindow.Top + (mainWindow.Height - this.ActualHeight) / 2;
}


答:
Just type cast your Any type instance with UIButton like

```<code>if let btn = nextBtn as? UIButton {
   btn.frame.origin = CGRect(x:0,y:0)
}
</code>```

Then you are able to access 'frame' property.

Body:
Just type cast your Any type instance with UIButton like

if let btn = nextBtn as? UIButton {
   btn.frame.origin = CGRect(x:0,y:0)
}

Then you are able to access 'frame' property.


问:
How to calculate fan-in and fan-out in Xavier initialization for neural networks?
Variations I have found of the Xavier initialization for weights in a Neural Network all mention a fan-in and a fan-out; could you please tell how those two parameters are computed? Specifically for these two examples:

1) initializing the weights of a convolutional layer, with a filter of shape [5, 5, 3, 6] (width, height, input depth, output depth);

2) initializing the weights of a fully connected layer, with shape [400, 120] (i.e. mapping 400 input variables onto 120 output variables).

Thanks!

答:
My understanding is that the fan in and out of a convolutional layer are defined as:

```<code>fan_in = n_feature_maps_in * receptive_field_height * receptive_field_width
fan_out = n_feature_maps_out * receptive_field_height * receptive_field_width / max_pool_area
</code>```

where receptive_field_height and receptive_field_width correspond to those of the conv layer under consideration and max_pool_area is the product of the height and width of the max pooling that follows the convolution layer.

Please correct me if I'm wrong.

Source: deeplearning.net

Body:
My understanding is that the fan in and out of a convolutional layer are defined as:

fan_in = n_feature_maps_in * receptive_field_height * receptive_field_width
fan_out = n_feature_maps_out * receptive_field_height * receptive_field_width / max_pool_area

where receptive_field_height and receptive_field_width correspond to those of the conv layer under consideration and max_pool_area is the product of the height and width of the max pooling that follows the convolution layer.

Please correct me if I'm wrong.

Source: deeplearning.net


问:
python: can't open file get-pip.py error 2] no such file or directory
When I am trying to execute this in CMD

```<code>python get-pip.py
</code>```

I am getting this error:

```<code>python: can't open file get-pip.py error 2] no such file or directory
</code>```

While the file store in (get-pip.py)

C:\Python27\Tools\Scripts

答:
Go to this link - https://www.liquidweb.com/kb/how-to-install-pip-on-ubuntu-14-04-lts/

For me it installed in

vagrant@vagrant-ubuntu-trusty-64:/vagrant$ which pip
/usr/local/bin/pip

So there is a mistake in the post as the command
pip --help

will not work.

vagrant@vagrant-ubuntu-trusty-64:/vagrant$ pip --help
-bash: /usr/bin/pip: No such file or directory

But you still have pip installed.

Enjoy!

Body:
When I am trying to execute this in CMD

python get-pip.py

I am getting this error:

python: can't open file get-pip.py error 2] no such file or directory

While the file store in (get-pip.py)

C:\Python27\Tools\Scripts


问:
How to see exception generated into django template variable?
Inside a Django template, one can call an object method like this :

```<code>{{ my_object.my_method }}
</code>```

The problem is when you get an exception/bug in 'def my_method(self)', it is hidden when rendering the template (there is an empty string output instead, so no errors appears).

As I want to debug what's wrong in 'def my_method(self)', I would like to turn on something like a global django flag to receive such exception.

in settings.py, I already have

```<code>DEBUG = True
TEMPLATE_DEBUG = True
</code>```

I can receive many kind of template exceptions, but none when I trig an object method.

What can I do ?

答: Similar to S. Lott's answer, activate the management shell (python manage.py shell) and create the appropriate instance of my_object, call my_method. Or put exception handling in my_method and log the exception.</p>

Body:
Inside a Django template, one can call an object method like this :

{{ my_object.my_method }}

The problem is when you get an exception/bug in 'def my_method(self)', it is hidden when rendering the template (there is an empty string output instead, so no errors appears).

As I want to debug what's wrong in 'def my_method(self)', I would like to turn on something like a global django flag to receive such exception.

in settings.py, I already have

DEBUG = True
TEMPLATE_DEBUG = True

I can receive many kind of template exceptions, but none when I trig an object method.

What can I do ?


问:
Using promises to await triggered events
In the following code, thing is an external object that I don't control; I can't change how the event system of thing works. When fn is called, we return a promise whose executor listens to an event and then begins awaiting a series of functions which eventually result in that event being triggered:

```<code>function fn() {

  return new Promise(async function(resolve, reject) {

      // This handler must be attached before `c` is called
      thing.once('myEvent', function(e) {
        resolve(e.data); // done
      });

      // The order of these functions calls is important,
      // and they may produce errors that need to be handled.
      await a();
      await b();
      await c(); // this causes myEvent

  });

}
</code>```

This works fine, but I've been told that this is a promise anti-pattern and that I should make fn an async function. How would I do this? If I made fn an async function, then how could I resolve e.data from within the event handler?

Edit:

I've accepted Bergi's answer because it is helpful in explaining the anti-pattern and how it applies to this scenario. Having said that, I think the code above is more readable and shows explicitly what's happening so I'm going to keep it as is. This isn't the noob denouncing the best practices, it's just that for my use-case, following the rules makes things more complicated than they need to be. Of course, this leaves me open to certain problems, but I'll just have to live with that until I find a better way to do this.

答:
Don't do any awaiting inside the Promise constructor - you only should do the promisification of the asynchronous callback in  there:

```<code>async function fn() {
  await a();
  await b();
  await c(); // this causes myEvent
  return new Promise(function(resolve, reject) {
    thing.once('myEvent', function(e) {
      resolve(e.data); // done
    });
  });
}
</code>```

The thing that starts the process which eventually causes the event to be emitted is usually called inside the Promise executor callback as well (to catch synchronous exceptions), but usually it doesn't return a promise like your c function does.

Maybe this expresses the intent better:

```<code>async function fn() {
  await a();
  await b();
  const {data} = await new Promise(resolve => {
    thing.once('myEvent', resolve);
    thing.c(); // this causes myEvent
  });
  return data;
}
</code>```

Of course this assumes that you only need to start listening to the event when you've called the other ones. If you expect the event to fire before that, you essentially have a race with parallel execution - I'd recommend to use Promise.all in that case:

```<code>async function fn() {
  await a();
  await b();
  const [{data}, cResult] = await Promise.all([
    new Promise(resolve => thing.once('myEvent', resolve)),
    c()
  ]);
  return data;
}
</code>```

If you have node v11.13.0 or higher you can use the events.once method so that you don't have to build the promise yourself - and it also handles error events correctly:

```<code>import { once } from 'events';

async function fn () {
  await a()
  await b()
  await c()
  await once(thing, 'myEvent')
}
</code>```

Body:
In the following code, thing is an external object that I don't control; I can't change how the event system of thing works. When fn is called, we return a promise whose executor listens to an event and then begins awaiting a series of functions which eventually result in that event being triggered:

function fn() {

  return new Promise(async function(resolve, reject) {

      // This handler must be attached before `c` is called
      thing.once('myEvent', function(e) {
        resolve(e.data); // done
      });

      // The order of these functions calls is important,
      // and they may produce errors that need to be handled.
      await a();
      await b();
      await c(); // this causes myEvent

  });

}

This works fine, but I've been told that this is a promise anti-pattern and that I should make fn an async function. How would I do this? If I made fn an async function, then how could I resolve e.data from within the event handler?

Edit:

I've accepted Bergi's answer because it is helpful in explaining the anti-pattern and how it applies to this scenario. Having said that, I think the code above is more readable and shows explicitly what's happening so I'm going to keep it as is. This isn't the noob denouncing the best practices, it's just that for my use-case, following the rules makes things more complicated than they need to be. Of course, this leaves me open to certain problems, but I'll just have to live with that until I find a better way to do this.

Body:
Don't do any awaiting inside the Promise constructor - you only should do the promisification of the asynchronous callback in  there:

async function fn() {
  await a();
  await b();
  await c(); // this causes myEvent
  return new Promise(function(resolve, reject) {
    thing.once('myEvent', function(e) {
      resolve(e.data); // done
    });
  });
}

The thing that starts the process which eventually causes the event to be emitted is usually called inside the Promise executor callback as well (to catch synchronous exceptions), but usually it doesn't return a promise like your c function does.

Maybe this expresses the intent better:

async function fn() {
  await a();
  await b();
  const {data} = await new Promise(resolve => {
    thing.once('myEvent', resolve);
    thing.c(); // this causes myEvent
  });
  return data;
}

Of course this assumes that you only need to start listening to the event when you've called the other ones. If you expect the event to fire before that, you essentially have a race with parallel execution - I'd recommend to use Promise.all in that case:

async function fn() {
  await a();
  await b();
  const [{data}, cResult] = await Promise.all([
    new Promise(resolve => thing.once('myEvent', resolve)),
    c()
  ]);
  return data;
}

If you have node v11.13.0 or higher you can use the events.once method so that you don't have to build the promise yourself - and it also handles error events correctly:

import { once } from 'events';

async function fn () {
  await a()
  await b()
  await c()
  await once(thing, 'myEvent')
}


问:
Google Analytics with a fixed URL site
I have a issue to track the user navigation in a site with FIXED URLs

No matter where the user is the URL will always be http://www.myurl.com

And so in my report the user stay always be at the on http://www.myurl.com

I would like to know if i can add something to the tracking script to improve the user tracking data

```<code><!-- default google tacking code -->
<script>
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

        ga('create', $cod, 'auto');
        ga('send', 'pageview');

</script>
</code>```

UPDATE

My solution:

Main page

```<code>    <!-- default google tacking code -->

    $this->response->insertScript($this->_minify("

                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

                ga('create', '" . $cod . "', 'auto');
                ga('set', 'page', '" . $page . "');
                ga('send', 'pageview');

    "));
</code>```

Forms, reports, windows

```<code>    <!-- additional information -->

    $this->response->insertScript($this->_minify("

                ga('set', 'page', '" . $page . "');
                ga('send', 'pageview');

    "));
</code>```

答:
You can add a third parameter to the pageview call. This works as a virtual URL, i.e. the GA interface show it as a distinct URL in the reports despite the fact that it does not actually exist on the server. If you pass a distinct, meaningful value for every action of the user (or at least any action that changes the content enough to warrant a pageview) then you can tell what they've been up to.</p>

```<code> ga('send', 'pageview', '/my/virtual/url/');
</code>```

Title: Google Analytics with a fixed URL site

Body:
I have a issue to track the user navigation in a site with FIXED URLs

No matter where the user is the URL will always be http://www.myurl.com

And so in my report the user stay always be at the on http://www.myurl.com

I would like to know if i can add something to the tracking script to improve the user tracking data

UPDATE

My solution:

Main page

    $this->response->insertScript($this->_minify("

                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

                ga('create', '" . $cod . "', 'auto');
                ga('set', 'page', '" . $page . "');
                ga('send', 'pageview');

    "));

Forms, reports, windows

    $this->response->insertScript($this->_minify("

                ga('set', 'page', '" . $page . "');
                ga('send', 'pageview');

    "));

Body:
You can add a third parameter to the pageview call. This works as a virtual URL, i.e. the GA interface show it as a distinct URL in the reports despite the fact that it does not actually exist on the server. If you pass a distinct, meaningful value for every action of the user (or at least any action that changes the content enough to warrant a pageview) then you can tell what they've been up to.

 ga('send', 'pageview', '/my/virtual/url/');


问:
How do I escape values in SpEL?
I am writing some SpEL statements in XML, and I can't get the parser to determine when I need to escape a character.

I've attempted the following:

```<code><... property="someProperty" value="#{ someBean.aMethodOnTheBean('st\'ring') }" />
</code>```

However adding in the \' does not seem to escape that single quote and I keep receiving a parser exception.

Is there any way to escape these values?

答:
I modified to:

```<code>.... value="#{ someBean.aMethodOnTheBean("st'ring") }"
</code>```

This works, I remembered incorrectly that I had issues when using a double quote to input a string value into a SpEL function prior.

Below is the schema definition:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
       default-lazy-init="true"
       default-init-method="initialize">
</code>```

The XML validates properly in eclipse.  However my simplified example was not valid -- my apologies and good catch.  I am actually setting the value like this:

```<code><bean id="someBean" class="someClass">
    <property name="someList">
        <list>
            <value>"#{ anotherBean.methodOnBean("some'String") }"</value>
        </list>
    </property>
</bean>
</code>```

Title: How do I escape values in SpEL?

Body:
I am writing some SpEL statements in XML, and I can't get the parser to determine when I need to escape a character.

I've attempted the following:

<... property="someProperty" value="#{ someBean.aMethodOnTheBean('st\'ring') }" />

However adding in the \' does not seem to escape that single quote and I keep receiving a parser exception.

Is there any way to escape these values?

Body:
I modified to:

.... value="#{ someBean.aMethodOnTheBean("st'ring") }"

This works, I remembered incorrectly that I had issues when using a double quote to input a string value into a SpEL function prior.

Below is the schema definition:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
       default-lazy-init="true"
       default-init-method="initialize">

The XML validates properly in eclipse.  However my simplified example was not valid -- my apologies and good catch.  I am actually setting the value like this:

<bean id="someBean" class="someClass">
    <property name="someList">
        <list>
            <value>"#{ anotherBean.methodOnBean("some'String") }"</value>
        </list>
    </property>
</bean>


问:
Don't want to delete object when shared_ptr get out of scope --Closed
I have a situation that I have some code like this. We need to add child objects to a clean up list, which will delete these children later when the class get destroyed. But we wish to use set for internal safety reasons, and obviously the set has longer lifetime.

```<code>//This is will delete twice, if this is called later.
~classX(){
    cleanList.clear();
}

classX::addToCleanList(T* child){
    set<shared_ptr<T> > cleanList;

    shared_ptr<T> p = shared_ptr(child);

    //Set has a customized comparetor
    //If the set already has the object pointer, insert will fail
    //and the shared_ptr will get out of the scope
    cleanList.insert(p);
}
//When it gets out of scope, p will be destroyed.
</code>```

This will cause issue, since the child objects are still needed.

Any solution to this? I don't see unique_ptr or shared_ptr and move semantic
can avoid being deleted when they get out of the scope.

答: You shouldn't manage the object ownership only in your classX class. These objects probably need to be shared_ptrs in other code as well. These objects are passed to the addToCleanList function as a raw pointer from somewhere. Who owns those pointers? You should manage the lifetime of the objects in one central location if you can, and only use raw pointers in places where there is no ownership.</p>

Body:
I have a situation that I have some code like this. We need to add child objects to a clean up list, which will delete these children later when the class get destroyed. But we wish to use set for internal safety reasons, and obviously the set has longer lifetime.

//This is will delete twice, if this is called later.
~classX(){
    cleanList.clear();
}

classX::addToCleanList(T* child){
    set<shared_ptr<T> > cleanList;

    shared_ptr<T> p = shared_ptr(child);

    //Set has a customized comparetor
    //If the set already has the object pointer, insert will fail
    //and the shared_ptr will get out of the scope
    cleanList.insert(p);
}
//When it gets out of scope, p will be destroyed.

This will cause issue, since the child objects are still needed.

Any solution to this? I don't see unique_ptr or shared_ptr and move semantic
can avoid being deleted when they get out of the scope.


问:
Pulling specific values from nested dictionaries and arrays in JSON in Python
This is a more specific follow up to a previous question that I had asked. Basically, I am trying to pull specific data from a block of JSON text that I received back after processing a GET request. After limiting down to just items (by using the dict.items() method), I am left with the following JSON data (there is a ton of it but this is just a sample):

```<code>[('response',
  {'count': 84,
   'users': [{'location_id': 123456,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 36619222,
                   'is_prohibited': False,},
             {'location_id': 5556667,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 4567777,
                   'is_prohibited': False,}
</code>```

The data I am trying pull is the 'id' number (not 'location_id') for each one of these objects and put all of those numbers gathered into an array. I am struggling a bit though since I am not used to working with big JSON data structures like this where there are dictionaries and arrays nested within each other. Will I have to also run a loop to accomplish this?

Any help would be greatly appreciated as I am stuck at the moment. Thanks.

答:
It can be done as follows (some stringent conditional checking is involved to avoid exceptions being raised)</p>

```<code>inp=[('response',
  {'count': 84,
   'users': [{'location_id': 123456,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 36619222,
                   'is_prohibited': False},
             {'location_id': 5556667,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 4567777,
                   'is_prohibited': False},
                {'location_id': 5556667,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 4567777,
                   'is_prohibited': False},
            {'location_id': 5556667,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 4567777,
                   'is_prohibited': False}]})]
output=[]
for tup_el in inp:
    for el in tup_el:
        if type(el) is dict:
            if "users" in el.keys():
                if type(el["users"]) is list:
                    for obj in el["users"]:
                        if "id" in obj.keys():
                            output.append(obj['id'])
print output
</code>```

Body:
This is a more specific follow up to a previous question that I had asked. Basically, I am trying to pull specific data from a block of JSON text that I received back after processing a GET request. After limiting down to just items (by using the dict.items() method), I am left with the following JSON data (there is a ton of it but this is just a sample):

[('response',
  {'count': 84,
   'users': [{'location_id': 123456,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 36619222,
                   'is_prohibited': False,},
             {'location_id': 5556667,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 4567777,
                   'is_prohibited': False,}

The data I am trying pull is the 'id' number (not 'location_id') for each one of these objects and put all of those numbers gathered into an array. I am struggling a bit though since I am not used to working with big JSON data structures like this where there are dictionaries and arrays nested within each other. Will I have to also run a loop to accomplish this?

Any help would be greatly appreciated as I am stuck at the moment. Thanks.

Body:
It can be done as follows (some stringent conditional checking is involved to avoid exceptions being raised)

inp=[('response',
  {'count': 84,
   'users': [{'location_id': 123456,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 36619222,
                   'is_prohibited': False},
             {'location_id': 5556667,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 4567777,
                   'is_prohibited': False},
                {'location_id': 5556667,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 4567777,
                   'is_prohibited': False},
            {'location_id': 5556667,
                   'acx_audit': None,
                   'flash_backup_url': u'',
                   'flash_backup_url_secure': u'',
                   'flash_click_variable': None,
                   'folder': None,
                   'format': u'url-json',
                   'height': 1,
                   'id': 4567777,
                   'is_prohibited': False}]})]
output=[]
for tup_el in inp:
    for el in tup_el:
        if type(el) is dict:
            if "users" in el.keys():
                if type(el["users"]) is list:
                    for obj in el["users"]:
                        if "id" in obj.keys():
                            output.append(obj['id'])
print output


问:
Convert String to SecureString
How to convert String to SecureString?

答:
There is also another way to convert between SecureString and String.

1. String to SecureString

```<code>SecureString theSecureString = new NetworkCredential("", "myPass").SecurePassword;
</code>```

2. SecureString to String

```<code>string theString = new NetworkCredential("", theSecureString).Password;
</code>```

Here is the link

Title: Convert String to SecureString

Body: How to convert String to SecureString?

Body:
There is also another way to convert between SecureString and String.

1. String to SecureString

SecureString theSecureString = new NetworkCredential("", "myPass").SecurePassword;

2. SecureString to String

string theString = new NetworkCredential("", theSecureString).Password;

Here is the link