问:
ReactJS Not Found The requested URL /AboutMe was not found on this server
I created a react app (also use react-router) without server and I build it.
After I upload it to the hosting it works fine until I tried to write the url to the address bar,
it display  "Not Found The requested URL /AboutMe was not found on this server."

Do I need also to create a server to catch the url (/AboutMe) everytime I try to write it to the address bar?

```<code><Router history={history}>
                <React.Fragment>
                    <Switch>
                        <Route exact path = "/" render = {() => (<Home value = {info} />)} />
                        <Route exact path = "/AboutMe" render = {() => (<AboutMe value = {info} />)}/>
                        <Route component = {NotFound} />
                    </Switch>
                </React.Fragment>
</code>```

答:
Quick solution:
Use hash router like this:
import { HashRouter as Router, Route, Switch, Link } from 'react-router-dom';

Body:
I created a react app (also use react-router) without server and I build it.
After I upload it to the hosting it works fine until I tried to write the url to the address bar,
it display  "Not Found The requested URL /AboutMe was not found on this server."

Do I need also to create a server to catch the url (/AboutMe) everytime I try to write it to the address bar?

<Router history={history}>
                <React.Fragment>
                    <Switch>
                        <Route exact path = "/" render = {() => (<Home value = {info} />)} />
                        <Route exact path = "/AboutMe" render = {() => (<AboutMe value = {info} />)}/>
                        <Route component = {NotFound} />
                    </Switch>
                </React.Fragment>


来源: stackexchange

问:
Timeout when installing ruby gems
I'm trying to install the bundler gem using $ gem install bundler. When I execute the command, I receive the following response:

```<code>ERROR:  Could not find a valid gem 'bundler' (>= 0), here is why:
    Unable to download data from https://rubygems.org/ - Errno::ETIMEDOUT: Operation   timed out - connect(2) (https://api.rubygems.org/latest_specs.4.8.gz)
ERROR:  Possible alternatives: bundler
</code>```

In an effort to make sure I wasn't going crazy, I tried installing nokogiri:

```<code>ERROR:  Could not find a valid gem 'nokogiri' (>= 0), here is why:
  Unable to download data from https://rubygems.org/ - Errno::ETIMEDOUT: Operation timed out - connect(2) (https://api.rubygems.org/latest_specs.4.8.gz)
ERROR:  Possible alternatives: nokogiri
</code>```

And a2z:

```<code>ERROR:  Could not find a valid gem 'a2z' (>= 0), here is why:
  Unable to download data from https://rubygems.org/ - Errno::ETIMEDOUT: Operation timed out - connect(2) (https://api.rubygems.org/quick/Marshal.4.8/a2z-0.1.3.gemspec.rz)
</code>```

If anyone has experience this issue before and can help me out it would be greatly appreciated.

If it helps, I'm running MacOS Mavericks and have gem version 2.2.2.

答:
api.rubygems.org is having issues with IPV6 host address. I faced the same issue after I setup the ubuntu server in vbox. We need to configure it to use our host's IPV4 first and then try IPV6.

So we can change the priority by adding this line ti /etc/gai.conf:

```<code># Debian defaults.
precedence  ::1/128         50
precedence  ::/0            40
precedence  2002::/16       30
precedence  ::/96           20
precedence  ::ffff:0:0/96   10

# Low precedence for api.rubygems.org IPv6 addresses.
precedence  2a04:4e42::0/32  5
</code>```

And it worked like a charm!

ContentLicense: CC BY-SA 3.0

Title: Timeout when installing ruby gems

Body:
I'm trying to install the bundler gem using $ gem install bundler. When I execute the command, I receive the following response:

ERROR:  Could not find a valid gem 'bundler' (>= 0), here is why:
    Unable to download data from https://rubygems.org/ - Errno::ETIMEDOUT: Operation   timed out - connect(2) (https://api.rubygems.org/latest_specs.4.8.gz)
ERROR:  Possible alternatives: bundler

In an effort to make sure I wasn't going crazy, I tried installing nokogiri:

ERROR:  Could not find a valid gem 'nokogiri' (>= 0), here is why:
  Unable to download data from https://rubygems.org/ - Errno::ETIMEDOUT: Operation timed out - connect(2) (https://api.rubygems.org/latest_specs.4.8.gz)
ERROR:  Possible alternatives: nokogiri

And a2z:

ERROR:  Could not find a valid gem 'a2z' (>= 0), here is why:
  Unable to download data from https://rubygems.org/ - Errno::ETIMEDOUT: Operation timed out - connect(2) (https://api.rubygems.org/quick/Marshal.4.8/a2z-0.1.3.gemspec.rz)

If anyone has experience this issue before and can help me out it would be greatly appreciated.

If it helps, I'm running MacOS Mavericks and have gem version 2.2.2.

Body:
api.rubygems.org is having issues with IPV6 host address. I faced the same issue after I setup the ubuntu server in vbox. We need to configure it to use our host's IPV4 first and then try IPV6.

So we can change the priority by adding this line ti /etc/gai.conf:

# Debian defaults.
precedence  ::1/128         50
precedence  ::/0            40
precedence  2002::/16       30
precedence  ::/96           20
precedence  ::ffff:0:0/96   10

# Low precedence for api.rubygems.org IPv6 addresses.
precedence  2a04:4e42::0/32  5

And it worked like a charm!

ContentLicense: CC BY-SA 4.0


问:
Remove parent JSON element depending on child value
I have a JSON with lots of empty content:

```<code>{
    "items": [
        {
            "category": "login",
            "fields": [
                {
                    "label": "Name",
                    "value": "",
                },
                {
                    "label": "E-Mail",
                    "value": "",
                },
                {
                    "label": "Password",
                    "value": "123456",
                },
                {
                    "label": "Website",
                    "fields": [
                        {
                            "label": "Name X",
                            "value": ""
                        },
                        {
                            "label": "Name Y",
                            "value": "another one"
                        },…
                    ]
                },…
            ]
        },…
    ]
}
</code>```

