问:
In a layered architecture using Entity Framework, should I return POCO classes from the BLL? (Architecture guidance needed)
I've been reading too much probably and am suffering from some information overload. So I would appreciate some explicit guidance.

From what I've gathered, I can use VS2010's T4 template thingy to generate POCO classes that aren't tied directly to the EF. I would place these in their own project while my DAL would have an ObjectContext-derived class, right?

Once I have these classes, is it acceptable practice to use them in the UI layer? That is, say one of the generated classes is BookInfo that holds stuff about books for a public library (Title, edition, pages, summary etc.).

My BLL would contain a class BooksBLL for example like so:

```<code>public class BooksBLL
{
    ObjectContext _context;

    public void AddBook(BookInfo book) { ... }
    public void DeleteBook(int bookID) { ... }
    public void UpdateBook(int bookID, BookInfo newBook) { ... }

    //Advanced search taking possibly all fields into consideration
    public List<BookInfo> ResolveSearch(Func<BookInfo, bool> filter) { ... }

    //etc...
}
</code>```

So, my ViewModels in my MVVM UI app will be communicating with the above BLL class and exchanging BookInfo instances. Is that okay?

Furthermore, MVVM posts on the Web suggest implementing IDataErrorInfo for validation purposes. Is it okay if I implement said interface on the generated POCO class? I see from samples that those generated POCO classes contain all virtual properties and stuf and I hope adding my own logic would be okay?

If it makes any difference, at present, my app does not use WCF (or any networking stuff).

Also, if you see something terribly wrong with the way I'm trying to build my BLL, please feel free to offer help in that area too.

Update (Additional info as requested):

I'm trying to create a library automation application. It is not network based at present.

I am thinking about having layers as follows:

A project consisting of generated POCO classes (BookInfo, Author, Member, Publisher,  Contact etc.)

A project with the ObjectContext-derived class (DAL?)

A Business Logic Layer with classes like the one I mentioned above (BooksBLL, AuthorsBLL etc)

A WPF UI layer using the MVVM pattern. (Hence my sub-question about IDataErrorInfo implementation).

So I'm wondering about stuff like using an instance of BooksBLL in a ViewModel class, calling ResolveSearch() on it to obtain a List<BookInfo> and presenting it... that is, using the POCO classes everywhere.

Or should I have additional classes that mirror the POCO classes exposed from my BLL?

If any more detail is needed, please ask.

答:
You don't need to do anything in particular... as Mark said, there is no "right" answer.  However, if your application is simple enough that you would simply be duplicating your classes (e.g. BookInfoUI & BookInfoBLL), then I'd recommend just using the business classes.  The extra layer wouldn't serve a purpose, and so it shouldn't exist.  Eric Evans in DDD even recommends putting all your logic in the UI layer if you app is simple and has very little business logic.

To make the distinction, the application layer should have classes that model what happens within the application, and the domain layer should have classes that model what happens in the domain.  For example, if you have a search page, your UI layer might retrieve a list of BookSearchResult objects from a BookSearchService in the application layer, which would use the domain to pull a list of BookInfo.

Body:
I've been reading too much probably and am suffering from some information overload. So I would appreciate some explicit guidance.

From what I've gathered, I can use VS2010's T4 template thingy to generate POCO classes that aren't tied directly to the EF. I would place these in their own project while my DAL would have an ObjectContext-derived class, right?

Once I have these classes, is it acceptable practice to use them in the UI layer? That is, say one of the generated classes is BookInfo that holds stuff about books for a public library (Title, edition, pages, summary etc.).

My BLL would contain a class BooksBLL for example like so:

public class BooksBLL
{
    ObjectContext _context;

    public void AddBook(BookInfo book) { ... }
    public void DeleteBook(int bookID) { ... }
    public void UpdateBook(int bookID, BookInfo newBook) { ... }

    //Advanced search taking possibly all fields into consideration
    public List<BookInfo> ResolveSearch(Func<BookInfo, bool> filter) { ... }

    //etc...
}

So, my ViewModels in my MVVM UI app will be communicating with the above BLL class and exchanging BookInfo instances. Is that okay?

Furthermore, MVVM posts on the Web suggest implementing IDataErrorInfo for validation purposes. Is it okay if I implement said interface on the generated POCO class? I see from samples that those generated POCO classes contain all virtual properties and stuf and I hope adding my own logic would be okay?

If it makes any difference, at present, my app does not use WCF (or any networking stuff).

Also, if you see something terribly wrong with the way I'm trying to build my BLL, please feel free to offer help in that area too.

Update (Additional info as requested):

I'm trying to create a library automation application. It is not network based at present.

I am thinking about having layers as follows:

A project consisting of generated POCO classes (BookInfo, Author, Member, Publisher,  Contact etc.)

A project with the ObjectContext-derived class (DAL?)

A Business Logic Layer with classes like the one I mentioned above (BooksBLL, AuthorsBLL etc)

A WPF UI layer using the MVVM pattern. (Hence my sub-question about IDataErrorInfo implementation).

So I'm wondering about stuff like using an instance of BooksBLL in a ViewModel class, calling ResolveSearch() on it to obtain a List<BookInfo> and presenting it... that is, using the POCO classes everywhere.

Or should I have additional classes that mirror the POCO classes exposed from my BLL?

If any more detail is needed, please ask.


来源: stackexchange

问:
UIGesturerecognizer is not working on UIView
When I am tapping on UIView but Gesture is not working.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }

</code>```

I just want to perform this action on UIView tap.

答:
You need to mention numberOfTapsRequired property of the UITapGestureRecognizer.

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    let tap = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_sender:)))
    tap.numberOfTapsRequired = 1
    viewForSHadow.isUserInteractionEnabled = true
    viewForSHadow.addGestureRecognizer(tap)
}

@objc func handleTapGesture(_sender: UITapGestureRecognizer) {
    print("---------View Tapped--------")
    // Why are you hiding this view **viewForSHadow**
    viewForSHadow.isHidden = true
    viewForAlert.isHidden = true
}
</code>```

Also, make sure you are not doing viewForSHadow.isUserInteractionEnabled = false anywhere in the code.

ContentLicense: CC BY-SA 4.0

Body:
When I am tapping on UIView but Gesture is not working.

override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }

I just want to perform this action on UIView tap.

Body:
You need to mention numberOfTapsRequired property of the UITapGestureRecognizer.

override func viewDidLoad() {
    super.viewDidLoad()
    let tap = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_sender:)))
    tap.numberOfTapsRequired = 1
    viewForSHadow.isUserInteractionEnabled = true
    viewForSHadow.addGestureRecognizer(tap)
}

@objc func handleTapGesture(_sender: UITapGestureRecognizer) {
    print("---------View Tapped--------")
    // Why are you hiding this view **viewForSHadow**
    viewForSHadow.isHidden = true
    viewForAlert.isHidden = true
}

Also, make sure you are not doing viewForSHadow.isUserInteractionEnabled = false anywhere in the code.


问:
How to repeat collision in unity?
I have a bird and a flower if the bird collides with the flower, the flower Destroys and another flower grows, else the flower drops and the bird goes away.

The problem is the newly created flower doesn't collide with the bird and just drops. how can I solve this?

```<code>public SpriteRenderer bird;
public SpriteRenderer flower;

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("bird"))
    {
        Destroy(this.gameObject);
        float x = Random.Range(-8f, 8f);
        Instantiate(flower, new Vector3(x, 6, 0), Quaternion.identity);
    }
    else if (collision.gameObject.CompareTag("flower"))
    {
        Destroy(bird);
    }
}
</code>```

答:
You're instantiating the flower using Spriterenderer instead of a GameObject. Try changing public SpriteRenderer flower; to public GameObject flower; and create a prefab out of the flower Object.

If you don't know how to create a prefab, all you need to do is drag a GameObject from your scene to an assets map. If this is still unclear to you, here is a reference to the Unity documentation: https://docs.unity3d.com/Manual/CreatingPrefabs.html

Once you've created the prefab you can drag the prefab onto the script into the flower GameObject. Then it should work.

If you have more questions make sure to ask them!

Title: How to repeat collision in unity?

Body:
I have a bird and a flower if the bird collides with the flower, the flower Destroys and another flower grows, else the flower drops and the bird goes away.

The problem is the newly created flower doesn't collide with the bird and just drops. how can I solve this?

public SpriteRenderer bird;
public SpriteRenderer flower;

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("bird"))
    {
        Destroy(this.gameObject);
        float x = Random.Range(-8f, 8f);
        Instantiate(flower, new Vector3(x, 6, 0), Quaternion.identity);
    }
    else if (collision.gameObject.CompareTag("flower"))
    {
        Destroy(bird);
    }
}


问:
Manually creating a foreign key for Android room for a nested array
My json response is:

```<code>{
    "categories": [
        {
            "categoryName": "Events",
            "entityId": "QwN9goUaw6",
             .....
        }
    ],
    "entityId": "T1nnwwpjOM"
}
</code>```

My initial plan was to follow how Google did it in their GithubSampleBrowser, except they change from a List Integer to a List String using StringUtil methods, so I decided to change tactic and try and follow what some others have said in here to convert it to a String and back to an ArrayList.

I thought I had the right query that I wanted to eventually do i.e.

```<code>@Query("SELECT * FROM category_table WHERE entityId in (:entityId) ORDER BY sortIndex ASC")
public abstract LiveData<List<Category>> loadById(List<String> entityId);
</code>```

My models are currently looking like:

CategorySearchResult

```<code>@NonNull
@PrimaryKey
private String entityId;
@Nullable
private String query;
public List<Category> categories;
private String lastUpdated;
</code>```

Category

```<code>@NonNull
@PrimaryKey(autoGenerate = true)
private int id;
private Integer sortIndex;
private String storyboardId;
@NonNull
private String entityId;
private String categoryName;
private String menuId;
</code>```

My attempt at the convertors:

```<code>@TypeConverter
public static List<Category> fromStringToCategory(String value) {
    if (value != null) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<Category>>() {
        }.getType();
        List<Category> categoryList = gson.fromJson(value,type);
        return categoryList;
    }
    return null;
}

@TypeConverter
public static String fromCategoryToString(List<Category> categories) {
    if (categories != null) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<Category>>() {
        }.getType();
        String json = gson.toJson(categories, type);
        return json;
    }
    return null;
}
</code>```

What i thought might be easier is to generate a list of entityIds of category part of categorySearchResult and build a @Relationship between them. I've looked at the android documentation on the user and pets but can't properly relate it to my data so any advice would be greatly appreciated.