The nesting goes several levels deeper. This shows only the first level. I want to delete all elements of "fields" (or whatever the array's key in deeper levels is), where their "value" is empty.

```<code>{
    "items": [
        {
            "category": "login",
            "fields": [
                {
                    "label": "Password",
                    "value": "123456",
                },
                {
                    "label": "Website",
                    "fields": [
                        {
                            "label": "Name Y",
                            "value": "another one"
                        },…
                    ]
                },…
            ]
        },…
    ]
}
</code>```

How can I do this in Javascript?

答:
use filter method,you could get a filtered array

it returned Boolean. if value  exist,it will be true

var list=JSON.parse(data)
list.items=list.items.map(val=>{
  val.fields=val.fields.filter(v=>v.value})
  return val
})
```

Body:
I have a JSON with lots of empty content:

{
    "items": [
        {
            "category": "login",
            "fields": [
                {
                    "label": "Name",
                    "value": "",
                },
                {
                    "label": "E-Mail",
                    "value": "",
                },
                {
                    "label": "Password",
                    "value": "123456",
                },
                {
                    "label": "Website",
                    "fields": [
                        {
                            "label": "Name X",
                            "value": ""
                        },
                        {
                            "label": "Name Y",
                            "value": "another one"
                        },…
                    ]
                },…
            ]
        },…
    ]
}

The nesting goes several levels deeper. This shows only the first level. I want to delete all elements of "fields" (or whatever the array's key in deeper levels is), where their "value" is empty.

{
    "items": [
        {
            "category": "login",
            "fields": [
                {
                    "label": "Password",
                    "value": "123456",
                },
                {
                    "label": "Website",
                    "fields": [
                        {
                            "label": "Name Y",
                            "value": "another one"
                        },…
                    ]
                },…
            ]
        },…
    ]
}

How can I do this in Javascript?


问:
Equivalent of NMI and B3 for multilabel extrinsic clustering evaluation metrics
Normalized Mutual Information (NMI) and B3 are used for extrinsic clustering evaluation metrics when each instance (sample) has only one label.

What are equivalent metrics when each instance (sample) has only one label?

For example, in first image, we see [apple, orange, pears], in second image, we see [orange, lime, lemon] and in third image, we see [apple], and in the forth image we see [orange]. Then, if put first image and last image in the one cluster it is good, and if put third and forth image in one cluster is bad.

Application: Many popular datasets for object detection or image segmentation have multi labels for each image. If we used this data for classification (not detection and not segmentation), we have multiple labels for each image.

Note: My task is unsupervised clustering, not supervised classification. I know that for supervised classification, we can use top-5 or top-10 score. But I do not know what will be in unsupervised clustering.

答:
If the multi-labels are still sparse, then you can use Element-centric similarity, Omega Index, or Overlapping NMI (I dont recommend the last, it has severe biases).  All three are implemented in the python package, CluSim.

If the multi-labels are dense, then you are into fuzzy clustering comparison.  There are several divergence measures for membership functions, including L1-norm, Euclidean distance, KL-divergence, but I'm not aware of a literature arguing for one method over another.


问:
Is .thenValue() blocking?
In a lot of places I find something like :

```<code>std::move(A).thenValue(B)
</code>```

Is thenValue() blocking on the future "A". I read through Folly documentation but couldn't understand it.
https://github.com/facebook/folly/blob/master/folly/docs/Futures.md

答:
No, it is not blocking.  Conceptually, you can think of the signature like this (though this is not the actual signature):

```<code>template <typename T>
template <typename TResult>
Future<TResult> Future<T>::thenValue(std::function<TResult(T&&)> callback) { ... }
</code>```

The basic idea is that if the future represented by std::move(A) succeeds, the passed callback (B) will be executed, passing in the value that the A future produced.  The callback's return value becomes the result of the future returned by thenValue().

If you're a visual person (like me) then perhaps labeling parts of the signature will help:

```<code>template <typename T>
template <typename TResult>
Future<TResult> Future<T>::thenValue(std::function<TResult(T&&)> callback) { ... }
^^^^^^^^^^^^^^^ ^^^^^^^^^                                        ^^^^^^^^
       3            1                                                2
</code>```

The future you are invoking thenValue on.

The callback function you pass to thenValue.

The future returned by thenValue.

When (1) has a successful result, (2) is invoked with that result.  When (2) returns, (3) produces the return value of (2).

The future (3) is constructed synchronously, but the callback (2) is invoked asynchronously.

Title: Is .thenValue() blocking?

Body:
In a lot of places I find something like :

std::move(A).thenValue(B)

Is thenValue() blocking on the future "A". I read through Folly documentation but couldn't understand it.
https://github.com/facebook/folly/blob/master/folly/docs/Futures.md

Body:
No, it is not blocking.  Conceptually, you can think of the signature like this (though this is not the actual signature):

template <typename T>
template <typename TResult>
Future<TResult> Future<T>::thenValue(std::function<TResult(T&&)> callback) { ... }

The basic idea is that if the future represented by std::move(A) succeeds, the passed callback (B) will be executed, passing in the value that the A future produced.  The callback's return value becomes the result of the future returned by thenValue().

If you're a visual person (like me) then perhaps labeling parts of the signature will help:

template <typename T>
template <typename TResult>
Future<TResult> Future<T>::thenValue(std::function<TResult(T&&)> callback) { ... }
^^^^^^^^^^^^^^^ ^^^^^^^^^                                        ^^^^^^^^
       3            1                                                2

The future you are invoking thenValue on.

The callback function you pass to thenValue.

The future returned by thenValue.

When (1) has a successful result, (2) is invoked with that result.  When (2) returns, (3) produces the return value of (2).

The future (3) is constructed synchronously, but the callback (2) is invoked asynchronously.


问:
Expose C# classes in .net 4 class library to Silverlight App
I have a bunch of classes in a C# class library that I bought from a 3rd party company.

I want to use these classes and create my classes by inheriting them.
I have it all working on a .net 4 wpf application.

I want to then use these classes in my silverlight application.

What options do I have and which is the best option?
I want to use it in such a way that I can update the 3rd party company's DLL as they release their new version every month.

Just to re-inforce few points:

We have few options.
1. Link the classes (as an adding existing item but with a link)
2. Create interfaces and share them amongst WCF as a link class and let all classes inherit the interface
3. Use RIA service and let the web app create auto code to expose it to silverlight.

Are there other options? and if not then which one is better for the scenario that I am facing?

Thanks

答:
If you don't have the source code, you can't reference the class library in your Silverlight application (as you probably know already). It is not possible to use standard .NET libraries in Silverlight without recompiling, because Silverlight is a different framework and a different CLR.

You can use the library on the server and create some services to access the functionality.

I don't think there is any other way to achieve your goal, unless you get the source code which you can put into a directory with the name Shared. It will then be copied to your Silverlight application and compiled in Silverlight.


问:
TypeScript function overloading with passing a variable
I'm trying to use TypeScript function overloading:

```<code>function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations): T;
function useEntityTranslation<T extends Translation>(entity: null): {};

function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations | null): T | {} {
  // do smth and return T or {}
}
</code>```

It works if I call it these ways:

```<code>useEntityTranslation<ProductTranslation>(product); // EntityWithTranslations type
useEntityTranslation<ProductTranslation>(null);
</code>```

But if product is of type EntityWithTranslations | null (it's in React component: null until an entity is retrieved from api)

```<code>useEntityTranslation<ProductTranslation>(product); // EntityWithTranslations | null
</code>```

TypeScript throws an error No overload matches this call.

It's because the type EntityWithTranslations | null is not assignable to any of the two overloads.

But how can I make it understandable for TypeScript?

UPDATE:

The problem also is I can't use a received value as a known type

```<code>const translation = useEntityTranslation<ProductTranslation>(product);
translation.name // name doesn't exist in {}
</code>```

My workaround is to add one more overload:

```<code>function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations | null): { [name: string]: any }
</code>```

I use translation if product isn't null, so I'm sure translation is of type ProductTranslation.

Not awesome (translation.name -> any) but at least works

答:
As you noted, TypeScript does not resolve overloads by allowing unions of arguments from different call signatures.  There is a longstanding open suggestion, microsoft/TypeScript#14107, asking for this to happen, but for now it is not part of the language.

The easiest way to deal with this for a small number of call signatures is to add new call signatures corresponding to each union of arguments you want to support.  In your case, you could add a single overload signature that happens to be the same as your implementation signature:

```<code>function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations): T;
function useEntityTranslation<T extends Translation>(entity: null): {};
function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations | null): T | {};

function useEntityTranslation<T extends Translation>(
  entity: EntityWithTranslations | null
): T | {} {
  // do smth and return T or {}
  return null!;
}
</code>```

And then it will work the way you want:

```<code>useEntityTranslation<ProductTranslation>(Math.random() < 0.5 ? product : null); // okay
</code>```

Okay, hope that helps; good luck!

Playground link to code

Body:
I'm trying to use TypeScript function overloading:

function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations): T;
function useEntityTranslation<T extends Translation>(entity: null): {};

function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations | null): T | {} {
  // do smth and return T or {}
}

It works if I call it these ways:

useEntityTranslation<ProductTranslation>(product); // EntityWithTranslations type
useEntityTranslation<ProductTranslation>(null);

But if product is of type EntityWithTranslations | null (it's in React component: null until an entity is retrieved from api)

useEntityTranslation<ProductTranslation>(product); // EntityWithTranslations | null

TypeScript throws an error No overload matches this call.

It's because the type EntityWithTranslations | null is not assignable to any of the two overloads.

But how can I make it understandable for TypeScript?

UPDATE:

The problem also is I can't use a received value as a known type

const translation = useEntityTranslation<ProductTranslation>(product);
translation.name // name doesn't exist in {}

My workaround is to add one more overload:

function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations | null): { [name: string]: any }

I use translation if product isn't null, so I'm sure translation is of type ProductTranslation.

Not awesome (translation.name -> any) but at least works

Body:
As you noted, TypeScript does not resolve overloads by allowing unions of arguments from different call signatures.  There is a longstanding open suggestion, microsoft/TypeScript#14107, asking for this to happen, but for now it is not part of the language.

The easiest way to deal with this for a small number of call signatures is to add new call signatures corresponding to each union of arguments you want to support.  In your case, you could add a single overload signature that happens to be the same as your implementation signature:

function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations): T;
function useEntityTranslation<T extends Translation>(entity: null): {};
function useEntityTranslation<T extends Translation>(entity: EntityWithTranslations | null): T | {};

function useEntityTranslation<T extends Translation>(
  entity: EntityWithTranslations | null
): T | {} {
  // do smth and return T or {}
  return null!;
}

And then it will work the way you want:

useEntityTranslation<ProductTranslation>(Math.random() < 0.5 ? product : null); // okay

Okay, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play/#code/CYUwxgNghgTiAEYD2A7AzgF3gBxk4ArmBgFzwCiKGAlhgJ4DqtAFgCoxTrQ2poDcAKAEB6YfADyANxAwISKMDRCAZgRTFqqeATQhKNeu05pumlAB5W8EAA8MIFIvhGuUHigB8ACgcG6ZfVpGFhcTNzM0AEoyVkFVdXdtXUDDDld3S2s7BydQ01RvXyCyFAIICGj4AG8AXzi1DS0dPSogvPDUTNt7RzRnNLD3Qtb6AJHgjDYB-PR4AB94UvLKqwXa+oSzJJa-doyrbpy+vbNhvzG-JkmT3nnFsoqYu9rqgXh4UXhgJHg0AFtJvBOMB4HAMAQYChnPAkDBqjU3qCQODIfdygBCQQIgTNFJ0G4WAAKeEIxAJ3lw+CIGEiglx4wJ5mJVLJ0w6ni8SwqdOSDLZGWZpIw5K8AFk3MwAHRpb5-LyReDmeAABklAFZ4AB+HAk6nwEoPWkfMRIADWUDoQhEYgAwqhgLQzFAIPAvAB3FiICEwOjUFAAc0iQmQ6Cw9L8Nu9dHgAF5FQdsr1+sYZt4FTGPIjzABVLI9Jx4q5TFPsvoLLlnYrwbOVXOHJOFkL8iJa6FkF4Z17vd5giFQrmYxHYkOYbZ4wXUgmxsfjSMwH1M3WsktDeWCEdYbDT8NBCfL9JmLyUoVGz574XN1ACDeLbe8vzngmcw18Y3w6+8TdQuM7+iPy8oGKErSsCSBygqSqqhq2rHnqBrLK+nwvAs-4rmYVqiJ89DYCASh+vYMDKFAYAIFOVSIjYZCYDAfr+liAj4TIREkRQ4xFgSfTke8-j3H8ABGMj0QxVBMcRCCoQeWj1rkAFdvAABeVEYDRAb0UAA" rel="nofollow noreferrer">Playground link to code


问:
Combining p values using scipy
I have to combine p values and get one p value.
I'm using scipy.stats.combine_pvalues function, but it is giving very small combined p value, is it normal?

e.g.:

```<code>>>> import scipy
>>> p_values_list=[8.017444955844044e-06, 0.1067379119652372, 5.306374345615846e-05, 0.7234201655194492, 0.13050605094545614, 0.0066989543716175, 0.9541246420333787]
>>> test_statistic, combined_p_value = scipy.stats.combine_pvalues(p_values_list, method='fisher',weights=None)
>>> combined_p_value
4.331727536209026e-08
</code>```

As you see, combined_p_value is smaller than any given p value in the p_values_list?
How can it be?

Thanks in advance,
Burcak

答:
I am by no means an expert in this field, but am interested in your question. Following some reading of wiki it seems to me that the combined_p_value tells you the likelihood of all p-values in the list been obtained under the same null-hypothesis. Which is very unlikely considering two extremely small values.
Your set has two extremely small values: 1st and 3rd. If the thought process I described is correct, removing any of them should yield a much higher p-value, which is indeed the case:

remove 1st: p-value of 0.00010569305282803985

remove 3rd: p-value of 2.4713196031837724e-05

In conclusion, I think that this is a correct way of interpreting the meta-analysis that combine_pvalues actually describes.

Title: Combining p values using scipy

Body:
I have to combine p values and get one p value.
I'm using scipy.stats.combine_pvalues function, but it is giving very small combined p value, is it normal?

e.g.:

>>> import scipy
>>> p_values_list=[8.017444955844044e-06, 0.1067379119652372, 5.306374345615846e-05, 0.7234201655194492, 0.13050605094545614, 0.0066989543716175, 0.9541246420333787]
>>> test_statistic, combined_p_value = scipy.stats.combine_pvalues(p_values_list, method='fisher',weights=None)
>>> combined_p_value
4.331727536209026e-08

As you see, combined_p_value is smaller than any given p value in the p_values_list?
How can it be?

Thanks in advance,
Burcak


问:
Checking elements in a dataframe and extract some values
I need to check if values in a column contain one word or another (e.g. apple/watermelon) and create a new column (Fruit) collecting those values coming from Sentence.

For example:

```<code>Sentence                      Fruit
I bought 1 watermelon        watermelon
I bought 2 apples            apples
I bought 1 apple             apple
</code>```

I have tried as follows

```<code>schema = '^(?P<Fruit>\d+ apple?| watermelon?)' but it is not working. If I wrote

schema_n = '^(?P<Fruit>\d+ apple?)
</code>```

or

```<code>schema_n = '^(?P<Fruit>\d+ watermelon?)
</code>```

it works.
My question is thus how I could use operator notation to check a value (the fourth element in a string; or condition).

Many thanks

答:
After discussion, it's not entirely clear what logic governs the fruit matching, but if you're trying to extract any "apple", "apples" or "watermelon" from sentences where the fruit is preceded by a digit and space, you can use:

```<code>>>> def replacer(s):
...     return re.search(r"(?<=\d )(apples?|watermelon)\b", s).group()
...
>>> df = pd.DataFrame({"Sentence": ["I bought 1 watermelon", "I bought 2 apples", "I bought 1 apple"]})
>>> df["Fruit"] = df["Sentence"].apply(replacer)
>>> df
                Sentence       Fruit
0  I bought 1 watermelon  watermelon
1      I bought 2 apples      apples
2       I bought 1 apple       apple
</code>```

If your data has rows that don't match the pattern, this will crash. You'd need to check those cases and fill in some default value, say:

```<code>>>> def replacer(s):
...     match = re.search(r"(?<=\d )(apples?|watermelon)\b", s)
...     return match.group() if match else None
...
>>> df = pd.DataFrame({"Sentence": ["foo 1 watermelons"]})
>>> df["Fruit"] = df["Sentence"].apply(replacer)
>>> df
            Sentence Fruit