答:
In the end I kept them seperate and by putting the query as the primary key, it also seems to accept a blank query which i wasn't sure about, it would allow it to overwrite. Then I simply did the reverse for delete using the in function, probably could do with the relationship being built for cascade delete but for now, it seems to work reasonably well.

So in summary

Whenever my mutablelivedata changes, it uses that query to pass through to my CategorySearchResult which brings back the entityIds based on that as a list. I then put the categories seperately in its own class as normal.

Body:
My json response is:

{
    "categories": [
        {
            "categoryName": "Events",
            "entityId": "QwN9goUaw6",
             .....
        }
    ],
    "entityId": "T1nnwwpjOM"
}

My initial plan was to follow how Google did it in their GithubSampleBrowser, except they change from a List Integer to a List String using StringUtil methods, so I decided to change tactic and try and follow what some others have said in here to convert it to a String and back to an ArrayList.

I thought I had the right query that I wanted to eventually do i.e.

@Query("SELECT * FROM category_table WHERE entityId in (:entityId) ORDER BY sortIndex ASC")
public abstract LiveData<List<Category>> loadById(List<String> entityId);

My models are currently looking like:

CategorySearchResult

@NonNull
@PrimaryKey
private String entityId;
@Nullable
private String query;
public List<Category> categories;
private String lastUpdated;

Category

@NonNull
@PrimaryKey(autoGenerate = true)
private int id;
private Integer sortIndex;
private String storyboardId;
@NonNull
private String entityId;
private String categoryName;
private String menuId;

My attempt at the convertors:

@TypeConverter
public static List<Category> fromStringToCategory(String value) {
    if (value != null) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<Category>>() {
        }.getType();
        List<Category> categoryList = gson.fromJson(value,type);
        return categoryList;
    }
    return null;
}

@TypeConverter
public static String fromCategoryToString(List<Category> categories) {
    if (categories != null) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<Category>>() {
        }.getType();
        String json = gson.toJson(categories, type);
        return json;
    }
    return null;
}

What i thought might be easier is to generate a list of entityIds of category part of categorySearchResult and build a @Relationship between them. I've looked at the android documentation on the user and pets but can't properly relate it to my data so any advice would be greatly appreciated.


问:
How to edit ListBox items via IEditableCollectionView
I have a ListBox, which ItemsSource is bound to ViewModel's ObservableCollection.
Now I'm making a custom cotrol, which should manipilate ListBox items.
For instance, move items up/down.
I can't work with ItemsSource, because I want this control to work with variant data types, and I don't know what Type it will be.
All I know about ItemsSource type - it will be IEnumerable.
So I wrote code that uses IEditableCollectionView to swap adjacent items' property values.
It works fine if ItemsSource is an ObservableCollection of some complex type - ObservableCollection<Customers>.

```<code>private void ItemsSwapComplex(object originalSource, object originalDestination)
{
    IEditableCollectionView items = ListBoxToManage.Items;
    Type type = originalSource.GetType();

    // Create clones of Source and Destination
    // DOES NOT WORK WITH <string>
    dynamic cloneSource = Activator.CreateInstance(type);
    dynamic cloneDestination = Activator.CreateInstance(type);

    // Copy property values from Original to Clone
    PropertiesCopyComlex(originalSource, cloneSource);
    PropertiesCopyComlex(originalDestination, cloneDestination);

    // Copy new property values to the Source item
    items.EditItem(originalSource);
    object editSource = items.CurrentEditItem;
    PropertiesCopyComlex(cloneDestination, editSource);
    items.CommitEdit();

    // Copy new property values to the Destination item
    items.EditItem(originalDestination);
    object editDestination = items.CurrentEditItem;
    PropertiesCopyComlex(cloneSource, editDestination);
    items.CommitEdit();
}

private void PropertiesCopyComlex(object originalSource, object originalDestination)
{
    foreach (var v in originalSource.GetType().GetProperties())
    {
        v.SetValue(originalDestination, v.GetValue(originalSource));
    }
}
</code>```

But if ItemsSource is a collection of simple type, like ObservableCollection<string> - it throws an exception, that string doesn't have a constructor.
And I dont understand how to use IEditableCollectionView to edit simple string ListBox items.
This code does not affect ItemsSource at all:

```<code>IEditableCollectionView items = ListBoxToManage.Items;

items.EditItem(originalSource);
object editSource = items.CurrentEditItem;
editSource = "New string";
items.CommitEdit();
</code>```

How do I use IEditableCollectionView to edit a single string item of ItemsSource?

UPDATE: this post implies that my task is not possible. Must use a wrapper for string. And for my particular task - wrapper must implement INotifyPropertyChanged, and have at least one, parameterless, constructor

答:
How do I use IEditableCollectionView to edit a single string item of ItemsSource?

You cannot edit a System.String because it's immutable, i.e. it cannot be modified after its creation.

Why .NET String is immutable?

If you use a mutable wrapper with a string property you can indeed modify the wrapper, but you can't assume that every type T that the enumerator returns is mutable.

Body:
I have a ListBox, which ItemsSource is bound to ViewModel's ObservableCollection.
Now I'm making a custom cotrol, which should manipilate ListBox items.
For instance, move items up/down.
I can't work with ItemsSource, because I want this control to work with variant data types, and I don't know what Type it will be.
All I know about ItemsSource type - it will be IEnumerable.
So I wrote code that uses IEditableCollectionView to swap adjacent items' property values.
It works fine if ItemsSource is an ObservableCollection of some complex type - ObservableCollection<Customers>.

private void ItemsSwapComplex(object originalSource, object originalDestination)
{
    IEditableCollectionView items = ListBoxToManage.Items;
    Type type = originalSource.GetType();

    // Create clones of Source and Destination
    // DOES NOT WORK WITH <string>
    dynamic cloneSource = Activator.CreateInstance(type);
    dynamic cloneDestination = Activator.CreateInstance(type);

    // Copy property values from Original to Clone
    PropertiesCopyComlex(originalSource, cloneSource);
    PropertiesCopyComlex(originalDestination, cloneDestination);

    // Copy new property values to the Source item
    items.EditItem(originalSource);
    object editSource = items.CurrentEditItem;
    PropertiesCopyComlex(cloneDestination, editSource);
    items.CommitEdit();

    // Copy new property values to the Destination item
    items.EditItem(originalDestination);
    object editDestination = items.CurrentEditItem;
    PropertiesCopyComlex(cloneSource, editDestination);
    items.CommitEdit();
}

private void PropertiesCopyComlex(object originalSource, object originalDestination)
{
    foreach (var v in originalSource.GetType().GetProperties())
    {
        v.SetValue(originalDestination, v.GetValue(originalSource));
    }
}

But if ItemsSource is a collection of simple type, like ObservableCollection<string> - it throws an exception, that string doesn't have a constructor.
And I dont understand how to use IEditableCollectionView to edit simple string ListBox items.
This code does not affect ItemsSource at all:

IEditableCollectionView items = ListBoxToManage.Items;

items.EditItem(originalSource);
object editSource = items.CurrentEditItem;
editSource = "New string";
items.CommitEdit();

How do I use IEditableCollectionView to edit a single string item of ItemsSource?

UPDATE: this post implies that my task is not possible. Must use a wrapper for string. And for my particular task - wrapper must implement INotifyPropertyChanged, and have at least one, parameterless, constructor


问:
What does the [Intrinsic] attribute in C# do?
A quick Google search for "instrinsic attribute c#" only returns articles about other attributes, such as [Serializable]. Apparently these are called "intrinsic attributes".

However, there is also an attribute in C# that is itself called [Intrinsic] and I'm trying to figure out what exactly it is and how it works. It doesn't exist on the common attributes page of the .NET Documentation, or anywhere else in the documentation as far as I can see.

This attribute is used inside of .NET Core in several places, for example, in the System.Numerics.Vectors folder, such as Vector2_Intrinsics.cs. Code snippet:

[Intrinsic]
public Vector2(float x, float y)
{
    X = x;
    Y = y;
}
```

答:
Here's what I've managed to find after a very limited search through dotnet/corefx repository on github.

[Intrinsic] marks methods, properties and fields that can be potentially replaced/optimized by JIT. Source code comments say something similar (IntrinsicAttribute.cs):

Calls to methods or references to fields marked with this attribute may be replaced at some call sites with jit intrinsic expansions. Types marked with this attribute may be specially treated by the runtime/compiler.

Purpose

For core developers, [Intrinsic] serves at least two purposes:

it notifies the developer that the code of the marked field, method or property can be replaced by VM. So, if the code changes, the change should probably be introduced in both places;

it is used as a flag for JIT-optimizer to quickly identify methods that can potentially be optimized.

To give a rough example: JIT-optimizer can replace Enum.HasFlag with a simple bitwise comparison in some cases and not in the others. To do this it needs to identify the method as Enum.HasFlag, check some conditions and replace it with a more optimal implementation. The optimizer can identify the method by name, but, for performance reasons, it's better to filter out methods by a simple flag before performing string comparisons.

Usage

The attribute is only relevant to core developers. You should only use it in an internal class and only in the case when you want to propose very specific JIT-level optimizations for it. [Intrinsic] is pretty much restricted to a small set of widely used .Net classes, that, for some reason, can't be optimized by other means.

from the comments: I'm planning to propose a Color struct for .NET Core which needs to behave similarly to other built-in types for consistency.

You should probably not use [Intrinsic] in your initial proposal. After it passes, you can think about optimization, and if you have a valid scenario when Color will benefit from low level optimizations, you can suggest using [Intrinsic] on some of its methods or properties.

How It Works

Here's how [Intrinsic] is currently used in core:

it is defined as a well-known attribute (wellknownattributes.h):

```<code>case WellKnownAttribute::Intrinsic:
    return "System.Runtime.CompilerServices.IntrinsicAttribute";
</code>```

VM parses it and sets the IsJitIntrinsic flag to true for a method (methodtablebuilder.cpp):

```<code>if (bmtProp->fIsHardwareIntrinsic || (S_OK == GetCustomAttribute(pMethod->GetMethodSignature().GetToken(),
                                            WellKnownAttribute::Intrinsic,
                                            NULL,
                                            NULL)))
{
    pNewMD->SetIsJitIntrinsic();
}
</code>```

this flag is used to set another flag in method attributes (jitinterface.cpp):

```<code>if (pMD->IsJitIntrinsic())
    result |= CORINFO_FLG_JIT_INTRINSIC;