0  foo 1 watermelons  None
</code>```

If your data is more complex than what you've shown, you'll need to adapt this to fit your actual use case.

Body:
I need to check if values in a column contain one word or another (e.g. apple/watermelon) and create a new column (Fruit) collecting those values coming from Sentence.

For example:

Sentence                      Fruit
I bought 1 watermelon        watermelon
I bought 2 apples            apples
I bought 1 apple             apple

I have tried as follows

schema = '^(?P<Fruit>\d+ apple?| watermelon?)' but it is not working. If I wrote

schema_n = '^(?P<Fruit>\d+ apple?)

or

schema_n = '^(?P<Fruit>\d+ watermelon?)

it works.
My question is thus how I could use operator notation to check a value (the fourth element in a string; or condition).

Many thanks

Body:
After discussion, it's not entirely clear what logic governs the fruit matching, but if you're trying to extract any "apple", "apples" or "watermelon" from sentences where the fruit is preceded by a digit and space, you can use:

>>> def replacer(s):
...     return re.search(r"(?<=\d )(apples?|watermelon)\b", s).group()
...
>>> df = pd.DataFrame({"Sentence": ["I bought 1 watermelon", "I bought 2 apples", "I bought 1 apple"]})
>>> df["Fruit"] = df["Sentence"].apply(replacer)
>>> df
                Sentence       Fruit
0  I bought 1 watermelon  watermelon
1      I bought 2 apples      apples
2       I bought 1 apple       apple

If your data has rows that don't match the pattern, this will crash. You'd need to check those cases and fill in some default value, say:

>>> def replacer(s):
...     match = re.search(r"(?<=\d )(apples?|watermelon)\b", s)
...     return match.group() if match else None
...
>>> df = pd.DataFrame({"Sentence": ["foo 1 watermelons"]})
>>> df["Fruit"] = df["Sentence"].apply(replacer)
>>> df
            Sentence Fruit
0  foo 1 watermelons  None

If your data is more complex than what you've shown, you'll need to adapt this to fit your actual use case.


问:
Image on Right, text on left
I'm pretty new to website development and currently still running a course..
We have this assignment and there is just one thing where I can't wrap my mind around (pun intended).

In the "problem" image, the image is in a correct position, but the text alignment is off..
The text should be as shown in the "solution" image

#article {
    width: 650px;
    min-height: 280px;
    margin: 20px;
}

#article p {
    font-size: .8em;
    line-height: 1.6em;
}

#win {
    position: relative;
    left: 160px;
    top: 40px;
    float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div id="article">

            <img id="win" src="img/gratis.png" alt="test"/>

        <h1>de spikes & de spikids</h1>

        <p>
            Dit is de officiële Spikes-site (dus: de enige echte)! Hier vindt u alle
            informatie en nog véél méér onzin over de knotsgekke bands de Spikes en de
            Spikids. Volg ons op
            Facebook. De
            foto's die wij van jou schieten op onze optredens – vind je voortaan op
            facebook. Op onze eigenste
            <a
            href="https://www.youtube.com/channel/UCTUYz6ynn0M-vHxUXJM15NA"
            target="_blank"
            >YouTube</a
            >
            SPIKES TV kom je alvast in de stemming. Véél kijkplezier!
        </p>

        <h1>De Spikes anno 2015</h1>

        <p>
            De Spikes hebben zichzelf microscopisch onder de loep genomen. Er is gewikt,
            gewogen en het orakel heeft beslist! Het jarenlange succesvolle
            Spikes-concept heeft z’n houdbaarheidsdatum bereikt. Het tijdperk van de
            “spottende parodieën en persiflages” is voorgoed voorbij. Het muzikaal
            voornemen is om “het muzikaal OORgasme” tot méérvoudige hoogtes te brengen
            in 2015 – en tegelijkertijd toch “dé allerleukste coverband uit België” te
            blijven.
        </p>
    </div></code>```

I've been struggling with this for a while now, a solution would help me out a LOT! :)

Thanks in advance for everyone who answers this!

PROBLEM_IMAGE

SOLUTION_IMAGE

答:
Just add to your CSS code

```<code>img {
  float: right;
}
</code>```

For more info and examples

Title: Image on Right, text on left

Body:
I'm pretty new to website development and currently still running a course..
We have this assignment and there is just one thing where I can't wrap my mind around (pun intended).

In the "problem" image, the image is in a correct position, but the text alignment is off..
The text should be as shown in the "solution" image

#article {
    width: 650px;
    min-height: 280px;
    margin: 20px;
}

#article p {
    font-size: .8em;
    line-height: 1.6em;
}

#win {
    position: relative;
    left: 160px;
    top: 40px;
    float: right;
}

de spikes & de spikids

            Dit is de officiële Spikes-site (dus: de enige echte)! Hier vindt u alle
            informatie en nog véél méér onzin over de knotsgekke bands de Spikes en de
            Spikids. Volg ons op
            Facebook. De
            foto's die wij van jou schieten op onze optredens – vind je voortaan op
            facebook. Op onze eigenste
            YouTube
            SPIKES TV kom je alvast in de stemming. Véél kijkplezier!

De Spikes anno 2015

            De Spikes hebben zichzelf microscopisch onder de loep genomen. Er is gewikt,
            gewogen en het orakel heeft beslist! Het jarenlange succesvolle
            Spikes-concept heeft z’n houdbaarheidsdatum bereikt. Het tijdperk van de
            “spottende parodieën en persiflages” is voorgoed voorbij. Het muzikaal
            voornemen is om “het muzikaal OORgasme” tot méérvoudige hoogtes te brengen
            in 2015 – en tegelijkertijd toch “dé allerleukste coverband uit België” te
            blijven.

I've been struggling with this for a while now, a solution would help me out a LOT! :)

Thanks in advance for everyone who answers this!

PROBLEM_IMAGE

SOLUTION_IMAGE

Body:
Just add to your CSS code

img {
  float: right;
}

For more info and examples


问:
PHP Use foreach on a json string that has unicode emojis in it
I have a database and it stores discord guilds in it and the discord guilds can have emojis like   and • . I am having an issue though when I am trying to do a foreach on the data it just says

PHP Warning:  Invalid argument supplied for foreach() in /path/to/my/php/file

I just want to either entirely remove all emojis/unicodes or just be able to show them normally within the foreach statement without a ton of work.

Foreach im using

$stmt = $conn->prepare("SELECT guilds FROM users WHERE discord_id = :discord_id");
$stmt->bindParam(':discord_id', $userdata['discord_id']);
$guildData = $stmt->fecth(PDO::FETCH_ASSOC);
$guildData = json_decode($guildData, true);
var_dump($guildData);

foreach($guildData as $g) {
    echo $g;
}
```

<p>Sample of the data that is in the column guilds:</p>

```[{"id": 1, "guildname": "Server Name "}, {"id": 2, "guildname": "Server Name"}]
```

I want to either keep them and show all the emojis or just entirely remove all unicode emojis and symbols.

答:
OK I still haven't been able to figure out what you're actually trying to accomplish, but what is clear is that you don't know what your data looks like and you're fumbling in the dark trying to apply random functions and hoping that something sensible comes out of echo.

Use var_dump(). It will tell you exactly what something is down to the smallest detail. For example, var_dump($userdata['guilds']); will tell you exactly what that variable actually is and let you make an informed decision about what to do with it next.

Eg:

$input_json = '[{"id": 1, "guildname": "Server Name "}, {"id": 2, "guildname": "Server Name"}]';
$decoded = json_decode($input_json, true);

var_dump($input_json, $decoded);
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>string(83) "[{"id": 1, "guildname": "Server Name "}, {"id": 2, "guildname": "Server Name"}]"
array(2) {
  [0]=>
  array(2) {
    ["id"]=>
    int(1)
    ["guildname"]=>
    string(16) "Server Name "
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(2)
    ["guildname"]=>
    string(11) "Server Name"
  }
}
</code>```

So now I know I should be able to:

foreach( $decoded as $guild ) {
    echo "Guild: " . $guild['guildname'] . "\n";
}
```

<p>Which gets me:</p>

<pre class="lang-none prettyprint-override"><code>Guild: Server Name
Guild: Server Name
</code>```

and if you want to really up your debugging game you'd want to look at using something like XDebug and an IDE that can plug into it properly.

Body:
I have a database and it stores discord guilds in it and the discord guilds can have emojis like   and • . I am having an issue though when I am trying to do a foreach on the data it just says

PHP Warning:  Invalid argument supplied for foreach() in /path/to/my/php/file

I just want to either entirely remove all emojis/unicodes or just be able to show them normally within the foreach statement without a ton of work.

Foreach im using

$stmt = $conn->prepare("SELECT guilds FROM users WHERE discord_id = :discord_id");
$stmt->bindParam(':discord_id', $userdata['discord_id']);
$guildData = $stmt->fecth(PDO::FETCH_ASSOC);
$guildData = json_decode($guildData, true);
var_dump($guildData);

foreach($guildData as $g) {
    echo $g;
}

Sample of the data that is in the column guilds:

[{"id": 1, "guildname": "Server Name "}, {"id": 2, "guildname": "Server Name"}]

I want to either keep them and show all the emojis or just entirely remove all unicode emojis and symbols.

Body:
OK I still haven't been able to figure out what you're actually trying to accomplish, but what is clear is that you don't know what your data looks like and you're fumbling in the dark trying to apply random functions and hoping that something sensible comes out of echo.

Use var_dump(). It will tell you exactly what something is down to the smallest detail. For example, var_dump($userdata['guilds']); will tell you exactly what that variable actually is and let you make an informed decision about what to do with it next.

Eg:

$input_json = '[{"id": 1, "guildname": "Server Name "}, {"id": 2, "guildname": "Server Name"}]';
$decoded = json_decode($input_json, true);

var_dump($input_json, $decoded);

Output:

string(83) "[{"id": 1, "guildname": "Server Name "}, {"id": 2, "guildname": "Server Name"}]"
array(2) {
  [0]=>
  array(2) {
    ["id"]=>
    int(1)
    ["guildname"]=>
    string(16) "Server Name "
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(2)
    ["guildname"]=>
    string(11) "Server Name"
  }
}

So now I know I should be able to:

foreach( $decoded as $guild ) {
    echo "Guild: " . $guild['guildname'] . "\n";
}

Which gets me:

Guild: Server Name
Guild: Server Name

and if you want to really up your debugging game you'd want to look at using something like XDebug and an IDE that can plug into it properly.


问:
How to dynamically load a C# dll from a C++ DLL
I have a C++ application.  This supports users' C++ plugin DLL's, it will dynamically load these DLL's and then be able to create and use the user's types dynamically. These user types derive from base types and interfaces defined in the main application's core library, so I hold user's objects as pointers to the base class and call the user's virtual functions to make their magic happen.

Now I want to extend the plugin DLL's to allow managed DLL's (I care about C# mostly). I want all of the same magic to happen in C# plugin DLL's.

How can I dynamically load these dll's, some how I think win32's LoadLibrary which I am currently using is going to be happy with a managed DLL.  I will not have access to these libraries at compile/link time, they come from the user.

After I get the library loaded, unfortunately I suspect COM in my future as the way to call the derived functions.  Possibly I could use the CLI/C++ wrapper I have been reading about but I am very inexperienced here and would appreciate any advice or links to appropriate articles.

答:
Another way of doing this would be creating a C++/CLI project that hosts your C# classes and use it as a bridge in your C++ project.

A few more links to this approach:

Connecting c++ and c# code with a c++/cli bridge

.NET to C++ Bridge

The latest link has simple source code for the bridge


问:
Unable to define runtime parameters with secret in azure YAML
I am trying to create a secret runtime parameter as described in GitHub. But getting the below error.

Encountered error(s) while parsing pipeline YAML:
/azure-pipelines.yml (Line: 12, Col: 3): Unexpected value 'secret'

Code:

parameters:
- name: app
  type: string
  values:
  - App1
  - App2
- name: mySecret
  type: string
  secret: true

I have raised the same in
Developer Community portal as well. Please let me know if there is any way possible.

答:
Unable to define runtime parameters with secret in azure YAML

Indeed, I could also reproduced this issue on my side. That because that document is a Design Docs.

You could check the state of that doc:

The design docs within this repo are created at different times during
  the development of Azure Pipelines, to support collaborative
  contributions to the design process. Designs documents are for,

features considered for implementation but never implemented

already implemented features

future ideas for features

The design docs in this repo may not represent the current state of an Azure Pipelines feature.

Obviously, this is a function that has not yet been implemented. That the reason why you get that error. You can expect it to come, I believe it will meet us soon.

Hope this helps.


问:
Get parent VALUE on React-select grouped options
Im using react-select with grouped options, they are grouped like this:

```<code>{
  label: PARENT_NAME,
  value: PARENT_ID,
  options: [
    {
      label: CHILD_NAME,
      value: CHILD_ID,
    }
  ]
}
</code>```

I have an array with those options, and im passing it to the  component like this:

```<code><Select
  options={ARR_OF_OPTIONS}
  onChange={this.handleChange("name")}
/>
</code>```

My handleChange function is like this:

```<code>handleChange = name => selectedOption => {
  const value = selectedOption.value
  this.setState({ [name]: value, })
}
</code>```

My question is:
Is it possible to get the PARENT_ID when selecting the child option?

Hopefully I made myself clear.

Thanks in advance

答:
Every option can have more properties

```<code>{
  label: PARENT_NAME,
  value: PARENT_ID,
  options: [
    {
      label: CHILD_NAME,
      value: CHILD_ID,

      // additional properties
      group: PARENT_ID,
      otherValue: OTHER_VALUE,
    }
  ]
}
</code>```

selectedOption is an object - you can easily access group, otherValue

```<code>handleChange = name => selectedOption => {
  const value = selectedOption.value
  console.log("group", selectedOption.group )
  this.setState({ [name]: value, })
}
</code>```

This method (based on original react-select grouped example) duplicates data (in this case) but is safe for case when value can exists in multiple groups (can't be reliably found by comparing value).

Body:
Im using react-select with grouped options, they are grouped like this:

{
  label: PARENT_NAME,
  value: PARENT_ID,
  options: [
    {
      label: CHILD_NAME,
      value: CHILD_ID,
    }
  ]
}

I have an array with those options, and im passing it to the  component like this:

<Select
  options={ARR_OF_OPTIONS}
  onChange={this.handleChange("name")}
/>

My handleChange function is like this:

handleChange = name => selectedOption => {
  const value = selectedOption.value
  this.setState({ [name]: value, })
}

My question is:
Is it possible to get the PARENT_ID when selecting the child option?

Hopefully I made myself clear.

Thanks in advance

Body:
Every option can have more properties

{
  label: PARENT_NAME,
  value: PARENT_ID,
  options: [
    {
      label: CHILD_NAME,
      value: CHILD_ID,

      // additional properties
      group: PARENT_ID,
      otherValue: OTHER_VALUE,
    }
  ]
}

selectedOption is an object - you can easily access group, otherValue

handleChange = name => selectedOption => {
  const value = selectedOption.value
  console.log("group", selectedOption.group )
  this.setState({ [name]: value, })
}

This method (based on original react-select grouped example) duplicates data (in this case) but is safe for case when value can exists in multiple groups (can't be reliably found by comparing value).


问:
Use XmlSerializer on request and DataContractSerializer on response?
Is it possible to receive a request with attributes and use the XmlSerializer to deserialize it and send a response back with just elements using the DataContractSerializer?

Also,  if you receive a request with attributes, must you use the XmlSerializer to deserialize the content?

答:
For the second question: if you have attributes, then you need to use the XmlSerializer - the DataContractSerializer doesn't support them.

For the first question: yes, it's possible. No, it's not easy. The selection of the serializer is done at the operation formatter level. WCF allows you to change the serializer per operation by using the [XmlSerializerFormat] or [DataContractFormat] (which is default), but that will bind the serializer to both request and responses.

If you really, really want to do it, you can create your own formatter (replace it using some operation behavior), then in that formatter you can choose how you serialize / deserialize the inputs / outputs (you can even use different serializers for each parameter), but you'll need to create one formatter, which isn't something too easy to do.

I've written some posts about message formatters and replacing serializers in Silverlight which can give you a hint on how to start about it. But if you can live with XmlSerializer only, that'll be a lot easier.


问:
Which of the following are correct regarding an equals() method in java?
This is a question on one of my practice exams that has me stumped.

Potential Answers

An equals() method written in a class named C must have a parameter that is declared to be of type C, in order to override the equals() method in the Object class.

An equals() method must have a parameter that is declared to be of type Object, in order to override the equals() method in the Object class.

An equals() method written in a class named C must cast its parameter to Object, even if its parameter is declared to be of type C, otherwise it will not be able to properly compare the fields of current object to those of the parameter object.

A well-designed equals() method should check for and handle the case where its current object may be null

An equals() method in a subclass cannot refer directly to private fields in a superclass in order to compare them, so it should invoke the superclass equals() method to do this

The answer is #2 & #5. I don't understand why #1 is wrong and #2 is correct. Don't you have to compare one type C with another type C? And why is #5 correct. I don't understand this one at all. Can't subclasses access the private fields of a superclass?

答:
Consider the following equals method for C class.

```<code> @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        C c= (C) o;
        return id == c.id;
    }
</code>```

Explanation for 1 & 5 options:

If you declare the parameter of type C, then it will not be overriding.

Error:

Method does not override method from its superclass

Indicates that a method declaration is intended to override a method declaration in a supertype. If a method is annotated with this annotation type compilers are required to generate an error message unless at least one of the following conditions hold:
  The method does override or implement a method declared in a supertype.
  The method has a signature that is override-equivalent to that of any public method declared in Object.

superclass cannot access private fields of a class, so they need to call the superclass equals method to compare them.

Body:
Consider the following equals method for C class.

 @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        C c= (C) o;
        return id == c.id;
    }

Explanation for 1 & 5 options:

If you declare the parameter of type C, then it will not be overriding.

Error:

Method does not override method from its superclass

Indicates that a method declaration is intended to override a method declaration in a supertype. If a method is annotated with this annotation type compilers are required to generate an error message unless at least one of the following conditions hold:
  The method does override or implement a method declared in a supertype.
  The method has a signature that is override-equivalent to that of any public method declared in Object.

superclass cannot access private fields of a class, so they need to call the superclass equals method to compare them.


答:
If this is your practical exam: did your course material not cover this?

As for #1: the method signature is public boolean equals(Object obj), so that's what you have to override. Any other signature and it's not an override, it's "a completely different method".

As for #5: That's what private means. The fields are private to that class and only that class. If a subclass should have access to them, then they'd have to be protected, not private.

Title: Which of the following are correct regarding an equals() method in java?

Body:
This is a question on one of my practice exams that has me stumped.

Potential Answers

An equals() method written in a class named C must have a parameter that is declared to be of type C, in order to override the equals() method in the Object class.

An equals() method must have a parameter that is declared to be of type Object, in order to override the equals() method in the Object class.

An equals() method written in a class named C must cast its parameter to Object, even if its parameter is declared to be of type C, otherwise it will not be able to properly compare the fields of current object to those of the parameter object.

A well-designed equals() method should check for and handle the case where its current object may be null

An equals() method in a subclass cannot refer directly to private fields in a superclass in order to compare them, so it should invoke the superclass equals() method to do this

The answer is #2 & #5. I don't understand why #1 is wrong and #2 is correct. Don't you have to compare one type C with another type C? And why is #5 correct. I don't understand this one at all. Can't subclasses access the private fields of a superclass?


问:
React JS - How better to add React component to ReactDOM
Is it okay if I insert React component directly in document body by id?

Or it is better to wrap it in DIV?

index.js

```<code>ReactDOM.render(
    <Provider store={store()}>
        <App/>
    </Provider>,
    document.querySelector("#root")
)
</code>```

index.html

```<code><body class="d-flex flex-column h-100" id="root">
  <noscript>You need to enable JavaScript to run this app.</noscript>
</body>
</code>```

答:
In my html page I only use one

After that:

```<code>ReactDOM.render(element, document.getElementById('root'));
</code>```

does all the magic.

reference:  https://reactjs.org/docs/rendering-elements.html

Body:
Is it okay if I insert React component directly in document body by id?

Or it is better to wrap it in DIV?

index.js

ReactDOM.render(
    <Provider store={store()}>
        <App/>
    </Provider>,
    document.querySelector("#root")
)

index.html

  You need to enable JavaScript to run this app.

Body:
In my html page I only use one <div id="root">

After that:

ReactDOM.render(element, document.getElementById('root'));

does all the magic.

reference:  https://reactjs.org/docs/rendering-elements.html


问:
firebase push notification with expo not working
I've an app based on react native with expo. For push notifications, i'm trying to use firebase. I've created functions in firebase and tried to send notification from firebase to my iphone. I don't see any issues in the code and verified firebase log too. Getting status "ok" message after this function triggered but still i didn't get notifications in my mobile. Anyone can help?

I'm in firebase paid plan. Same code is firing notification when i run directly from react native app.

```<code>const functions = require("firebase-functions");
const fetch = require("node-fetch");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

exports.sendPushNotification = functions.database
  .ref("orders/{id}")
  .onCreate((snapshot, context) => {
    var messages = [];
    const root = admin.database().ref("customers");
    console.log("customers : " + root.path);
    return root
      .once("value")
      .then((snapshot) => {
        snapshot.forEach((childSnapshot) => {
          //alert(expoToken);
          var expoToken = childSnapshot.val().expoPushToken;
          console.log("token : " + expoToken);
          if (expoToken) {
            messages.push({
              to: expoToken,
              title: "hello",
              body: "New Order",
            });
          }
        });
        return Promise.all(messages);
      })
      .then((messages) => {
        const res = fetch("https://exp.host/--/api/v2/push/send", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(messages),
        });
        console.log(res);
        return res;
      });
  });
</code>```

答:
Not sure what was the problem but after i added below line in headers tag, it started working fine.

"Accept-encoding": "gzip, deflate"

Body:
I've an app based on react native with expo. For push notifications, i'm trying to use firebase. I've created functions in firebase and tried to send notification from firebase to my iphone. I don't see any issues in the code and verified firebase log too. Getting status "ok" message after this function triggered but still i didn't get notifications in my mobile. Anyone can help?

I'm in firebase paid plan. Same code is firing notification when i run directly from react native app.

const functions = require("firebase-functions");
const fetch = require("node-fetch");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

exports.sendPushNotification = functions.database
  .ref("orders/{id}")
  .onCreate((snapshot, context) => {
    var messages = [];
    const root = admin.database().ref("customers");
    console.log("customers : " + root.path);
    return root
      .once("value")
      .then((snapshot) => {
        snapshot.forEach((childSnapshot) => {
          //alert(expoToken);
          var expoToken = childSnapshot.val().expoPushToken;
          console.log("token : " + expoToken);
          if (expoToken) {
            messages.push({
              to: expoToken,
              title: "hello",
              body: "New Order",
            });
          }
        });
        return Promise.all(messages);
      })
      .then((messages) => {
        const res = fetch("https://exp.host/--/api/v2/push/send", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(messages),
        });
        console.log(res);
        return res;
      });
  });


问:
Avoiding Side Effects in List Comprehension
What is the most Pythonic and efficient way of processing a list of dictionaries and avoiding side effects (what are side effects)?

More specifically: Why does the following code produce a generator object, while just about any other similar code produces the desired output?

```<code>print(sum(dictionary[site] for site in dictionary) for dictionary in listofdictionaries)
</code>```

Some background

I started by fiddling with **kwargs and produced what I would consider pretty awful code.

```<code>def testing(**kwargs):
    mysum = 0
    for kw in kwargs:
        mysum += kwargs[kw]
    print(mysum)

listofdictionaries = [{"site1": 1, "room1": 2, "day1": 3}, {"site2": 4, "room2": 5, "day2": 6}]

for dictionary in listofdictionaries:
    testing(**dictionary)
</code>```

I reviewed the Data Structures Document including List Comprehension and found a better way to achieve the same output:

```<code>listofdictionaries = [{"site1": 1, "room1": 2, "day1": 3}, {"site2": 4, "room2": 5, "day2": 6}]
for dictionary in listofdictionaries:
    mysum = 0
    for value in dictionary:
        mysum += dictionary[value]
    print(mysum)
</code>```

And then got a little clever and shortened it a bit more:

```<code>for dictionary in listofdictionaries:
    print(sum(dictionary[value] for value in dictionary))
</code>```

I really have no interest in making this a one-liner for the sake of making it a one-liner, but after reading countless list comprehension posts on Stack Overflow talking about avoiding "side effects", I feel like there may be an additional step to take this. Perhaps I'm not understanding what side effects are.

Regardless, each of these should result in the output:

```<code>6
15
</code>```

答:
Your specific question only prints the representation of your actual generator object formed by the generator expression, namely this one-

```<code>(sum(dictionary[site] for site in dictionary) for dictionary in listofdictionaries)
</code>```

See this answer on printing generators for further details-
https://stackoverflow.com/a/44616115

For this example you may be better off using a list comprehension, e.g.

```<code>print([sum(dictionary.values()) for dictionary in listofdictionaries])
</code>```

You coudl print the generator by unpakcing it first but for this example it appears less readable and less effective-

```<code>print(*(sum(dictionary.values()) for dictionary in listofdictionaries))
</code>```

Side effects can be quite a broad term- https://en.wikipedia.org/wiki/Side_effect_(computer_science) but as per the previous answer you're not modifying your dictionary in any way with these methods so there are no side effects.

Body:
What is the most Pythonic and efficient way of processing a list of dictionaries and avoiding side effects (what are side effects)?

More specifically: Why does the following code produce a generator object, while just about any other similar code produces the desired output?

print(sum(dictionary[site] for site in dictionary) for dictionary in listofdictionaries)

Some background

I started by fiddling with **kwargs and produced what I would consider pretty awful code.

def testing(**kwargs):
    mysum = 0
    for kw in kwargs:
        mysum += kwargs[kw]
    print(mysum)

listofdictionaries = [{"site1": 1, "room1": 2, "day1": 3}, {"site2": 4, "room2": 5, "day2": 6}]

for dictionary in listofdictionaries:
    testing(**dictionary)

I reviewed the Data Structures Document including List Comprehension and found a better way to achieve the same output:

listofdictionaries = [{"site1": 1, "room1": 2, "day1": 3}, {"site2": 4, "room2": 5, "day2": 6}]
for dictionary in listofdictionaries:
    mysum = 0
    for value in dictionary:
        mysum += dictionary[value]
    print(mysum)

And then got a little clever and shortened it a bit more:

for dictionary in listofdictionaries:
    print(sum(dictionary[value] for value in dictionary))

I really have no interest in making this a one-liner for the sake of making it a one-liner, but after reading countless list comprehension posts on Stack Overflow talking about avoiding "side effects", I feel like there may be an additional step to take this. Perhaps I'm not understanding what side effects are.

Regardless, each of these should result in the output:

6
15

Body:
Your specific question only prints the representation of your actual generator object formed by the generator expression, namely this one-

(sum(dictionary[site] for site in dictionary) for dictionary in listofdictionaries)

See this answer on printing generators for further details-
https://stackoverflow.com/a/44616115

For this example you may be better off using a list comprehension, e.g.

print([sum(dictionary.values()) for dictionary in listofdictionaries])

You coudl print the generator by unpakcing it first but for this example it appears less readable and less effective-

print(*(sum(dictionary.values()) for dictionary in listofdictionaries))

Side effects can be quite a broad term- https://en.wikipedia.org/wiki/Side_effect_(computer_science) but as per the previous answer you're not modifying your dictionary in any way with these methods so there are no side effects.


问:
Using datetime index in where clause MySQL
I have a table with 200 million rows where index is created in "created_at" column which is datetime datatype.

show create table [tablename] outputs:

```<code> create table `table`
 (`created_at` datetime NOT NULL)
 PRIMARY KEY (`id`)
 KEY `created_at_index` (`created_at`)
 ENGINE=InnoDB AUTO_INCREMENT=208512112 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'
</code>```

created_at ranges from 2020-04-01 ~ 2020-05-28.

I want to get only rows that are beyond 2020-05-15 23:00:00.

when I run :

```<code>EXPLAIN SELECT created_at
          FROM table
         where created_at >= '2020-05-15 23:00:00';
</code>```

it says it outputs:

```<code>rows       Extra
200mil   Using Where
</code>```

My understanding is that in RDMS if no index rows are not ordered but when you create an index on a column it is in sorted order therefore right after finding '2020-05-15 23:00:00' it will simply return all rows after that.

Also since its cardinalty is 7mil I'd thought using an index would be better than full table scan.

Is it because I've inputted date as a string? but when I try

```<code> where created_at >= date('2020-05-15 23:00:00');
</code>```

still the same.

and

```<code> where created_at >= datetime('2020-05-15 23:00:00');
</code>```

outputs syntax error.

Did mysql just decide it would be more efficient to do a full table scan?

EDIT:

using equals

```<code>EXPLAIN SELECT created_at
          FROM table
         where created_at = '2020-05-15';
</code>```

outputs:

```<code>key_len    ref     rows     Extra
  5        const    51
</code>```

In where clause if I change string to date('2020-05-15') it outputs:

```<code>key_len    ref     rows     Extra
  5        const    51      Using index condition
</code>```

does this mean that first equal query one didn't use an index?

答:
All of your queries would take advantage of an index on column created_at. MySQL always uses an index when it matches the predicate(s) of the where clause.

The output of your explains do indicate that you do not have this index in place, which is confirmed by the output of your create table.

Just create the index and your database will use it.

Here is a demo:

```<code>-- sample table, without the index
create table mytable(id int, created_at datetime);

--  the query does a full scan, as no index is available
explain select created_at from mytable where created_at >= '2020-05-15 23:00:00';
</code>```

```
id | select_type | table   | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra
-: | :---------- | :------ | :--------- | :--- | :------------ | :--- | :------ | :--- | ---: | -------: | :----------
 1 | SIMPLE      | mytable | <em>null</em>       | ALL  | <em>null</em>          | <em>null</em> | <em>null</em>    | <em>null</em> |    1 |   100.00 | Using where
```

```<code>-- now add the index
create index idx_mytable_created_at on mytable(created_at);

-- the query uses the index
explain select created_at from mytable where created_at >= '2020-05-15 23:00:00';
</code>```

```
id | select_type | table   | partitions | type  | possible_keys          | key                    | key_len | ref  | rows | filtered | Extra
-: | :---------- | :------ | :--------- | :---- | :--------------------- | :--------------------- | :------ | :--- | ---: | -------: | :-----------------------
 1 | SIMPLE      | mytable | <em>null</em>       | index | idx_mytable_created_at | idx_mytable_created_at | 6       | <em>null</em> |    1 |   100.00 | Using where; Using index
```

Body:
I have a table with 200 million rows where index is created in "created_at" column which is datetime datatype.

show create table [tablename] outputs:

 create table `table`
 (`created_at` datetime NOT NULL)
 PRIMARY KEY (`id`)
 KEY `created_at_index` (`created_at`)
 ENGINE=InnoDB AUTO_INCREMENT=208512112 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'

created_at ranges from 2020-04-01 ~ 2020-05-28.

I want to get only rows that are beyond 2020-05-15 23:00:00.

when I run :

EXPLAIN SELECT created_at
          FROM table
         where created_at >= '2020-05-15 23:00:00';

it says it outputs:

rows       Extra
200mil   Using Where

My understanding is that in RDMS if no index rows are not ordered but when you create an index on a column it is in sorted order therefore right after finding '2020-05-15 23:00:00' it will simply return all rows after that.

Also since its cardinalty is 7mil I'd thought using an index would be better than full table scan.

Is it because I've inputted date as a string? but when I try

 where created_at >= date('2020-05-15 23:00:00');

still the same.

and

 where created_at >= datetime('2020-05-15 23:00:00');

outputs syntax error.

Did mysql just decide it would be more efficient to do a full table scan?

EDIT:

using equals

EXPLAIN SELECT created_at
          FROM table
         where created_at = '2020-05-15';

outputs:

key_len    ref     rows     Extra
  5        const    51

In where clause if I change string to date('2020-05-15') it outputs:

key_len    ref     rows     Extra
  5        const    51      Using index condition

does this mean that first equal query one didn't use an index?

Body:
All of your queries would take advantage of an index on column created_at. MySQL always uses an index when it matches the predicate(s) of the where clause.

The output of your explains do indicate that you do not have this index in place, which is confirmed by the output of your create table.

Just create the index and your database will use it.

Here is a demo:

-- sample table, without the index
create table mytable(id int, created_at datetime);

--  the query does a full scan, as no index is available
explain select created_at from mytable where created_at >= '2020-05-15 23:00:00';

id | select_type | table   | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra
-: | :---------- | :------ | :--------- | :--- | :------------ | :--- | :------ | :--- | ---: | -------: | :----------
 1 | SIMPLE      | mytable | null       | ALL  | null          | null | null    | null |    1 |   100.00 | Using where

-- now add the index
create index idx_mytable_created_at on mytable(created_at);

-- the query uses the index
explain select created_at from mytable where created_at >= '2020-05-15 23:00:00';

id | select_type | table   | partitions | type  | possible_keys          | key                    | key_len | ref  | rows | filtered | Extra
-: | :---------- | :------ | :--------- | :---- | :--------------------- | :--------------------- | :------ | :--- | ---: | -------: | :-----------------------
 1 | SIMPLE      | mytable | null       | index | idx_mytable_created_at | idx_mytable_created_at | 6       | null |    1 |   100.00 | Using where; Using index


问:
Only get the latest build from a branch on deployment
When doing a deployment job with a CI trigger and resources.pipelines that are defined like

```<code>resources:
  pipelines:
    - pipeline: thumbnailGenerator
      project: myServices
      source: thumbnail-generator CI
      trigger:
        branches:
          include:
            - master
</code>```

The deployment job downloads the latest build of the pipeline (which may be a PR) rather than the last build from master.  Is there a way of making it only download the specific branches when doing a CI build?

I haven't explored it yet, but I am thinking based on this behaviour it will always do the latest builds for all the pipelines regardless.

答:
There's a property called branch on the pipeline object

```<code>resources:
  pipelines:
    - pipeline: thumbnailGenerator
      project: myServices
      source: thumbnail-generator CI
      branch: master
      trigger:
        branches:
          include:
            - master
</code>```

Body:
When doing a deployment job with a CI trigger and resources.pipelines that are defined like

resources:
  pipelines:
    - pipeline: thumbnailGenerator
      project: myServices
      source: thumbnail-generator CI
      trigger:
        branches:
          include:
            - master

The deployment job downloads the latest build of the pipeline (which may be a PR) rather than the last build from master.  Is there a way of making it only download the specific branches when doing a CI build?

I haven't explored it yet, but I am thinking based on this behaviour it will always do the latest builds for all the pipelines regardless.

Body:
There's a property called branch on the pipeline object

resources:
  pipelines:
    - pipeline: thumbnailGenerator
      project: myServices
      source: thumbnail-generator CI
      branch: master
      trigger:
        branches:
          include:
            - master


问:
Including one list component and excluding all other components repeatedly in R
I have a list of values. I would like to use the first value in one portion of a function and use the remaining values in a separate part of the function. Then, I would like to use the second value from the list in one portion of the function and use the remaining values (including the first value) in another part of the function.

The following is not real code since I have excluded some function inputs, but it shows what I am trying to do:

```<code>group <- c(1, 3, 4, 5, 9) #the complete group
#It is important to note that these values are not continuous. They are distinct values.

#include 1st unit of the list group as treatment and then use
#the remaining values as controls

controls_not2 <- c(3, 4, 5, 9)
df1 <- dataprep(treatment = 1, controls = controls_not1)
gaps.plot(dataprep = df1)

#use the 2nd unit from the list as the treatment and use
#the remaining values as controls

controls_not2 <- c(1, 4, 5, 9)
df2 <- dataprep(treatment = 3, controls = controls_not3)
gaps.plot(dataprep = df3)
</code>```

In the full list, I have about 50 values. Is there a way for me to iterate over all these values in the way I have shown above?

Here is some additional information.

Packages used:

```<code>library(tidyverse)
library(synth)
</code>```

Here is an example of what the full code looks like to create a single graph.

treatment.identifier is equivalent to what I have as treatment in the simple example above. controls.identifier is equivalent to what I have as controls in the example above.

```<code>dataprep.out1 <- dataprep(foo = as.data.frame(df),
                         predictors = predictors1,
                         predictors.op = "mean",
                         special.predictors = NULL,
                         dependent = "logfatalitiespercapita",
                         unit.variable = "state",
                         time.variable = "year",
                     treatment.identifier = "99",
                     controls.identifier = controlstates,
                     time.predictors.prior = c(1981:1985),
                     time.optimize.ssr = c(1981:1985), #check on these years
                     time.plot = 1981:2003,
                     unit.names.variable = "statenames")

#identifying weights that create the best possible synthetic control unit for the treated
synth.out1 <- synth(dataprep.out1)

#graph
spec1 <- gaps.plot(dataprep.res = dataprep.out1, synth.res = synth.out1, Xlab = c("Year"), Ylab = c("Gap"))
</code>```

答:
First a comment, you may not want to use 'list' as a vector name since list is a data type in R. You can subset the vector by referring to the index number. Example below.

list1 <- c(1, 3, 4, 5, 9) #the complete group

```<code>df1 <- dataprep(treatment = 1, controls = list1[c(1,3:length(list1))])
gaps.plot(dataprep = df1)

#use the 2nd unit from the list as the treatment and use
#the remaining values as controls

df2 <- dataprep(treatment = 3, controls = list1[c(2)])
gaps.plot(dataprep = df3)
</code>```

Body:
I have a list of values. I would like to use the first value in one portion of a function and use the remaining values in a separate part of the function. Then, I would like to use the second value from the list in one portion of the function and use the remaining values (including the first value) in another part of the function.

The following is not real code since I have excluded some function inputs, but it shows what I am trying to do:

group <- c(1, 3, 4, 5, 9) #the complete group
#It is important to note that these values are not continuous. They are distinct values.

#include 1st unit of the list group as treatment and then use
#the remaining values as controls

controls_not2 <- c(3, 4, 5, 9)
df1 <- dataprep(treatment = 1, controls = controls_not1)
gaps.plot(dataprep = df1)

#use the 2nd unit from the list as the treatment and use
#the remaining values as controls

controls_not2 <- c(1, 4, 5, 9)
df2 <- dataprep(treatment = 3, controls = controls_not3)
gaps.plot(dataprep = df3)

In the full list, I have about 50 values. Is there a way for me to iterate over all these values in the way I have shown above?

Here is some additional information.

Packages used:

library(tidyverse)
library(synth)

Here is an example of what the full code looks like to create a single graph.

treatment.identifier is equivalent to what I have as treatment in the simple example above. controls.identifier is equivalent to what I have as controls in the example above.

dataprep.out1 <- dataprep(foo = as.data.frame(df),
                         predictors = predictors1,
                         predictors.op = "mean",
                         special.predictors = NULL,
                         dependent = "logfatalitiespercapita",
                         unit.variable = "state",
                         time.variable = "year",
                     treatment.identifier = "99",
                     controls.identifier = controlstates,
                     time.predictors.prior = c(1981:1985),
                     time.optimize.ssr = c(1981:1985), #check on these years
                     time.plot = 1981:2003,
                     unit.names.variable = "statenames")

#identifying weights that create the best possible synthetic control unit for the treated
synth.out1 <- synth(dataprep.out1)

#graph
spec1 <- gaps.plot(dataprep.res = dataprep.out1, synth.res = synth.out1, Xlab = c("Year"), Ylab = c("Gap"))

Body:
First a comment, you may not want to use 'list' as a vector name since list is a data type in R. You can subset the vector by referring to the index number. Example below.

list1 <- c(1, 3, 4, 5, 9) #the complete group

df1 <- dataprep(treatment = 1, controls = list1[c(1,3:length(list1))])
gaps.plot(dataprep = df1)

#use the 2nd unit from the list as the treatment and use
#the remaining values as controls

df2 <- dataprep(treatment = 3, controls = list1[c(2)])
gaps.plot(dataprep = df3)