</code>```

this flag is later used to filter out methods which are obviously not intrinsic (importer.cpp):

```<code>if ((mflags & (CORINFO_FLG_INTRINSIC | CORINFO_FLG_JIT_INTRINSIC)) != 0)
{
    const bool isTail = canTailCall && (tailCall != 0);

    call = impIntrinsic(newobjThis, clsHnd, methHnd, sig, mflags, pResolvedToken->token, readonlyCall, isTail,
                        pConstrainedResolvedToken, callInfo->thisTransform, &intrinsicID, &isSpecialIntrinsic);
</code>```

impIntrinsic then calls lookupNamedIntrinsic to identify (mostly by name) methods that really (not just potentially) should be optimized;

after all of that importer can perform optimizations based on method. For example, optimization for Enum.HasFlag (importer.cpp):

```<code> case NI_System_Enum_HasFlag:
    {
        GenTree* thisOp  = impStackTop(1).val;
        GenTree* flagOp  = impStackTop(0).val;
        GenTree* optTree = gtOptimizeEnumHasFlag(thisOp, flagOp);

        if (optTree != nullptr)
        {
            // Optimization successful. Pop the stack for real.
            impPopStack();
            impPopStack();
            retNode = optTree;
        }
        else
        {
            // Retry optimizing this during morph.
            isSpecial = true;
        }

        break;
    }
</code>```

DISCLAIMER: as far as I can tell, the attribute's behaviour is not properly documented anywhere and, thus, is subject for change. The description above is only relevant to code currently in master, this part of core is actively developed and the whole process can be changed in the future.

History

Here's a short timeline of [Intrinsic] based on github repository history:

At some time before 2014 [JitIntrisic] attribute was introduced as a part of System.Numerics with a goal to support new processor instructions (see How does JitIntrinsicAttribute affect code generation?).

On June 6, 2016, Chris McKinsey opened an issue #5626. "Optimize enum1.HasFlag(enum2) into inline bittest without boxing allocations when types are the same". At the time, Enum.HasFlag had a well-known performance issues (see What is it that makes Enum.HasFlag so slow?).

While working on the issue Andy Ayers suggested to introduce a universal mechanism to introduce JIT intrinsics (Issue #13813: Add more flexible method for specifying jit instrinsics)

This led to two pull requests: New jit intrinsic support introduced the general mechanics for [Intrinsic] and JIT: optimize Enum.HasFlag implemented it for Enum.HasFlag. I suggest going through both of them as they are extremely illustrative on the changes that come with [Intrinsic].

Later, during the discussion about moving Vector classes to the CoreLib it was suggested that [JitIntrinsic] isn't used anywhere and should be replaced/removed:

@jkotas: We should not need the JitIntrinsicAttribute. As far as I know, this attribute was future proofing, never used for anything real. We should delete it, and use the IntrinsicAttribute from CoreLib instead.

Promptly, [JitIntrinsic] was removed and replace by [Intrinsic] (Replace JitIntrinsicAttribute with IntrinsicAttribute). That's how this attribute came to be in Vector2.

Body:
Here's what I've managed to find after a very limited search through dotnet/corefx repository on github.

[Intrinsic] marks methods, properties and fields that can be potentially replaced/optimized by JIT. Source code comments say something similar (IntrinsicAttribute.cs):

Calls to methods or references to fields marked with this attribute may be replaced at some call sites with jit intrinsic expansions. Types marked with this attribute may be specially treated by the runtime/compiler.

Purpose

For core developers, [Intrinsic] serves at least two purposes:

it notifies the developer that the code of the marked field, method or property can be replaced by VM. So, if the code changes, the change should probably be introduced in both places;

it is used as a flag for JIT-optimizer to quickly identify methods that can potentially be optimized.

To give a rough example: JIT-optimizer can replace Enum.HasFlag with a simple bitwise comparison in some cases and not in the others. To do this it needs to identify the method as Enum.HasFlag, check some conditions and replace it with a more optimal implementation. The optimizer can identify the method by name, but, for performance reasons, it's better to filter out methods by a simple flag before performing string comparisons.

Usage

The attribute is only relevant to core developers. You should only use it in an internal class and only in the case when you want to propose very specific JIT-level optimizations for it. [Intrinsic] is pretty much restricted to a small set of widely used .Net classes, that, for some reason, can't be optimized by other means.

from the comments: I'm planning to propose a Color struct for .NET Core which needs to behave similarly to other built-in types for consistency.

You should probably not use [Intrinsic] in your initial proposal. After it passes, you can think about optimization, and if you have a valid scenario when Color will benefit from low level optimizations, you can suggest using [Intrinsic] on some of its methods or properties.

How It Works

Here's how [Intrinsic] is currently used in core:

it is defined as a well-known attribute (wellknownattributes.h):

case WellKnownAttribute::Intrinsic:
    return "System.Runtime.CompilerServices.IntrinsicAttribute";

VM parses it and sets the IsJitIntrinsic flag to true for a method (methodtablebuilder.cpp):

if (bmtProp->fIsHardwareIntrinsic || (S_OK == GetCustomAttribute(pMethod->GetMethodSignature().GetToken(),
                                            WellKnownAttribute::Intrinsic,
                                            NULL,
                                            NULL)))
{
    pNewMD->SetIsJitIntrinsic();
}

this flag is used to set another flag in method attributes (jitinterface.cpp):

if (pMD->IsJitIntrinsic())
    result |= CORINFO_FLG_JIT_INTRINSIC;

this flag is later used to filter out methods which are obviously not intrinsic (importer.cpp):

if ((mflags & (CORINFO_FLG_INTRINSIC | CORINFO_FLG_JIT_INTRINSIC)) != 0)
{
    const bool isTail = canTailCall && (tailCall != 0);

    call = impIntrinsic(newobjThis, clsHnd, methHnd, sig, mflags, pResolvedToken->token, readonlyCall, isTail,
                        pConstrainedResolvedToken, callInfo->thisTransform, &intrinsicID, &isSpecialIntrinsic);

impIntrinsic then calls lookupNamedIntrinsic to identify (mostly by name) methods that really (not just potentially) should be optimized;

after all of that importer can perform optimizations based on method. For example, optimization for Enum.HasFlag (importer.cpp):

 case NI_System_Enum_HasFlag:
    {
        GenTree* thisOp  = impStackTop(1).val;
        GenTree* flagOp  = impStackTop(0).val;
        GenTree* optTree = gtOptimizeEnumHasFlag(thisOp, flagOp);

        if (optTree != nullptr)
        {
            // Optimization successful. Pop the stack for real.
            impPopStack();
            impPopStack();
            retNode = optTree;
        }
        else
        {
            // Retry optimizing this during morph.
            isSpecial = true;
        }

        break;
    }

DISCLAIMER: as far as I can tell, the attribute's behaviour is not properly documented anywhere and, thus, is subject for change. The description above is only relevant to code currently in master, this part of core is actively developed and the whole process can be changed in the future.

History

Here's a short timeline of [Intrinsic] based on github repository history:

At some time before 2014 [JitIntrisic] attribute was introduced as a part of System.Numerics with a goal to support new processor instructions (see How does JitIntrinsicAttribute affect code generation?).

On June 6, 2016, Chris McKinsey opened an issue #5626. "Optimize enum1.HasFlag(enum2) into inline bittest without boxing allocations when types are the same". At the time, Enum.HasFlag had a well-known performance issues (see What is it that makes Enum.HasFlag so slow?).

While working on the issue Andy Ayers suggested to introduce a universal mechanism to introduce JIT intrinsics (Issue #13813: Add more flexible method for specifying jit instrinsics)

This led to two pull requests: New jit intrinsic support introduced the general mechanics for [Intrinsic] and JIT: optimize Enum.HasFlag implemented it for Enum.HasFlag. I suggest going through both of them as they are extremely illustrative on the changes that come with [Intrinsic].

Later, during the discussion about moving Vector classes to the CoreLib it was suggested that [JitIntrinsic] isn't used anywhere and should be replaced/removed:

@jkotas: We should not need the JitIntrinsicAttribute. As far as I know, this attribute was future proofing, never used for anything real. We should delete it, and use the IntrinsicAttribute from CoreLib instead.

Promptly, [JitIntrinsic] was removed and replace by [Intrinsic] (Replace JitIntrinsicAttribute with IntrinsicAttribute). That's how this attribute came to be in Vector2.


问:
Fatal error: Call to a member function query() on a non-object in
Fatal error: Call to a member function query() on a non-object on line:
$result = $conn->query($sql) or die(mysqli_error());

Who knows whats wrong and how to fix it?

```<code><?php
function dbConnect($usertype, $connectionType = 'mysqli') {
  $host = 'localhost';
  $db = 'phpsols';
  if ($usertype  == 'read') {
    $user = 'psread';
    $pwd = '123';
  } elseif ($usertype == 'write') {
    $user = 'pswrite';
    $pwd = '123';
  } else {
    exit('Unrecognized connection type');
  }
  if ($connectionType == 'mysqli') {
    return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
  } else {
    try {
      return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
    } catch (PDOException $e) {
      echo 'Cannot connect to database';
      exit;
    }
  }
}

// connect to MySQL
$conn = dbConnect('read');
// prepare the SQL query
$sql = 'SELECT * FROM images';
// submit the query and capture the result
**$result = $conn->query($sql) or die(mysqli_error());**
// find out how many records were retrieved
$numRows = $result->num_rows;
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Connecting with MySQLi</title>
</head>

<body>
<p>A total of <?php echo $numRows; ?> records were found.</p>
</body>
</html>
</code>```

答:
I know this has been answered, but just wanted to add my own 2 cents worth....

I was googling "return new mysqli" to fix this very problem. The code is a snippet from an e-book (PHP Solutions. Dynamic Web Design Made Easy.) - 2nd Edition if I'm not too mistaken! Ironically the book is supposed to be teaching PHP basics (in this case DB connection methods) to poor souls like myself and easyrider. I have very limited understanding, as this book is my own introduction to PHP coding but I managed to suss out that creating or rather instantiating an actual object, passing it to a temporary variable and then returning that variable was the solution.

Annoyingly, this was demonstrated correctly in the first edition of said publication.

I dont know if Google will cache or index my post, but it might help others who are learning from the book, to discover that the code example is flawed, and as the time of writing, the error is not listed in the errata on the publishers website.

ContentLicense: CC BY-SA 2.5

Body:
Fatal error: Call to a member function query() on a non-object on line:
$result = $conn->query($sql) or die(mysqli_error());

Who knows whats wrong and how to fix it?

<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
  $host = 'localhost';
  $db = 'phpsols';
  if ($usertype  == 'read') {
    $user = 'psread';
    $pwd = '123';
  } elseif ($usertype == 'write') {
    $user = 'pswrite';
    $pwd = '123';
  } else {
    exit('Unrecognized connection type');
  }
  if ($connectionType == 'mysqli') {
    return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
  } else {
    try {
      return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
    } catch (PDOException $e) {
      echo 'Cannot connect to database';
      exit;
    }
  }
}

// connect to MySQL
$conn = dbConnect('read');
// prepare the SQL query
$sql = 'SELECT * FROM images';
// submit the query and capture the result
**$result = $conn->query($sql) or die(mysqli_error());**
// find out how many records were retrieved
$numRows = $result->num_rows;
?>
<!DOCTYPE HTML>

<meta charset="utf-8">
<title>Connecting with MySQLi</title>

A total of <?php echo $numRows; ?> records were found.

ContentLicense: CC BY-SA 3.0


问:
How to replace text from Row name in R
Currency Name

ISO Code

Base Currency

Decimal Points

Accounting Rates as of 11/1/03

Accounting Rates as of 12/1/03

Accounting Rates as of 1/1/04

I have column names like this (270 columns) where I want to replace Accounting Rates as of using gsub however, I am not able to do it.

```<code>Fxfile[1,] <- gsub("Accounting Rates as of ","",Fxfile[1,])
</code>```

答:
Column names are not the values of the first row. So just as ANG mentioned it, you should use the colnames() function which use the named attributes given to each column. (Attributes are "advanced" feature in R, yet quite useful)
Try out this:

colnames(Fxfile) <- gsub("Accounting Rates as of ","",colnames(Fxfile))
```

PS: for future use, please write your question according to the Best practice guide for asking a good question in Stackoverflow. I answered this question as I understood it, do not hesitate to correct any misunderstanding from my part.

Title: How to replace text from Row name in R

Body:
Currency Name

ISO Code

Base Currency

Decimal Points

Accounting Rates as of 11/1/03

Accounting Rates as of 12/1/03

Accounting Rates as of 1/1/04

I have column names like this (270 columns) where I want to replace Accounting Rates as of using gsub however, I am not able to do it.

Fxfile[1,] <- gsub("Accounting Rates as of ","",Fxfile[1,])

Body:
Column names are not the values of the first row. So just as ANG mentioned it, you should use the colnames() function which use the named attributes given to each column. (Attributes are "advanced" feature in R, yet quite useful)
Try out this:

colnames(Fxfile) <- gsub("Accounting Rates as of ","",colnames(Fxfile))

PS: for future use, please write your question according to the Best practice guide for asking a good question in Stackoverflow. I answered this question as I understood it, do not hesitate to correct any misunderstanding from my part.


问:
Update a post's taxonomy when a specific acf_form() is updated
I'm currently building a parent admissions portal for a school. Pupils are created as a custom post type (pupil) when a user (parent) signs up – the parent is the author of each pupil post. These pupil posts have a custom taxonomy named status which determines if the pupil's admission forms have been submitted and reviewed. I'm using acf_form() to create the admission forms that display on the frontend and are filled in by the parent user. Each pupil currently has 6 ACF field groups (6 forms). I'm getting the keys of these field groups and looping through them with a foreach loop to display 6 individual acf_form() forms for each of the field groups.

When a pupil post is created, it's status is automatically set to "in progress" i.e. the parent is filling out the forms.

What I want

When a user updates one specific form/field group of the 6, I want the pupil's status taxonomy to be changed from "in progress" to "submitted". To explain further, this form is the final form the user/parent needs to complete and so once they press the acf_form() update button, the taxonomy should be updated.

So essentially...

I'm looking for a way to hook into the action of saving an acf_form(), doing a check to see if the form that was updated was a specific form (by the field group key?) and then updating the status taxonomy of the post that the form was submitted on.

What I've tried

I've tried using ACF's pre_save_post filter and save_post action but I can't figure out a way to check which field group was saved as those two functions just give me the $post_id. I simply added the code from the ACF Docs and tried to print_r() / echo the data from the functions to see if there was any way for me to check the field group key, but nothing is being printed on the page when I update the acf_form().

So...

Does anyone know how I can hook into that action properly and get the correct data that will allow me to do the checks that I want?

答:
I found a way to do what I'm looking for but I feel like it isn't a very good or robust way to do it so I'm still open to suggestions/advice.

The code:

```<code>function my_acf_save_post( $post_id ) {

    $keys_of_specific_field_group = array(
        'field_5ce2970bc9fbd' => '',
        'field_5ce29741c9fbe' => '',
        'field_5ce297c7c9fc1' => '',
        'field_5ce297ddc9fc2' => '',
        'field_5ce297fac9fc3' => '',
        'field_5ce2980ec9fc4' => '',
        'field_5ce29874c9fc5' => '',
        '_validate_email' => ''
    );

    if ( $_POST['acf'] === $keys_of_specific_field_group ) {

        wp_set_post_terms($post_id, array(21), 'status');

    }

}

add_action('acf/save_post', 'my_acf_save_post', 1);
</code>```

Basically I am just checking if the field keys returned from $_POST['acf'] match the field keys of the fields in the specific form I want to check, and if they do I am updating the post's status taxonomy (array(21) is the ID of the 'submitted' term I want to set).

Hopefully there's a nicer/better way to do this as if any fields are added to the field group I will have to manually update the code.

Body:
I found a way to do what I'm looking for but I feel like it isn't a very good or robust way to do it so I'm still open to suggestions/advice.

The code:

function my_acf_save_post( $post_id ) {

    $keys_of_specific_field_group = array(
        'field_5ce2970bc9fbd' => '',
        'field_5ce29741c9fbe' => '',
        'field_5ce297c7c9fc1' => '',
        'field_5ce297ddc9fc2' => '',
        'field_5ce297fac9fc3' => '',
        'field_5ce2980ec9fc4' => '',
        'field_5ce29874c9fc5' => '',
        '_validate_email' => ''
    );

    if ( $_POST['acf'] === $keys_of_specific_field_group ) {

        wp_set_post_terms($post_id, array(21), 'status');

    }

}

add_action('acf/save_post', 'my_acf_save_post', 1);

Basically I am just checking if the field keys returned from $_POST['acf'] match the field keys of the fields in the specific form I want to check, and if they do I am updating the post's status taxonomy (array(21) is the ID of the 'submitted' term I want to set).

Hopefully there's a nicer/better way to do this as if any fields are added to the field group I will have to manually update the code.


问:
Why am I getting "A sql/plsql compilation error occured." error because of semicolons in trigger creation?
I am trying to create a trigger using 'Oracle SQL Developer' in 'Oracle 11G'. But every time a try it I get 'ORA-24344: success with compilation error' message and my trigger gets partially created with errors.

My Oracle SQL Developer version is '3.0.04' and server version is 'Oracle Database 11G Release 11.2.0.4.0 (64-bit)'. Every time I try creating a trigger I get the same message and I realized that it stops execution at the first semicolon. I tried everything written in here that looks like having the same problem, but none of them helped.

For example I am trying to create a trigger like:

```<code>create or replace
TRIGGER TEST_TRG
BEFORE INSERT ON TEST_TABLE2
REFERENCING NEW AS NEW FOR EACH ROW
DECLARE testvar number;
BEGIN
testvar := test_sequence.nextval;
INSERT INTO TEST_TABLE(id,data) VALUES(testvar,:NEW.id);
END TEST_TRG;
/
</code>```

I am getting:

```<code>Error starting at line 0 in command:
CREATE OR REPLACE TRIGGER TEST_TRG
BEFORE INSERT ON TEST_TABLE2
REFERENCING NEW AS NEW FOR EACH ROW
DECLARE testvar number
Error report:
SQL Command: trıgger TEST_TRG
Failed: ORA-24344: success with compilation error
24344. 00000 -  "success with compilation error"
*Cause:    A sql/plsql compilation error occurred.
*Action:   Return OCI_SUCCESS_WITH_INFO along with the error code
Bind Variable "NEW" is NOT DECLARED
anonymous block completed
</code>```

As you can see, it thinks that the statement ends at first occurrence of semicolon. To prove my suspicion I performed one more test removing the unnecessary DECLARE statement:

```<code>CREATE OR REPLACE TRIGGER TEST_TRG
BEFORE INSERT ON TEST_TABLE2
REFERENCING NEW AS NEW FOR EACH ROW
BEGIN
INSERT INTO TEST_TABLE(id,data) VALUES(test_sequence.nextval,:NEW.id);
END TEST_TRG;
/
</code>```

Which caused the same error but at different position (again at first semicolon):

```<code>Error starting at line 0 in command:
CREATE OR REPLACE TRIGGER TEST_TRG
BEFORE INSERT ON TEST_TABLE2
REFERENCING NEW AS NEW FOR EACH ROW
BEGIN
INSERT INTO TEST_TABLE(id,data) VALUES(test_sequence.nextval,:NEW.id)
Error report:
SQL Command: trıgger TEST_TRG
Failed: ORA-24344: success with compilation error
24344. 00000 -  "success with compilation error"
*Cause:    A sql/plsql compilation error occurred.
*Action:   Return OCI_SUCCESS_WITH_INFO along with the error code

Error starting at line 6 in command:
END TEST_TRG
Error report:
Unknown Command
</code>```

So the question is obvious. Why can't I create those triggers and what should I do to create them?

答:
See this example (11.2.0.4):

Tables and a sequence:

```<code>SQL> create table test_table2 (id number, data varchar2(20));

Table created.

SQL> create table test_table  (id number, data varchar2(20));

Table created.

SQL> create sequence test_sequence;

Sequence created.
</code>```

Trigger:

```<code>SQL> create or replace trigger test_trg
  2     before insert
  3     on test_table2
  4     for each row
  5  begin
  6     insert into test_table (id, data)
  7          values (test_sequence.nextval, :new.id);
  8  end test_trg;
  9  /

Trigger created.
</code>```

Testing:

```<code>SQL> insert into test_table2 (id, data) values (100, 'A');

1 row created.

SQL> select * from test_table;

        ID DATA
---------- --------------------
         1 100

SQL> select * from test_table2;

        ID DATA
---------- --------------------
       100 A

SQL>
</code>```

By the way, the first trigger whose code you posted works OK in my database:

```<code>SQL> create or replace
  2  TRIGGER TEST_TRG
  3  BEFORE INSERT ON TEST_TABLE2
  4  REFERENCING NEW AS NEW FOR EACH ROW
  5  DECLARE testvar number;
  6  BEGIN
  7  testvar := test_sequence.nextval;
  8  INSERT INTO TEST_TABLE(id,data) VALUES(testvar,:NEW.id);
  9  END TEST_TRG;
 10  /

Trigger created.

SQL>
</code>```

The second:

```<code>SQL> CREATE OR REPLACE TRIGGER TEST_TRG
  2  BEFORE INSERT ON TEST_TABLE2
  3  REFERENCING NEW AS NEW FOR EACH ROW
  4  BEGIN
  5  INSERT INTO TEST_TABLE(id,data) VALUES(test_sequence.nextval,:NEW.id);
  6  END TEST_TRG;
  7  /

Trigger created.

SQL>
</code>```

So, maybe it is about your quite old SQL Developer version. I suggest you upgrade to the most recent version (downloadable for free on Oracle Technology Network).

Body:
I am trying to create a trigger using 'Oracle SQL Developer' in 'Oracle 11G'. But every time a try it I get 'ORA-24344: success with compilation error' message and my trigger gets partially created with errors.

My Oracle SQL Developer version is '3.0.04' and server version is 'Oracle Database 11G Release 11.2.0.4.0 (64-bit)'. Every time I try creating a trigger I get the same message and I realized that it stops execution at the first semicolon. I tried everything written in here that looks like having the same problem, but none of them helped.

For example I am trying to create a trigger like:

create or replace
TRIGGER TEST_TRG
BEFORE INSERT ON TEST_TABLE2
REFERENCING NEW AS NEW FOR EACH ROW
DECLARE testvar number;
BEGIN
testvar := test_sequence.nextval;
INSERT INTO TEST_TABLE(id,data) VALUES(testvar,:NEW.id);
END TEST_TRG;
/

I am getting:

Error starting at line 0 in command:
CREATE OR REPLACE TRIGGER TEST_TRG
BEFORE INSERT ON TEST_TABLE2
REFERENCING NEW AS NEW FOR EACH ROW
DECLARE testvar number
Error report:
SQL Command: trıgger TEST_TRG
Failed: ORA-24344: success with compilation error
24344. 00000 -  "success with compilation error"
*Cause:    A sql/plsql compilation error occurred.
*Action:   Return OCI_SUCCESS_WITH_INFO along with the error code
Bind Variable "NEW" is NOT DECLARED
anonymous block completed

As you can see, it thinks that the statement ends at first occurrence of semicolon. To prove my suspicion I performed one more test removing the unnecessary DECLARE statement:

CREATE OR REPLACE TRIGGER TEST_TRG
BEFORE INSERT ON TEST_TABLE2
REFERENCING NEW AS NEW FOR EACH ROW
BEGIN
INSERT INTO TEST_TABLE(id,data) VALUES(test_sequence.nextval,:NEW.id);
END TEST_TRG;
/

Which caused the same error but at different position (again at first semicolon):

Error starting at line 0 in command:
CREATE OR REPLACE TRIGGER TEST_TRG
BEFORE INSERT ON TEST_TABLE2
REFERENCING NEW AS NEW FOR EACH ROW
BEGIN
INSERT INTO TEST_TABLE(id,data) VALUES(test_sequence.nextval,:NEW.id)
Error report:
SQL Command: trıgger TEST_TRG
Failed: ORA-24344: success with compilation error
24344. 00000 -  "success with compilation error"
*Cause:    A sql/plsql compilation error occurred.
*Action:   Return OCI_SUCCESS_WITH_INFO along with the error code

Error starting at line 6 in command:
END TEST_TRG
Error report:
Unknown Command

So the question is obvious. Why can't I create those triggers and what should I do to create them?

Body:
See this example (11.2.0.4):

Tables and a sequence:

SQL> create table test_table2 (id number, data varchar2(20));

Table created.

SQL> create table test_table  (id number, data varchar2(20));

Table created.

SQL> create sequence test_sequence;

Sequence created.

Trigger:

SQL> create or replace trigger test_trg
  2     before insert
  3     on test_table2
  4     for each row
  5  begin
  6     insert into test_table (id, data)
  7          values (test_sequence.nextval, :new.id);
  8  end test_trg;
  9  /

Trigger created.

Testing:

SQL> insert into test_table2 (id, data) values (100, 'A');

1 row created.

SQL> select * from test_table;

        ID DATA
---------- --------------------
         1 100

SQL> select * from test_table2;

        ID DATA
---------- --------------------
       100 A

SQL>

By the way, the first trigger whose code you posted works OK in my database:

SQL> create or replace
  2  TRIGGER TEST_TRG
  3  BEFORE INSERT ON TEST_TABLE2
  4  REFERENCING NEW AS NEW FOR EACH ROW
  5  DECLARE testvar number;
  6  BEGIN
  7  testvar := test_sequence.nextval;
  8  INSERT INTO TEST_TABLE(id,data) VALUES(testvar,:NEW.id);
  9  END TEST_TRG;
 10  /

Trigger created.

SQL>

The second:

SQL> CREATE OR REPLACE TRIGGER TEST_TRG
  2  BEFORE INSERT ON TEST_TABLE2
  3  REFERENCING NEW AS NEW FOR EACH ROW
  4  BEGIN
  5  INSERT INTO TEST_TABLE(id,data) VALUES(test_sequence.nextval,:NEW.id);
  6  END TEST_TRG;
  7  /

Trigger created.

SQL>

So, maybe it is about your quite old SQL Developer version. I suggest you upgrade to the most recent version (downloadable for free on Oracle Technology Network).


问:
how to align multiple line text as the column of the table
I have to display text as follows(please notice that the month should be properly aligned with the months of other two rows, time should be properly aligned with the time of other two rows and so is the date as follows):

and all these values are coming from two way data binding inside a div in an angular 7 project as follows:

```<code><div *ngFor="let date of dates">
{{date.month}} {{date.day}} {{date.time}}
<div>
</code>```

please help me to display these values in the exact same style style.

答:
you can simply do this:

```<code><div *ngFor="let date of dates">
  <span>{{date.month}}</span><span>{{date.day}}</span><span>{{date.time}}</span>
<div>
</code>```

And give some style to these span (padding, margin)...

Body:
I have to display text as follows(please notice that the month should be properly aligned with the months of other two rows, time should be properly aligned with the time of other two rows and so is the date as follows):

and all these values are coming from two way data binding inside a div in an angular 7 project as follows:

{{date.month}} {{date.day}} {{date.time}}

please help me to display these values in the exact same style style.

Body:
you can simply do this:

<div *ngFor="let date of dates">
  <span>{{date.month}}</span><span>{{date.day}}</span><span>{{date.time}}</span>
<div>

And give some style to these span (padding, margin)...


问:
Can I gain access to telephony settings through the contentresolver or elsewhere outside an activity
As part of a test utility on android I am gaining access to the telephony setting in my activity as follows:

```<code>Cursor cursor = getContentResolver().(Uri.parse("content://telephony/carriers"), null, null, null, null);
</code>```

Is it possible to access the settings outside an activity through the content resolver or through another manner.

答:
AndroidTestCase and ActivityInstrumentationTestCase2 both provide methods to get Context

AndroidTestCase:

```<code>getContext();
</code>```

ActivityInstrumentationTestCase2

```<code>getInstrumentation().getContext();
</code>```

This Context provides access to the getContentResolver() but permissions to change are adopted from the application under test.

Body:
As part of a test utility on android I am gaining access to the telephony setting in my activity as follows:

Cursor cursor = getContentResolver().(Uri.parse("content://telephony/carriers"), null, null, null, null);

Is it possible to access the settings outside an activity through the content resolver or through another manner.

Body:
AndroidTestCase and ActivityInstrumentationTestCase2 both provide methods to get Context

AndroidTestCase:

getContext();

ActivityInstrumentationTestCase2

getInstrumentation().getContext();

This Context provides access to the getContentResolver() but permissions to change are adopted from the application under test.


问:
Unable to resolve type: System.String, System.Private.CoreLib, Version 4.0.0.0 - Asp.net Core (.net core 2.1) server, .NET 4.6.1 Client
I've got a legacy client application written in .net 4.6.1 consuming data of a WCF server.
I am trying to replace the WCF server with an ASP.NET Core application and Protobuf serialization.
I am using libraries:

Protobuf-net in both the client and server for serialization/de-serialization

Core WebApi Formatters in the server

Trying in the client side to deserialize the returned content like below:

```<code>var resultData = ProtoBuf.Serializer.Deserialize<ExcelDropdownNode>(response.Content.ReadAsStreamAsync().Result);
</code>```

But I am getting an error in the protobuf library:

Unable to resolve type: System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e (you can use the TypeModel.DynamicTypeFormatting event to provide a custom mapping)

Any idea what could I be doing wrong?

As a side note, I have to return dynamic data in the server and protobuf isn't very happy about it. I have marked a List<object> property with DynamicType=True and changing all ValueTypes to string (i.e 4 -> "4"). This allowed the serialization on the server-side to work.

The dynamic property in the ExcelDropDownCode is as below:

```<code>[ProtoMember(1, DynamicType = true)]
public List<object> DataItems
{
    get { return dataItems; }
    set { dataItems = value; }
}
</code>```

答:
Managed to solve by adding in the client side the type resolution code below:</p>

```<code>RuntimeTypeModel.Default.DynamicTypeFormatting += (sender, args) => {
if (args.FormattedName.Contains("System.String, System.Private.CoreLib"))
{
    args.Type = typeof(string);
}};
</code>```

Body:
I've got a legacy client application written in .net 4.6.1 consuming data of a WCF server.
I am trying to replace the WCF server with an ASP.NET Core application and Protobuf serialization.
I am using libraries:

Protobuf-net in both the client and server for serialization/de-serialization

Core WebApi Formatters in the server

Trying in the client side to deserialize the returned content like below:

var resultData = ProtoBuf.Serializer.Deserialize<ExcelDropdownNode>(response.Content.ReadAsStreamAsync().Result);

But I am getting an error in the protobuf library:

Unable to resolve type: System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e (you can use the TypeModel.DynamicTypeFormatting event to provide a custom mapping)

Any idea what could I be doing wrong?

As a side note, I have to return dynamic data in the server and protobuf isn't very happy about it. I have marked a List<object> property with DynamicType=True and changing all ValueTypes to string (i.e 4 -> "4"). This allowed the serialization on the server-side to work.

The dynamic property in the ExcelDropDownCode is as below:

[ProtoMember(1, DynamicType = true)]
public List<object> DataItems
{
    get { return dataItems; }
    set { dataItems = value; }
}

Body:
Managed to solve by adding in the client side the type resolution code below:

RuntimeTypeModel.Default.DynamicTypeFormatting += (sender, args) => {
if (args.FormattedName.Contains("System.String, System.Private.CoreLib"))
{
    args.Type = typeof(string);
}};


问:
using nz-upload i.e (Using ant-design NG-Zorro) custom Request how to upload image
I am using NG_ZORRO ant design for angular 6 application. I have created a component to upload an image using nz-upload. Now i want to use the custom request for uploading image that holds the action and request headers to upload the image.</p>

答:
This is a snippet from the code playground:

Before you begin, ensure that your HTTP request interceptors (if any) are not modifying the headers

TEMPLATE:

```<code><nz-upload [nzCustomRequest]="customUploadReq" [nzHeaders] = "setMediaUploadHeaders" [nzName]="'file'">
</nz-upload>
</code>```

TS File

```<code>/* nzUpload: Upload */
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { BrowserModule, DomSanitizer } from '@angular/platform-browser'
/* nzUpload: Custom pre-upload checks */
import { /*Observable,*/ Observer } from 'rxjs';
/* nzUpload: Custom Upload request */
import { HttpRequest, HttpClient, HttpEventType, HttpEvent, HttpResponse } from '@angular/common/http';
import { UploadXHRArgs } from 'ng-zorro-antd';

  setMediaUploadHeaders = (file: UploadFile) => {
    return {
      "Content-Type": "multipart/form-data",
      "Accept": "application/json",
    }
  };
  customUploadReq = (item: UploadXHRArgs) => {
    const formData = new FormData();
    formData.append('file', item.file as any); // tslint:disable-next-line:no-any
    ///formData.append('id', '1000');
    const req = new HttpRequest('POST', item.action, formData, {
      reportProgress : true,
      withCredentials: false
    });
    // Always return a `Subscription` object, nz-upload will automatically unsubscribe at the appropriate time
   return this.http.request(req).subscribe((event: HttpEvent<{}>) => {
      if (event.type === HttpEventType.UploadProgress) {
        if (event.total > 0) {
          (event as any).percent = event.loaded / event.total * 100; // tslint:disable-next-line:no-any
        }
        // To process the upload progress bar, you must specify the `percent` attribute to indicate progress.
        item.onProgress(event, item.file);
      } else if (event instanceof HttpResponse) { /* success */
        item.onSuccess(event.body, item.file, event);
      }
    },(err) => { /* error */
      item.onError(err, item.file);
    });
  }
</code>```

Body:
This is a snippet from the code playground:

Before you begin, ensure that your HTTP request interceptors (if any) are not modifying the headers

TEMPLATE:

<nz-upload [nzCustomRequest]="customUploadReq" [nzHeaders] = "setMediaUploadHeaders" [nzName]="'file'">
</nz-upload>

TS File

/* nzUpload: Upload */
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { BrowserModule, DomSanitizer } from '@angular/platform-browser'
/* nzUpload: Custom pre-upload checks */
import { /*Observable,*/ Observer } from 'rxjs';
/* nzUpload: Custom Upload request */
import { HttpRequest, HttpClient, HttpEventType, HttpEvent, HttpResponse } from '@angular/common/http';
import { UploadXHRArgs } from 'ng-zorro-antd';

  setMediaUploadHeaders = (file: UploadFile) => {
    return {
      "Content-Type": "multipart/form-data",
      "Accept": "application/json",
    }
  };
  customUploadReq = (item: UploadXHRArgs) => {
    const formData = new FormData();
    formData.append('file', item.file as any); // tslint:disable-next-line:no-any
    ///formData.append('id', '1000');
    const req = new HttpRequest('POST', item.action, formData, {
      reportProgress : true,
      withCredentials: false
    });
    // Always return a `Subscription` object, nz-upload will automatically unsubscribe at the appropriate time
   return this.http.request(req).subscribe((event: HttpEvent<{}>) => {
      if (event.type === HttpEventType.UploadProgress) {
        if (event.total > 0) {
          (event as any).percent = event.loaded / event.total * 100; // tslint:disable-next-line:no-any
        }
        // To process the upload progress bar, you must specify the `percent` attribute to indicate progress.
        item.onProgress(event, item.file);
      } else if (event instanceof HttpResponse) { /* success */
        item.onSuccess(event.body, item.file, event);
      }
    },(err) => { /* error */
      item.onError(err, item.file);
    });
  }


问:
JQuery event for only one element of a specific class
I'm new to jQuery and can't seem to understand how to solve this problem on my own.

The issue is that when I press on one element (div) with the same class, all others also open.
Here's a gif that shows the problem. - https://gyazo.com/8315d69878d7e5efb5a699798343b278

```

```$(document).ready(() => {
    $('.items').on('click', () => {
        $('.blue-img').slideToggle();
    })
})

```

答:
The issue is because you're selecting all .blue-img elements within the click handler.

To fix this use the this keyword to refer to the clicked .items element, then find() the div within it. Try this:

$(document).ready(() => {
  $('.items').on('click', (e) => {
    $(e.target).find('.blue-img').slideToggle();
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="middle-side">
  <div class="items">
    A
    <img src="img/services/1.jpg" alt="">
    <div class="blue-img">Blue-img A</div>
  </div>
  <div class="items">
    B
    <img src="img/services/2.jpg" alt="">
    <div class="blue-img">Blue-img B</div>
  </div>
  <div class="items">
    C
    <img src="img/services/3.jpg" alt="">
    <div class="blue-img">Blue-img C</div>
  </div>
</div></code>```

Body:
I'm new to jQuery and can't seem to understand how to solve this problem on my own.

The issue is that when I press on one element (div) with the same class, all others also open.
Here's a gif that shows the problem. - https://gyazo.com/8315d69878d7e5efb5a699798343b278

$(document).ready(() => {
    $('.items').on('click', () => {
        $('.blue-img').slideToggle();
    })
})

Body:
The issue is because you're selecting all .blue-img elements within the click handler.

To fix this use the this keyword to refer to the clicked .items element, then find() the div within it. Try this:

$(document).ready(() => {
  $('.items').on('click', (e) => {
    $(e.target).find('.blue-img').slideToggle();
  })
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="middle-side">
  <div class="items">
    A
    <img src="img/services/1.jpg" alt="">
    <div class="blue-img">Blue-img A</div>
  </div>
  <div class="items">
    B
    <img src="img/services/2.jpg" alt="">
    <div class="blue-img">Blue-img B</div>
  </div>
  <div class="items">
    C
    <img src="img/services/3.jpg" alt="">
    <div class="blue-img">Blue-img C</div>
  </div>
</div>


问:
How to retrieve large amounts of data (5000+ videos) from YouTube Data API v3?
My goal is to extract all videos from a playlist which can have many videos, ~3000 and can  have more than 5000 videos. With maxResults=50 and after implementing pagination with nextPageToken, I'm only able to call the API 20 times, after which nextPageToken isn't sent with the response

I'm calling the API from a python application. I have a while loop running till nextPageToken isn't sent, ideally this should happen AFTER all the videos are extracted, but it prematurely exits after calling the API 19-20 times

def main():
    youtube = get_authorised_youtube()  # returns YouTube resource authorized with OAuth.

    first_response = make_single_request(youtube, None)  # make_single_request() takes in the youtube resource and nextPageToken, if any.
    nextPageToken = first_response["nextPageToken"]

    try:
        count = 0
        while True:
            response = make_single_request(youtube, nextPageToken)
            nextPageToken = response["nextPageToken"]

            count += 1
            print(count, end=" ")
            print(nextPageToken)
    except KeyError as e:  # KeyError to catch if nextPageToken wasn't present
        response.pop("items")
        print(response)  # prints the last response for analysis

if __name__ == '__main__':
    main()
```

<p>snippet of <code>make_single_request()</code>:</p>

<pre class="lang-py prettyprint-override"><code>def make_single_request(youtube, nextPageToken):
    if nextPageToken is None:
        request = youtube.videos().list(
            part="id",
            myRating="like",
            maxResults=50
        )
    else:
        request = youtube.videos().list(
            part="id",
            myRating="like",
            pageToken=nextPageToken,
            maxResults=50
        )
    response = request.execute()

    return response
</code>```

Expected the code to make upwards of 50 API calls but is observed to only make around 20 calls, consistently.

Note: The following code was executed with an unpaid GCP account. The calls made has part="id" which has a quota cost of 0. The calls limit according to GCP is: 10,000. According to the quota on the console, I make only 20.

Output:

```<code>1 CGQQAA
2 CJYBEAA
3 CMgBEAA
4 CPoBEAA
5 CKwCEAA
6 CN4CEAA
7 CJADEAA
8 CMIDEAA
9 CPQDEAA
10 CKYEEAA
11 CNgEEAA
12 CIoFEAA
13 CLwFEAA
14 CO4FEAA
15 CKAGEAA
16 CNIGEAA
17 CIQHEAA
18 CLYHEAA
19 {'kind': 'youtube#videoListResponse', 'etag': '"ETAG"', 'prevPageToken': 'CLYHEAE', 'pageInfo': {'totalResults': TOTAL_RESULTS(>4000), 'resultsPerPage': 50}}
</code>```

EDIT: After changing maxResults=20, It is observed that the code makes around 50 API calls, therefore the total number of videos that can be extracted is a constant at 1000.

答:
For obtaining the entire list of liked videos of a given channel without any omissions, I suggest you to use PlaylistItems endpoint instead, queried for the given channel's liked-videos playlist by passing a proper value to the endpoint's playlistId parameter.

A given channel's liked-videos playlist ID is obtained upon querying the channel's own endpoint. The needed ID is to be found at .items.contentDetails.relatedPlaylists.likes.

Body:
My goal is to extract all videos from a playlist which can have many videos, ~3000 and can  have more than 5000 videos. With maxResults=50 and after implementing pagination with nextPageToken, I'm only able to call the API 20 times, after which nextPageToken isn't sent with the response

I'm calling the API from a python application. I have a while loop running till nextPageToken isn't sent, ideally this should happen AFTER all the videos are extracted, but it prematurely exits after calling the API 19-20 times

def main():
    youtube = get_authorised_youtube()  # returns YouTube resource authorized with OAuth.

    first_response = make_single_request(youtube, None)  # make_single_request() takes in the youtube resource and nextPageToken, if any.
    nextPageToken = first_response["nextPageToken"]

    try:
        count = 0
        while True:
            response = make_single_request(youtube, nextPageToken)
            nextPageToken = response["nextPageToken"]

            count += 1
            print(count, end=" ")
            print(nextPageToken)
    except KeyError as e:  # KeyError to catch if nextPageToken wasn't present
        response.pop("items")
        print(response)  # prints the last response for analysis

if __name__ == '__main__':
    main()

snippet of make_single_request():

def make_single_request(youtube, nextPageToken):
    if nextPageToken is None:
        request = youtube.videos().list(
            part="id",
            myRating="like",
            maxResults=50
        )
    else:
        request = youtube.videos().list(
            part="id",
            myRating="like",
            pageToken=nextPageToken,
            maxResults=50
        )
    response = request.execute()

    return response

Expected the code to make upwards of 50 API calls but is observed to only make around 20 calls, consistently.

Note: The following code was executed with an unpaid GCP account. The calls made has part="id" which has a quota cost of 0. The calls limit according to GCP is: 10,000. According to the quota on the console, I make only 20.

Output:

1 CGQQAA
2 CJYBEAA
3 CMgBEAA
4 CPoBEAA
5 CKwCEAA
6 CN4CEAA
7 CJADEAA
8 CMIDEAA
9 CPQDEAA
10 CKYEEAA
11 CNgEEAA
12 CIoFEAA
13 CLwFEAA
14 CO4FEAA
15 CKAGEAA
16 CNIGEAA
17 CIQHEAA
18 CLYHEAA
19 {'kind': 'youtube#videoListResponse', 'etag': '"ETAG"', 'prevPageToken': 'CLYHEAE', 'pageInfo': {'totalResults': TOTAL_RESULTS(>4000), 'resultsPerPage': 50}}

EDIT: After changing maxResults=20, It is observed that the code makes around 50 API calls, therefore the total number of videos that can be extracted is a constant at 1000.


问:
Flexbox item does not shrink when only one item
In flexbox, if you set flex-flow: column nowrap and the elements inside have non-zero value of flex shrink, they should shrink down to all fit inside the flex container.

I have found that if you have only one item in this container and it has content bigger than the flex-container then it will not shrink down. But if other elements are included in the container (if it is not the only item) then it will shrink down.

Best visualized in this CodePen.

Here is the same code from the CodePen.

.container {
  padding: 10px;
  height: 100px;
  width: 100px;
  background: red;
  margin: 5px 20px;
  display: flex;
  flex-flow: column nowrap;
  align-items: center;
}

.item {
  width: 80px;
  height: 40px;
  background: blue;
  margin: 5px;
  /* same as
  flex: 1 1 40px;
  */
}

.super.item {
  height: 200px;
}

.item div {
  width: 10px;
  height: 150px;
  background: black;
}

body {
  margin: 0;
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'>
  </div>
</div>

<div class='container'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'>
    <div></div>
  </div>
</div>

<div class='container'>
  <div class='item super'>
  </div>
</div>

<div class='container'>
  <div class='item super'>
    <div></div>
  </div>
</div></code>```

Is there an explanation on why that last div does not shrink to fit the flex container?

答:
Very simple rule for items of a flexbox:

Items grow value is 0 and shrink is 1 and the base-case is auto.

flex: 0 1 auto

So

```<code>.item{
  width: 80px;
  height: 40px;         # will be used as base-case
  background: blue;
  margin: 5px;
  /* same as
  flex: 1 1 40px;
  */
}
</code>```

Why does second container's item shrink? Easy. base-case is 40px or on the other hand it dose not have the class .super. Add .super and see what happens.

```<code><div class='container'>
    <div class='item'></div>
    <div class='item'></div>
    <div class='item'></div>
    <div class='item'>            # flex's item height: 40px;
        <div></div>               # regular div
    </div>
</div>
</code>```

Why the third container that has the class .super does shrink? while height: 200px and it should overflow? Easy. it is the same as: flex: 0 1 200px (this is not quite right, see the comment below, what @TemaniAfif has pointed out)

try it:

```<code>.super.item{
/*   height: 200px; */
  flex: 0 1 200px;            # equal to height: 200px
}
</code>```

now try this:

```<code>.super.item{
/*   height: 200px; */
  flex: 0 0 200px;            # turn off auto grow / shrink
}
</code>```

Why the fourth overflows?. Easy. the item has a child that is a regular div

```<code><div class='container'>
  <div class='item super'>         # flex's item
    <div></div>                    # regular div
  </div>
</div>
</code>```

and the height of this div is 150px

```<code>.item div{
  width: 10px;
  height: 150px;               # remove this one, it shrinks
  background: black;
}
</code>```

Body:
In flexbox, if you set flex-flow: column nowrap and the elements inside have non-zero value of flex shrink, they should shrink down to all fit inside the flex container.

I have found that if you have only one item in this container and it has content bigger than the flex-container then it will not shrink down. But if other elements are included in the container (if it is not the only item) then it will shrink down.

Best visualized in this CodePen.

Here is the same code from the CodePen.

.container {
  padding: 10px;
  height: 100px;
  width: 100px;
  background: red;
  margin: 5px 20px;
  display: flex;
  flex-flow: column nowrap;
  align-items: center;
}

.item {
  width: 80px;
  height: 40px;
  background: blue;
  margin: 5px;
  /* same as
  flex: 1 1 40px;
  */
}

.super.item {
  height: 200px;
}

.item div {
  width: 10px;
  height: 150px;
  background: black;
}

body {
  margin: 0;
  display: flex;
}

Is there an explanation on why that last div does not shrink to fit the flex container?

Body:
Very simple rule for items of a flexbox:

Items grow value is 0 and shrink is 1 and the base-case is auto.

flex: 0 1 auto

So

.item{
  width: 80px;
  height: 40px;         # will be used as base-case
  background: blue;
  margin: 5px;
  /* same as
  flex: 1 1 40px;
  */
}

Why does second container's item shrink? Easy. base-case is 40px or on the other hand it dose not have the class .super. Add .super and see what happens.

<div class='container'>
    <div class='item'></div>
    <div class='item'></div>
    <div class='item'></div>
    <div class='item'>            # flex's item height: 40px;
        <div></div>               # regular div
    </div>
</div>

Why the third container that has the class .super does shrink? while height: 200px and it should overflow? Easy. it is the same as: flex: 0 1 200px (this is not quite right, see the comment below, what @TemaniAfif has pointed out)

try it:

.super.item{
/*   height: 200px; */
  flex: 0 1 200px;            # equal to height: 200px
}

now try this:

.super.item{
/*   height: 200px; */
  flex: 0 0 200px;            # turn off auto grow / shrink
}

Why the fourth overflows?. Easy. the item has a child that is a regular div

<div class='container'>
  <div class='item super'>         # flex's item
    <div></div>                    # regular div
  </div>
</div>

and the height of this div is 150px

.item div{
  width: 10px;
  height: 150px;               # remove this one, it shrinks
  background: black;
}


问:
Heroku app does not display Cyrillic characters with UTF-8 as default encoding
I am following this Baeldung tutorial and although the languages change correctly, whenever I try to change to a Cyrillic-based language(Bulgarian,Russian), the characters are just question marks. I am hosting my app on Heroku.

I have tried executing heroku config:add LANG=en_US.UTF-8 in the Heroku CLI but that had no effect.

This is the code for my LocaleResolver,ReloadableResourceBundleMessageSource,LocaleChangeInterceptor and the overridden addInterceptors method

```<code>    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.US);
        return slr;
    }

    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
</code>```

I expect to get "Добре дошъл"(Welcome in Bulgarian) however I just get ??????? instead.

EDIT 1
After adding the Heroku Locale Buildpack, I get the following error when I try to deploy my app to Heroku:

```<code>-----> Locale app detected
cat: /tmp/build_1406e9f58f41cacf3931deb52b55d687/.locales: No such file or
directory
!     Push rejected, failed to compile Locale app.
!     Push failed
</code>```

答:
If you have installed the locale buildpack, remove the .locales file you created and the buildpack by going to your Heroku app's settings.

I fixed the problem by applying the following settings in my application.properties file:

```<code>spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
</code>```

Also, on a side note, the first build after these settings are applied may be extra slow - if you are building in Eclipse and are used to your Heroku app building in around 1 minute, beware that this may take over 5 minutes to build.

Body:
I am following this Baeldung tutorial and although the languages change correctly, whenever I try to change to a Cyrillic-based language(Bulgarian,Russian), the characters are just question marks. I am hosting my app on Heroku.

I have tried executing heroku config:add LANG=en_US.UTF-8 in the Heroku CLI but that had no effect.

This is the code for my LocaleResolver,ReloadableResourceBundleMessageSource,LocaleChangeInterceptor and the overridden addInterceptors method

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.US);
        return slr;
    }

    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

I expect to get "Добре дошъл"(Welcome in Bulgarian) however I just get ??????? instead.

EDIT 1
After adding the Heroku Locale Buildpack, I get the following error when I try to deploy my app to Heroku:

-----> Locale app detected
cat: /tmp/build_1406e9f58f41cacf3931deb52b55d687/.locales: No such file or
directory
!     Push rejected, failed to compile Locale app.
!     Push failed

Body:
If you have installed the locale buildpack, remove the .locales file you created and the buildpack by going to your Heroku app's settings.

I fixed the problem by applying the following settings in my application.properties file:

spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true

Also, on a side note, the first build after these settings are applied may be extra slow - if you are building in Eclipse and are used to your Heroku app building in around 1 minute, beware that this may take over 5 minutes to build.


问:
Scraping each image from a craigslist search
I'm trying to pull each image url from a craigslist search, but can't seem to drill down to the URL itself.  When I try soup.find_all("a", { "class":"result-image gallery"} )[0].img, it doesn't return anything.

Specifically, the page I am trying to scrape is https://raleigh.craigslist.org/search/rea?query=duplex&sort=date&availabilityMode=0&sale_date=all+dates.

I'm trying to get the image at the following src: https://images.craigslist.org/00j0j_cC4PhAMdHLj_300x300.jpg

The super frustrating thing is that I was able to successfully do this yesterday, but didn't commit that working code to Github at the time.  I have since accidentally deleted it and can't figure out what I had originally done to make this work :(

答:
You should try automation selenium library. it allows you to scrape dynamic rendering request(js or ajax) page data.

```<code>from selenium import webdriver
from bs4 import BeautifulSoup
import time
from bs4.element import Tag

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('https://raleigh.craigslist.org/search/rea?query=duplex&sort=date&availabilityMode=0&sale_date=all+dates')
time.sleep(3)

soup = BeautifulSoup(driver.page_source,'lxml')
rowArray = soup.find_all("li", { "class":"result-row"})

for row in rowArray:
    img = row.find("img")
    if img is None:
        continue
    if isinstance(img,Tag) and img.has_attr("src"):
        print(img['src'])
        print("----------------")
</code>```

O/P:

```<code>https://images.craigslist.org/00U0U_azwRntzeNXr_300x300.jpg
----------------
https://images.craigslist.org/00101_h0xsGArMWPh_300x300.jpg
----------------
https://images.craigslist.org/00J0J_2EzptPF9ysn_300x300.jpg
----------------
https://images.craigslist.org/00101_2FiqAHsu509_300x300.jpg
----------------
https://images.craigslist.org/00D0D_jQbpUTsk6o3_300x300.jpg
</code>```

where '/usr/bin/chromedriver' selenium web driver path.

Download selenium web driver for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

https://christopher.su/2015/selenium-chromedriver-ubuntu/

Selenium tutorial:

https://selenium-python.readthedocs.io/

Body:
You should try automation selenium library. it allows you to scrape dynamic rendering request(js or ajax) page data.

from selenium import webdriver
from bs4 import BeautifulSoup
import time
from bs4.element import Tag

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('https://raleigh.craigslist.org/search/rea?query=duplex&sort=date&availabilityMode=0&sale_date=all+dates')
time.sleep(3)

soup = BeautifulSoup(driver.page_source,'lxml')
rowArray = soup.find_all("li", { "class":"result-row"})

for row in rowArray:
    img = row.find("img")
    if img is None:
        continue
    if isinstance(img,Tag) and img.has_attr("src"):
        print(img['src'])
        print("----------------")

O/P:

https://images.craigslist.org/00U0U_azwRntzeNXr_300x300.jpg
----------------
https://images.craigslist.org/00101_h0xsGArMWPh_300x300.jpg
----------------
https://images.craigslist.org/00J0J_2EzptPF9ysn_300x300.jpg
----------------
https://images.craigslist.org/00101_2FiqAHsu509_300x300.jpg
----------------
https://images.craigslist.org/00D0D_jQbpUTsk6o3_300x300.jpg

where '/usr/bin/chromedriver' selenium web driver path.

Download selenium web driver for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

https://christopher.su/2015/selenium-chromedriver-ubuntu/

Selenium tutorial:

https://selenium-python.readthedocs.io/


问:
How can I initialize a user's balance in a Substrate blockchain?
When I start my Substrate blockchain, I want to initialize users with some free balance.

How can I achieve this?

What if my chain is already running and I do not want to restart it?

答:
Genesis Configuration

The best way to set up your Substrate users with some initial free balance is to update your chain_spec.rs file such that users are given units at the genesis block of your blockchain.

This genesis configuration happens through the Balances module:

```<code>fn testnet_genesis(initial_authorities: Vec<AuthorityId>, endowed_accounts: Vec<AccountId>, root_key: AccountId) -> GenesisConfig {
    GenesisConfig {
        balances: Some(BalancesConfig {
            transaction_base_fee: 1,
            transaction_byte_fee: 0,
            existential_deposit: 500,
            transfer_fee: 0,
            creation_fee: 0,
            balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(),
            vesting: vec![],
        }),
        ...
    }
}
</code>```

Note the balances configuration here where each of the endowed_accounts are iterated, and their balance is set to 1 << 60 (which reads 1 left shift 60, which is 1152921504606846976 in decimal).

For the --dev chain, the endowed_accounts is just Alice, but you can add whatever accounts you want like this:

```<code>vec![
    account_key("Alice"),
    account_key("Bob"),
    // From public key
    sr25519::Public::from_ss58check("5GukQt4gJW2XqzFwmm3RHa7x6sYuVcGhuhz72CN7oiBsgffx").unwrap(),

]
</code>```

Where the account_key function uses the inputted string to generate an sr25519 seed.

```<code>fn account_key(s: &str) -> AccountId {
    sr25519::Pair::from_string(&format!("//{}", s), None)
        .expect("static values are valid; qed")
        .public()
}
</code>```

Sudo Module

If you already have started a blockchain and you have the Sudo module enabled, then use can also make a call to the set_balance privileged function in the Balances module.

This function will allow you to set the free and reserved balance of any account to any value.

Body:
Genesis Configuration

The best way to set up your Substrate users with some initial free balance is to update your chain_spec.rs file such that users are given units at the genesis block of your blockchain.

This genesis configuration happens through the Balances module:

fn testnet_genesis(initial_authorities: Vec<AuthorityId>, endowed_accounts: Vec<AccountId>, root_key: AccountId) -> GenesisConfig {
    GenesisConfig {
        balances: Some(BalancesConfig {
            transaction_base_fee: 1,
            transaction_byte_fee: 0,
            existential_deposit: 500,
            transfer_fee: 0,
            creation_fee: 0,
            balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(),
            vesting: vec![],
        }),
        ...
    }
}

Note the balances configuration here where each of the endowed_accounts are iterated, and their balance is set to 1 << 60 (which reads 1 left shift 60, which is 1152921504606846976 in decimal).

For the --dev chain, the endowed_accounts is just Alice, but you can add whatever accounts you want like this:

vec![
    account_key("Alice"),
    account_key("Bob"),
    // From public key
    sr25519::Public::from_ss58check("5GukQt4gJW2XqzFwmm3RHa7x6sYuVcGhuhz72CN7oiBsgffx").unwrap(),

]

Where the account_key function uses the inputted string to generate an sr25519 seed.

fn account_key(s: &str) -> AccountId {
    sr25519::Pair::from_string(&format!("//{}", s), None)
        .expect("static values are valid; qed")
        .public()
}

Sudo Module

If you already have started a blockchain and you have the Sudo module enabled, then use can also make a call to the set_balance privileged function in the Balances module.

This function will allow you to set the free and reserved balance of any account to any value.


问:
openpyxl set nunmber format to cell but doesn't work
I want to create an excel by reading data from the csv files.
So, I use Openpyxl and CSV in python.
However, no matter number_format I put in the code the cell value from the csv remain in 'text' format

```<code>from openpyxl import load_workbook
import csv
from openpyxl.styles import numbers

ws= load_workbook('myworkbook.xlsx')
with open("myfile.csv", "r", newline="", encoding="utf16") as f:
    mydata=csv.reader(f,delimiter='|')
    for row in mydata:
        for col_index,col_data in enumerate(row,3):
            ws.cell(row=new800row_count, column=col_index, value=col_data).number_format = numbers.FORMAT_NUMBER
</code>```

let's say my csv file contains 800, 200, 100 data value.
After using my  code above. Instead of showing 800, 200, 100 in number format (excel) it's told me that this cell contain number stored as text even the actual excel format told me that it's a number

Thank you for any help in advance.

答:
Loop through your data set, convert the data if its a string to float:

```<code>str = '1234.0'
data = float(str)
row[col] = data
row[col].number_format = '#,##0.00'
</code>```

The last line of code ensures its formatted as a number. don't forget to save the file after making the above changes.

Body:
I want to create an excel by reading data from the csv files.
So, I use Openpyxl and CSV in python.
However, no matter number_format I put in the code the cell value from the csv remain in 'text' format

from openpyxl import load_workbook
import csv
from openpyxl.styles import numbers

ws= load_workbook('myworkbook.xlsx')
with open("myfile.csv", "r", newline="", encoding="utf16") as f:
    mydata=csv.reader(f,delimiter='|')
    for row in mydata:
        for col_index,col_data in enumerate(row,3):
            ws.cell(row=new800row_count, column=col_index, value=col_data).number_format = numbers.FORMAT_NUMBER

let's say my csv file contains 800, 200, 100 data value.
After using my  code above. Instead of showing 800, 200, 100 in number format (excel) it's told me that this cell contain number stored as text even the actual excel format told me that it's a number

Thank you for any help in advance.

Body:
Loop through your data set, convert the data if its a string to float:

str = '1234.0'
data = float(str)
row[col] = data
row[col].number_format = '#,##0.00'

The last line of code ensures its formatted as a number. don't forget to save the file after making the above changes.


问:
CreateProcess error=206, The filename or extension is too long when running main() method
I have this error in eclipse helios:

Exception occurred executing command line.
Cannot run program "C:\Program Files (x86)\Java\jre6\bin\javaw.exe" (in directory "C:\Users\motiver\helios_workspace\TimeTracker"): CreateProcess error=206, The filename or extension is too long

I researched a bit but most of the issues were related to DataNucleus when working on Google App Engine. But I am not using anything remotely related to Google App Engine. I am doing a small project with Servlet 3.0 on JBOSS 6. I am using Hibernate 4.1.2 for ORM and RESTEasy to expose a web service. I created a util file that has a main() method that basically drops and re-creates the schema. I run the main() methos when I need a clean database for testing purposes. It worked fine on Tomcat 7 but it stopped working when I moved to JBoss 6.

Any hint or solution would be greatly appreciated.

答:
To solve it:

If you are using Eclipse:

Move .m2 repository to

c:\
Go to Eclipse > Windows/Preferences/Maven/User Settings -> Create your own setting.xml with its content:

```<code><settings>
  <localRepository>c:/.m2/repository</localRepository>
</settings>
</code>```

If you are using IntelliJ:
Go to IntelliJ >  clicking the right mouse button on "pom.xml" > maven > create "settings.xml"

with its content:

```<code><settings>
      xmlns="yourcontent"
      xmlns:xsi="yourcontent"
      xsi:schemaLocation="yourcontent.xsd">
  <localRepository>c:/.m2/repository</localRepository>
</settings>
</code>```

Body:
To solve it:

If you are using Eclipse:

Move .m2 repository to

c:\
Go to Eclipse > Windows/Preferences/Maven/User Settings -> Create your own setting.xml with its content:

<settings>
  <localRepository>c:/.m2/repository</localRepository>
</settings>

If you are using IntelliJ:
Go to IntelliJ >  clicking the right mouse button on "pom.xml" > maven > create "settings.xml"

with its content:

<settings>
      xmlns="yourcontent"
      xmlns:xsi="yourcontent"
      xsi:schemaLocation="yourcontent.xsd">
  <localRepository>c:/.m2/repository</localRepository>
</settings>