问:
EF Core 2.0.0 Query Filter is Caching TenantId (Updated for 2.0.1+)
I'm building a multi-tenant application, and am running into difficulties with what I think is EF Core caching the tenant id across requests. The only thing that seems to help is constantly rebuilding the application as I sign in and out of tenants.

I thought it may have something to do with the IHttpContextAccessor instance being a singleton, but it can't be scoped, and when I sign in and out without rebuilding I can see the tenant's name change at the top of the page, so it's not the issue.

The only other thing I can think of is that EF Core is doing some sort of query caching. I'm not sure why it would be considering that it's a scoped instance and it should be getting rebuild on every request, unless I'm wrong, which I probably am. I was hoping it would behave like a scoped instance so I could simply inject the tenant id at model build time on each instance.

I'd really appreciate it if someone could point me in the right direction. Here's my current code:

TenantProvider.cs

```<code>public sealed class TenantProvider :
    ITenantProvider {
    private readonly IHttpContextAccessor _accessor;

    public TenantProvider(
        IHttpContextAccessor accessor) {
        _accessor = accessor;
    }

    public int GetId() {
        return _accessor.HttpContext.User.GetTenantId();
    }
}
</code>```

...which is injected into TenantEntityConfigurationBase.cs where I use it to setup a global query filter.

```<code>internal abstract class TenantEntityConfigurationBase<TEntity, TKey> :
    EntityConfigurationBase<TEntity, TKey>
    where TEntity : TenantEntityBase<TKey>
    where TKey : IEquatable<TKey> {
    protected readonly ITenantProvider TenantProvider;

    protected TenantEntityConfigurationBase(
        string table,
        string schema,
        ITenantProvider tenantProvider) :
        base(table, schema) {
        TenantProvider = tenantProvider;
    }

    protected override void ConfigureFilters(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureFilters(builder);

        builder.HasQueryFilter(
            e => e.TenantId == TenantProvider.GetId());
    }

    protected override void ConfigureRelationships(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureRelationships(builder);

        builder.HasOne(
            t => t.Tenant).WithMany().HasForeignKey(
            k => k.TenantId);
    }
}
</code>```

...which is then inherited by all other tenant entity configurations. Unfortunately it doesn't seem to work as I had planned.

I have verified that the tenant id being returned by the user principal is changing depending on what tenant user is logged in, so that's not the issue. Thanks in advance for any help!

Update

For a solution when using EF Core 2.0.1+, look at the not-accepted answer from me.

Update 2

Also look at Ivan's update for 2.0.1+, it proxies in the filter expression from the DbContext which restores the ability to define it once in a base configuration class. Both solutions have their pros and cons. I've opted for Ivan's again because I just want to leverage my base configurations as much as possible.

答:
Currently (as of EF Core 2.0.0) the dynamic global query filtering is quite limited. It works only if the dynamic part is provided by direct property of the target  DbContext derived class (or one of its base DbContext derived classes). Exactly as in the Model-level query filters example from the documentation. Exactly that way - no method calls, no nested property accessors - just property of the context. It's sort of explained in the link:

Note the use of a DbContext instance level property: TenantId. Model-level filters will use the value from the correct context instance. i.e. the one that is executing the query.

To make it work in your scenario, you have to create a base class like this:

```<code>public abstract class TenantDbContext : DbContext
{
    protected ITenantProvider TenantProvider;
    internal int TenantId => TenantProvider.GetId();
}
</code>```

derive your context class from it and somehow inject the TenantProvider instance into it. Then modify the TenantEntityConfigurationBase class to receive TenantDbContext:

```<code>internal abstract class TenantEntityConfigurationBase<TEntity, TKey> :
    EntityConfigurationBase<TEntity, TKey>
    where TEntity : TenantEntityBase<TKey>
    where TKey : IEquatable<TKey> {
    protected readonly TenantDbContext Context;

    protected TenantEntityConfigurationBase(
        string table,
        string schema,
        TenantDbContext context) :
        base(table, schema) {
        Context = context;
    }

    protected override void ConfigureFilters(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureFilters(builder);

        builder.HasQueryFilter(
            e => e.TenantId == Context.TenantId);
    }

    protected override void ConfigureRelationships(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureRelationships(builder);

        builder.HasOne(
            t => t.Tenant).WithMany().HasForeignKey(
            k => k.TenantId);
    }
}
</code>```

and everything will work as expected. And remember, the Context variable type must be a DbContext derived class - replacing it with interface won't work.

Update for 2.0.1: As @Smit pointed out in the comments, v2.0.1 removed most of the limitations - now you can use methods and sub properties.

However, it introduced another requirement - the dynamic expression must be rooted at the DbContext.

This requirement breaks the above solution, since the expression root is TenantEntityConfigurationBase<TEntity, TKey> class, and it's not so easy to create such expression outside the DbContext due to lack of compile time support for generating constant expressions.

It could be solved with some low level expression manipulation methods, but the easier in your case would be to move the filter creation in generic instance method of the TenantDbContext and call it from the entity configuration class.

Here are the modifications:

TenantDbContext class:

```<code>internal Expression<Func<TEntity, bool>> CreateFilter<TEntity, TKey>()
    where TEntity : TenantEntityBase<TKey>
    where TKey : IEquatable<TKey>
{
    return e => e.TenantId == TenantId;
}
</code>```

TenantEntityConfigurationBase<TEntity, TKey> class:

```<code>builder.HasQueryFilter(Context.CreateFilter<TEntity, TKey>());
</code>```

Body:
I'm building a multi-tenant application, and am running into difficulties with what I think is EF Core caching the tenant id across requests. The only thing that seems to help is constantly rebuilding the application as I sign in and out of tenants.

I thought it may have something to do with the IHttpContextAccessor instance being a singleton, but it can't be scoped, and when I sign in and out without rebuilding I can see the tenant's name change at the top of the page, so it's not the issue.

The only other thing I can think of is that EF Core is doing some sort of query caching. I'm not sure why it would be considering that it's a scoped instance and it should be getting rebuild on every request, unless I'm wrong, which I probably am. I was hoping it would behave like a scoped instance so I could simply inject the tenant id at model build time on each instance.

I'd really appreciate it if someone could point me in the right direction. Here's my current code:

TenantProvider.cs

public sealed class TenantProvider :
    ITenantProvider {
    private readonly IHttpContextAccessor _accessor;

    public TenantProvider(
        IHttpContextAccessor accessor) {
        _accessor = accessor;
    }

    public int GetId() {
        return _accessor.HttpContext.User.GetTenantId();
    }
}

...which is injected into TenantEntityConfigurationBase.cs where I use it to setup a global query filter.

internal abstract class TenantEntityConfigurationBase<TEntity, TKey> :
    EntityConfigurationBase<TEntity, TKey>
    where TEntity : TenantEntityBase<TKey>
    where TKey : IEquatable<TKey> {
    protected readonly ITenantProvider TenantProvider;

    protected TenantEntityConfigurationBase(
        string table,
        string schema,
        ITenantProvider tenantProvider) :
        base(table, schema) {
        TenantProvider = tenantProvider;
    }

    protected override void ConfigureFilters(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureFilters(builder);

        builder.HasQueryFilter(
            e => e.TenantId == TenantProvider.GetId());
    }

    protected override void ConfigureRelationships(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureRelationships(builder);

        builder.HasOne(
            t => t.Tenant).WithMany().HasForeignKey(
            k => k.TenantId);
    }
}

...which is then inherited by all other tenant entity configurations. Unfortunately it doesn't seem to work as I had planned.

I have verified that the tenant id being returned by the user principal is changing depending on what tenant user is logged in, so that's not the issue. Thanks in advance for any help!

Update

For a solution when using EF Core 2.0.1+, look at the not-accepted answer from me.

Update 2

Also look at Ivan's update for 2.0.1+, it proxies in the filter expression from the DbContext which restores the ability to define it once in a base configuration class. Both solutions have their pros and cons. I've opted for Ivan's again because I just want to leverage my base configurations as much as possible.

Body:
Currently (as of EF Core 2.0.0) the dynamic global query filtering is quite limited. It works only if the dynamic part is provided by direct property of the target  DbContext derived class (or one of its base DbContext derived classes). Exactly as in the Model-level query filters example from the documentation. Exactly that way - no method calls, no nested property accessors - just property of the context. It's sort of explained in the link:

Note the use of a DbContext instance level property: TenantId. Model-level filters will use the value from the correct context instance. i.e. the one that is executing the query.

To make it work in your scenario, you have to create a base class like this:

public abstract class TenantDbContext : DbContext
{
    protected ITenantProvider TenantProvider;
    internal int TenantId => TenantProvider.GetId();
}

derive your context class from it and somehow inject the TenantProvider instance into it. Then modify the TenantEntityConfigurationBase class to receive TenantDbContext:

internal abstract class TenantEntityConfigurationBase<TEntity, TKey> :
    EntityConfigurationBase<TEntity, TKey>
    where TEntity : TenantEntityBase<TKey>
    where TKey : IEquatable<TKey> {
    protected readonly TenantDbContext Context;

    protected TenantEntityConfigurationBase(
        string table,
        string schema,
        TenantDbContext context) :
        base(table, schema) {
        Context = context;
    }

    protected override void ConfigureFilters(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureFilters(builder);

        builder.HasQueryFilter(
            e => e.TenantId == Context.TenantId);
    }

    protected override void ConfigureRelationships(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureRelationships(builder);

        builder.HasOne(
            t => t.Tenant).WithMany().HasForeignKey(
            k => k.TenantId);
    }
}

and everything will work as expected. And remember, the Context variable type must be a DbContext derived class - replacing it with interface won't work.

Update for 2.0.1: As @Smit pointed out in the comments, v2.0.1 removed most of the limitations - now you can use methods and sub properties.

However, it introduced another requirement - the dynamic expression must be rooted at the DbContext.

This requirement breaks the above solution, since the expression root is TenantEntityConfigurationBase<TEntity, TKey> class, and it's not so easy to create such expression outside the DbContext due to lack of compile time support for generating constant expressions.

It could be solved with some low level expression manipulation methods, but the easier in your case would be to move the filter creation in generic instance method of the TenantDbContext and call it from the entity configuration class.

Here are the modifications:

TenantDbContext class:

internal Expression<Func<TEntity, bool>> CreateFilter<TEntity, TKey>()
    where TEntity : TenantEntityBase<TKey>
    where TKey : IEquatable<TKey>
{
    return e => e.TenantId == TenantId;
}

TenantEntityConfigurationBase<TEntity, TKey> class:

builder.HasQueryFilter(Context.CreateFilter<TEntity, TKey>());


来源: stackexchange

问:
Is there an example of how to customize a .NET 4.0 profiler?
I know there is one for profiler 2.0: http://www.codeproject.com/KB/dotnet/dotnetprofiler.aspx
But the profiler API has changed in .NET 4.0 and we need to consider in-process side by side issues. I need an example to customize our own profiler. Anyone knows that? Thanks!</p>

答:
I don't have an actual example, but this post is exactly about your question. Also check out the rest of his blog, there are more posts about 4.0 profilers (and profilers in general).

By the way, in the comments section of the linked blog post he says the official 4.0 profiler source is not ready, but when it is he'll post about it. (Though this was 4 months ago or something.)

Edit: CLRProfiler 4.0 just got released and includes source code, so you got your sample ;-)

ContentLicense: CC BY-SA 2.5


问:
Grails createCriteria() used inside Domain classes
Just got to know about the capability of createCriteria() method. Just wanna know that other than applying it on the Controller, is there a way to apply onto the domain classes as well? Probably on its own mapping to a property like:</p>

```<code>static mapping = {
      additionalInfo: Page.createCriteria().list()
}
</code>```

答:
Perhaps you may want to simply create a new field based the target field like the below example:

```<code>class myInfo {
    String additionalInfo
    String[] moreInfo  // a transient field

    getMoreInfo(){
        def myresultmap = createCriteria.list{
         // insert any other criteria shenanigans
        }
        return myresultmap
    }
    static transients = ['moreInfo']
}
</code>```

In a controller return a view like normal with the Domain instance of class MyInfo
Then use in view like:

```<code><g:each in="${domaininstancefromcontroller}">
${it.moreInfo[0]
</g:each>
</code>```

see docs.
Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
Just got to know about the capability of createCriteria() method. Just wanna know that other than applying it on the Controller, is there a way to apply onto the domain classes as well? Probably on its own mapping to a property like:

static mapping = {
      additionalInfo: Page.createCriteria().list()
}

Body:
Perhaps you may want to simply create a new field based the target field like the below example:

class myInfo {
    String additionalInfo
    String[] moreInfo  // a transient field

    getMoreInfo(){
        def myresultmap = createCriteria.list{
         // insert any other criteria shenanigans
        }
        return myresultmap
    }
    static transients = ['moreInfo']
}

In a controller return a view like normal with the Domain instance of class MyInfo
Then use in view like:

<g:each in="${domaininstancefromcontroller}">
${it.moreInfo[0]
</g:each>

see docs.
Hope this helps.


问:
Game view is slower than build - unity 2017.2.0f3
I am creating a sample 2D Unity tutorial.
If I run the game using play mode in the UnityEditor, the game seems very slow, and skips some frames. The standalone version runs smooth.

Did I configure something wrong?

答:
Thats normal.

When you compare the FPS from UnityPlayer to Standalone, you will see that the Standalone application will perform alot better.

Here is a article, which describes the speed differences


问:
How to convert chr(0xdfff) to utf-8 bytes in Python 3 as in Python 2?
The code below explains my problem. It works as expected in Python 2.7, yet, all of the encode calls I've tried fail in Python 3.5 (see exception below)... does anyone on a way to circumvent this error and make it work in Python 3.5 as it did on Python 2.7?

```<code>import sys

if sys.version_info[0] <= 2:
    chr = unichr

out = chr(0xdfff)
print(repr(out)) # outputs '\udfff' both in Python 2 and 3
assert out.encode('utf-8').decode('utf-8') == out
assert out.encode('utf-8', errors='surrogateescape').decode('utf-8') == out
assert out.encode('utf-8', errors='strict').decode('utf-8') == out
</code>```

Error in Python 3.5:

```<code>Traceback (most recent call last):
  File "W:\rocky40\Projects\etk\coilib50\source\python\coilib50\io\xmlpickle\snippet.py", line 8, in <module>
    assert out.encode('utf-8').decode('utf-8') == out
UnicodeEncodeError: 'utf-8' codec can't encode character '\udfff' in position 0: surrogates not allowed
</code>```

Note that a different encoding wouldn't really suit it as I have files written this way to disk in Python 2 and I need to be able to load it back and dump it again on Python 3 so that Python 2 can read it again (so, the actual bytes written shouldn't really change).

答:
The problem is that char belongs to utf-16:

```<code>import sys

if sys.version_info[0] <= 2:
    chr = unichr

out = chr(0xdfff)

print(out.encode('utf-16-le', 'ignore').decode('utf-16-le', 'ignore') == out)
print(out.encode('utf-16-le', 'ignore').decode('utf-16-le', 'ignore') == out)
print(out.encode('utf-16-le', 'ignore').decode('utf-16-le', 'ignore') == out)
</code>```

That compiles and works, but... acording to this answer, you will have problems with surrogates

Body:
The code below explains my problem. It works as expected in Python 2.7, yet, all of the encode calls I've tried fail in Python 3.5 (see exception below)... does anyone on a way to circumvent this error and make it work in Python 3.5 as it did on Python 2.7?

import sys

if sys.version_info[0] <= 2:
    chr = unichr

out = chr(0xdfff)
print(repr(out)) # outputs '\udfff' both in Python 2 and 3
assert out.encode('utf-8').decode('utf-8') == out
assert out.encode('utf-8', errors='surrogateescape').decode('utf-8') == out
assert out.encode('utf-8', errors='strict').decode('utf-8') == out

Error in Python 3.5:

Traceback (most recent call last):
  File "W:\rocky40\Projects\etk\coilib50\source\python\coilib50\io\xmlpickle\snippet.py", line 8, in <module>
    assert out.encode('utf-8').decode('utf-8') == out
UnicodeEncodeError: 'utf-8' codec can't encode character '\udfff' in position 0: surrogates not allowed

Note that a different encoding wouldn't really suit it as I have files written this way to disk in Python 2 and I need to be able to load it back and dump it again on Python 3 so that Python 2 can read it again (so, the actual bytes written shouldn't really change).

Body:
The problem is that char belongs to utf-16:

import sys

if sys.version_info[0] <= 2:
    chr = unichr

out = chr(0xdfff)

print(out.encode('utf-16-le', 'ignore').decode('utf-16-le', 'ignore') == out)
print(out.encode('utf-16-le', 'ignore').decode('utf-16-le', 'ignore') == out)
print(out.encode('utf-16-le', 'ignore').decode('utf-16-le', 'ignore') == out)

That compiles and works, but... acording to this answer, you will have problems with surrogates


问:
Accessing DependencyProperty: The calling thread cannot access this object because a different thread owns it
I would like to load data into my WPF DataGrid when a DependencyProperty value changes. I thought something as simple as this would work but it does not;

```<code>public SQLiteDb.Attorney attorney
{
    get { return (SQLiteDb.Attorney)GetValue(attorneyProperty); }
    set {
        SetValue(attorneyProperty, value);
        GetAttorneysIdentitiesAsync(); //Load the data here.
    }
}
public static readonly DependencyProperty attorneyProperty =
    DependencyProperty.Register("attorney", typeof(SQLiteDb.Attorney),
      typeof(AttorneyDetails), new PropertyMetadata(new SQLiteDb.Attorney()));
</code>```

But I end up getting thread exceptions which I have very little experience about. The method GetAttorneysIdentitiesAsync looks like this which I guess is trying to access the property value from another thread.

```<code>public async void GetAttorneysIdentitiesAsync()
{
    AlternativeIdentities = await SQLiteDb.db.Table<SQLiteDb.AttorneyIdentity>().Where(x => x.AttorneyId == attorney.Id).ThenBy(x => x.Id).Take(30).ToListAsync();
    AlternativeIdentitiesGrid.ItemsSource = AlternativeIdentities;
}
</code>```

I get the exception whenever I try to access the property from within the property class.

```<code>The calling thread cannot access this object because a different thread owns it.
</code>```

答:
You should access the attorny property outside a Task thread:

```<code>public async Task GetAttorneysIdentitiesAsync()
{
    var id = attorney.Id;

    AlternativeIdentities = await SQLiteDb.db.Table<SQLiteDb.AttorneyIdentity>()
        .Where(x => x.AttorneyId == id)
        .ThenBy(x => x.Id)
        .Take(30)
        .ToListAsync();

    AlternativeIdentitiesGrid.ItemsSource = AlternativeIdentities;
}
</code>```

Note also that you should not call anything else than GetValue and SetValue in the CLR wrapper of a dependency property. The reason is explained here.

You should register a PropertyChangedCallback like this:

```<code>public SQLiteDb.Attorney attorney
{
    get { return (SQLiteDb.Attorney)GetValue(attorneyProperty); }
    set { SetValue(attorneyProperty, value); }
}

public static readonly DependencyProperty attorneyProperty = DependencyProperty.Register(
    nameof(attorney), typeof(SQLiteDb.Attorney), typeof(AttorneyDetails),
    new PropertyMetadata(new SQLiteDb.Attorney(), attorneyPropertyChanged));

private static async void attorneyPropertyChanged(
    DependencyObject o, DependencyPropertyChangedEventArgs e)
{
    await ((AttorneyDetails)o).GetAttorneysIdentitiesAsync();
}
</code>```

Body:
I would like to load data into my WPF DataGrid when a DependencyProperty value changes. I thought something as simple as this would work but it does not;

public SQLiteDb.Attorney attorney
{
    get { return (SQLiteDb.Attorney)GetValue(attorneyProperty); }
    set {
        SetValue(attorneyProperty, value);
        GetAttorneysIdentitiesAsync(); //Load the data here.
    }
}
public static readonly DependencyProperty attorneyProperty =
    DependencyProperty.Register("attorney", typeof(SQLiteDb.Attorney),
      typeof(AttorneyDetails), new PropertyMetadata(new SQLiteDb.Attorney()));

But I end up getting thread exceptions which I have very little experience about. The method GetAttorneysIdentitiesAsync looks like this which I guess is trying to access the property value from another thread.

public async void GetAttorneysIdentitiesAsync()
{
    AlternativeIdentities = await SQLiteDb.db.Table<SQLiteDb.AttorneyIdentity>().Where(x => x.AttorneyId == attorney.Id).ThenBy(x => x.Id).Take(30).ToListAsync();
    AlternativeIdentitiesGrid.ItemsSource = AlternativeIdentities;
}

I get the exception whenever I try to access the property from within the property class.

The calling thread cannot access this object because a different thread owns it.

Body:
You should access the attorny property outside a Task thread:

public async Task GetAttorneysIdentitiesAsync()
{
    var id = attorney.Id;

    AlternativeIdentities = await SQLiteDb.db.Table<SQLiteDb.AttorneyIdentity>()
        .Where(x => x.AttorneyId == id)
        .ThenBy(x => x.Id)
        .Take(30)
        .ToListAsync();

    AlternativeIdentitiesGrid.ItemsSource = AlternativeIdentities;
}

Note also that you should not call anything else than GetValue and SetValue in the CLR wrapper of a dependency property. The reason is explained here.

You should register a PropertyChangedCallback like this:

public SQLiteDb.Attorney attorney
{
    get { return (SQLiteDb.Attorney)GetValue(attorneyProperty); }
    set { SetValue(attorneyProperty, value); }
}

public static readonly DependencyProperty attorneyProperty = DependencyProperty.Register(
    nameof(attorney), typeof(SQLiteDb.Attorney), typeof(AttorneyDetails),
    new PropertyMetadata(new SQLiteDb.Attorney(), attorneyPropertyChanged));

private static async void attorneyPropertyChanged(
    DependencyObject o, DependencyPropertyChangedEventArgs e)
{
    await ((AttorneyDetails)o).GetAttorneysIdentitiesAsync();
}


问:
Having a custom fmap traversing until non Functor type is found
In my learning curve of Haskell, I am wondering if it possible to implement a custom fmap function, fmap' , that would "apply" until a non Functor is found.

For example; with fmap , one has to write

```<code>fmap (fmap (*2)) [[1,2] , [ 3,4 ,5]]
[[2,4],[6,8,10]]
</code>```

or

```<code>fmap (fmap (*2)) [Just 1, Just 2]
[Just 2,Just 4]
</code>```

The idea is to write

```<code>fmap' (*2) [[1,2] , [3,4,5]]
fmap' (*2) [Just 1 , Just 2]
</code>```

to get the same result as above.

My current understanding is that it is not possible because fmap' and fmap do not have the same signature as

```<code>:t fmap (fmap)
fmap (fmap)
  :: (Functor f2, Functor f1) => f1 (a -> b) -> f1 (f2 a -> f2 b)
</code>```

答:
You are looking for a function:

```<code>rfmap :: (a -> b) -> F a -> F b
</code>```

where F is some arbitrary "context" of a, which may be quite sophisticated.  E.g. one specialization would be:

```<code>rfmap :: (a -> b) -> Maybe (Int -> Either Bool a) -> Maybe (Int -> Either Bool b)
</code>```

We need the typechecker to figure out that F = Maybe (Int -> Either Bool _).  This is not as easy as fmap, whose argument is a type constructor applied to a variable

```<code>fmap :: (a -> b) -> Compose Maybe (Either Bool) a -> Compose Maybe (Either Bool) b
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^      ^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

and is easily found, because type constructors are injective.

rfmap needs to deal with some tricky ambiguities. Consider:

```<code>rfmap id (Just [42])
</code>```

Which specialization should we choose?

```<code>rfmap :: (Int -> Int) -> Maybe [Int] -> Maybe [Int]
rfmap :: ([Int] -> [Int]) -> Maybe [Int] -> Maybe [Int]
rfmap :: (Maybe [Int] -> Maybe [Int]) -> Maybe [Int] -> Maybe [Int]
</code>```

That is, do we consider the functor Maybe _ or Maybe (Int -> _), or even the identity functor _?  You probably want to say "as deep as possible", but alas, that interferes with polymorphism:

```<code>f :: a -> Maybe a
f x = rfmap id (Just x)
</code>```

You probably want this to just be one fmap, because going deeper doesn't typecheck. However if we pass f [42] then it's the same as the expression above which goes down two by the "as deep as possible" rule -- so this is something like like a violation of referential transparency (I wouldn't consider it a full violation because there is hidden type-directed information that might differ).

Nevermind that there might be a Num instance for a functor, e.g. Num a => Num (Vector a), which would mean that [42] is actually more than two levels deep.

So there are a lot of hard questions that make something like rfmap unlikely to have a well-behaved implementation.

As usual, if you give up polymorphism (which is a terrible idea), you can hack something together with typeclasses.  It also has some other problems.

I would recommend against expecting any solution to be usable.  It's the kind of thing that's not very compatible with Haskell's type system.

As far as alternatives:

If you are writing a single instance and just annoyed with all the fmaps, look at semantic editor combinators for a nice way to think about it.

If you are making abstractions (in the sense of a type w/ operations) which are just nested functors and annoyed by the tedious reimplementation of fmap = fmap.fmap.fmap, then using Compose is the way to go.

Body:
In my learning curve of Haskell, I am wondering if it possible to implement a custom fmap function, fmap' , that would "apply" until a non Functor is found.

For example; with fmap , one has to write

fmap (fmap (*2)) [[1,2] , [ 3,4 ,5]]
[[2,4],[6,8,10]]

or

fmap (fmap (*2)) [Just 1, Just 2]
[Just 2,Just 4]

The idea is to write

fmap' (*2) [[1,2] , [3,4,5]]
fmap' (*2) [Just 1 , Just 2]

to get the same result as above.

My current understanding is that it is not possible because fmap' and fmap do not have the same signature as

:t fmap (fmap)
fmap (fmap)
  :: (Functor f2, Functor f1) => f1 (a -> b) -> f1 (f2 a -> f2 b)

Body:
You are looking for a function:

rfmap :: (a -> b) -> F a -> F b

where F is some arbitrary "context" of a, which may be quite sophisticated.  E.g. one specialization would be:

rfmap :: (a -> b) -> Maybe (Int -> Either Bool a) -> Maybe (Int -> Either Bool b)

We need the typechecker to figure out that F = Maybe (Int -> Either Bool _).  This is not as easy as fmap, whose argument is a type constructor applied to a variable

fmap :: (a -> b) -> Compose Maybe (Either Bool) a -> Compose Maybe (Either Bool) b
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^      ^^^^^^^^^^^^^^^^^^^^^^^^^^^

and is easily found, because type constructors are injective.

rfmap needs to deal with some tricky ambiguities. Consider:

rfmap id (Just [42])

Which specialization should we choose?

rfmap :: (Int -> Int) -> Maybe [Int] -> Maybe [Int]
rfmap :: ([Int] -> [Int]) -> Maybe [Int] -> Maybe [Int]
rfmap :: (Maybe [Int] -> Maybe [Int]) -> Maybe [Int] -> Maybe [Int]

That is, do we consider the functor Maybe _ or Maybe (Int -> _), or even the identity functor _?  You probably want to say "as deep as possible", but alas, that interferes with polymorphism:

f :: a -> Maybe a
f x = rfmap id (Just x)

You probably want this to just be one fmap, because going deeper doesn't typecheck. However if we pass f [42] then it's the same as the expression above which goes down two by the "as deep as possible" rule -- so this is something like like a violation of referential transparency (I wouldn't consider it a full violation because there is hidden type-directed information that might differ).

Nevermind that there might be a Num instance for a functor, e.g. Num a => Num (Vector a), which would mean that [42] is actually more than two levels deep.

So there are a lot of hard questions that make something like rfmap unlikely to have a well-behaved implementation.

As usual, if you give up polymorphism (which is a terrible idea), you can hack something together with typeclasses.  It also has some other problems.

I would recommend against expecting any solution to be usable.  It's the kind of thing that's not very compatible with Haskell's type system.

As far as alternatives:

If you are writing a single instance and just annoyed with all the fmaps, look at semantic editor combinators for a nice way to think about it.

If you are making abstractions (in the sense of a type w/ operations) which are just nested functors and annoyed by the tedious reimplementation of fmap = fmap.fmap.fmap, then using Compose is the way to go.


问:
How can I count number of commits between two branches?
Using the git diff --shortstat my_branch master is a great way to tell how many files changes and the insertions and deletions. I read the git diff documentation, but I couldn't find a way to tell the number of commits between my_branch and master. Does that exist?

答:
This gives me the number of commits I've made to branch_being_merged_in since branching from branch_A:

git log --pretty=%H branch_A..branch_being_merged_in | wc -l


问:
html button, the value="submit" is not showing up?
I am looking for the value="submit" to show up in the middle of the button.  I am not seeing any text, not sure why?    </p>

```<code><button type="button" class="button btn_big_blue" value="Submit"></button>

.button{
    display: block;
    width: 137px;
    height:    44px;
    text-align:center;
    line-height: 40px;
    font-size: 18px;
    font-weight: bold;
    text-decoration: none;
    color:#fff;
    border:none;
    cursor: pointer;
}

.button.btn_big_blue {
    background: url(/img/btn_big_blue.png) no-repeat;
    color: #fff;
}
</code>```

答:
value is the value transmitted when submitting/sending the form.

you want to put your content between the button tags:

```<code> <button class="button …">Submit</button>
</code>```

ps. the class button seems pretty useless, because you can style the button directly

Body:
I am looking for the value="submit" to show up in the middle of the button.  I am not seeing any text, not sure why?

<button type="button" class="button btn_big_blue" value="Submit"></button>

.button{
    display: block;
    width: 137px;
    height:    44px;
    text-align:center;
    line-height: 40px;
    font-size: 18px;
    font-weight: bold;
    text-decoration: none;
    color:#fff;
    border:none;
    cursor: pointer;
}

.button.btn_big_blue {
    background: url(/img/btn_big_blue.png) no-repeat;
    color: #fff;
}

Body:
value is the value transmitted when submitting/sending the form.

you want to put your content between the button tags:

 <button class="button …">Submit</button>

ps. the class button seems pretty useless, because you can style the button directly


问:
Django - Cannot assign "'Biography test'": "User.biography" must be a "Biography" instance
I have extended the user model with an extra field - biography. It appears in the admin panel as a new section.  Here's a picture:

Here's the new model:

```<code>class Biography(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    biography = models.TextField(max_length=500, blank=True)
</code>```

Here's the profile view:

```<code>def profile(request, username):
    user = get_object_or_404(User, username=username)
    products = Product.objects.filter(user=user)
    if not request.user == user:
        return render(request, 'no.html')
    else:
        return render(request, 'profile.html', {'user':user,'products': products})
</code>```

I'm using a form to edit the profile - here's the view:

```<code>def edit_profile(request):
    user = request.user
    products = Product.objects.filter(user=user)
    form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name, 'biography':user.biography})
    if request.method == 'POST':
        if form.is_valid():
            user.first_name = request.POST['first_name']
            user.last_name = request.POST['last_name']
            user.biography = request.POST['biography']
            user.save()
            return render(request, 'profile.html', {'user':user, 'products':products})
    context = {"form": form}
    return render(request, "edit_profile.html", context)
</code>```

...and here's the form:

```<code>class EditProfileForm(forms.Form):
    first_name = forms.CharField(label='First Name')
    last_name = forms.CharField(label='Last Name')
    biography = forms.CharField(label='Biography', widget=Textarea(attrs={'rows': 5}))
</code>```

Here's a screenshot of the error message:

I'm mixing something up but I can't figure out what. Doesn't help that I'm new to this ...still trying!

答:
As the error message says:

```<code>"User.Biography" must be a "Biography" instance.
</code>```

In your edit_profile definition, you have the following assignment:

```<code>user.biography = request.POST['biography']
</code>```

request.POST['biography'] is not a valid instance of Biography. So, you have to create a valid Biography instance, according to your Biography model, with the request.POST['biography'].

After that, you can assign your valid instance to user.biography.

I hope it had been useful for you.

Body:
I have extended the user model with an extra field - biography. It appears in the admin panel as a new section.  Here's a picture:

Here's the new model:

class Biography(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    biography = models.TextField(max_length=500, blank=True)

Here's the profile view:

def profile(request, username):
    user = get_object_or_404(User, username=username)
    products = Product.objects.filter(user=user)
    if not request.user == user:
        return render(request, 'no.html')
    else:
        return render(request, 'profile.html', {'user':user,'products': products})

I'm using a form to edit the profile - here's the view:

def edit_profile(request):
    user = request.user
    products = Product.objects.filter(user=user)
    form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name, 'biography':user.biography})
    if request.method == 'POST':
        if form.is_valid():
            user.first_name = request.POST['first_name']
            user.last_name = request.POST['last_name']
            user.biography = request.POST['biography']
            user.save()
            return render(request, 'profile.html', {'user':user, 'products':products})
    context = {"form": form}
    return render(request, "edit_profile.html", context)

...and here's the form:

class EditProfileForm(forms.Form):
    first_name = forms.CharField(label='First Name')
    last_name = forms.CharField(label='Last Name')
    biography = forms.CharField(label='Biography', widget=Textarea(attrs={'rows': 5}))

Here's a screenshot of the error message:

I'm mixing something up but I can't figure out what. Doesn't help that I'm new to this ...still trying!

Body:
As the error message says:

"User.Biography" must be a "Biography" instance.

In your edit_profile definition, you have the following assignment:

user.biography = request.POST['biography']

request.POST['biography'] is not a valid instance of Biography. So, you have to create a valid Biography instance, according to your Biography model, with the request.POST['biography'].

After that, you can assign your valid instance to user.biography.

I hope it had been useful for you.


问:
MySQL join table to itself based on row number returns no data
I've got a logs table with an ID column in it, and I want to do the following:

Select the ID and row number

Join the table to itself based on the row number

My objective is to get a specific row as well as the row before it. The SQL query below actually returns nothing. It's like it forgets the row number entirely. Joining on ID returns just fine.

Is there something that needs to be done in MySQL to support this kind of operation?

```<code>select * from
    (select id, @rownum := @rownum + 1 as 'row'
        from logs, (select @rownum := 0) r order by id) a
join
    (select id, @rownum := @rownum + 1 as 'row'
        from logs, (select @rownum := 0) r order by id) b
on a.row = b.row;
</code>```

答:
Change your variable name in second query, using same variable in both queries can produce unexpected results</p>

```<code>select * from
    (select id, @rownum := @rownum + 1 as 'row'
        from logs, (select @rownum := 0) r order by id) a
join
    (select id, @rownum1 := @rownum1 + 1 as 'row1'
        from logs, (select @rownum1 := 0) r order by id) b
on a.row = b.row1;
</code>```

Body:
I've got a logs table with an ID column in it, and I want to do the following:

Select the ID and row number

Join the table to itself based on the row number

My objective is to get a specific row as well as the row before it. The SQL query below actually returns nothing. It's like it forgets the row number entirely. Joining on ID returns just fine.

Is there something that needs to be done in MySQL to support this kind of operation?

select * from
    (select id, @rownum := @rownum + 1 as 'row'
        from logs, (select @rownum := 0) r order by id) a
join
    (select id, @rownum := @rownum + 1 as 'row'
        from logs, (select @rownum := 0) r order by id) b
on a.row = b.row;

Body:
Change your variable name in second query, using same variable in both queries can produce unexpected results

select * from
    (select id, @rownum := @rownum + 1 as 'row'
        from logs, (select @rownum := 0) r order by id) a
join
    (select id, @rownum1 := @rownum1 + 1 as 'row1'
        from logs, (select @rownum1 := 0) r order by id) b
on a.row = b.row1;


问:
Want to form one general Update query for all tables
I have written the code for insert into a database for all tables but I am stuck at update query.  tablename, tablepk_name, tablepk, table_sc_name , table_sc_id  are values which I am fetching from another method here is my code </p>

```<code>try {
        PreparedStatement sv = localConnection.prepareStatement("select * from " + tablename + " where " + tablepk_name + " = '" + tablepk + "'" + " and " + table_sc_name + " = '" + table_sc_id + "'");
        ResultSet rs_local = sv.executeQuery();
        while (rs_local.next()) {
           localConnection.setAutoCommit(false);
            rsmd = rs_local.getMetaData();
            final int columnCount = rsmd.getColumnCount();
            List<List<String>> rowList = new LinkedList<>();
            List<String> columnNames = null;
            String insertColumns = "";
            String insertValues = "";
            columnNames = new ArrayList<>();
            List<String> columnList = new LinkedList<>();
            rowList.add(columnList);
            for (int j = 1; j <= columnCount; j++) {
                columnNames.add(rsmd.getColumnLabel(j));
            }
            if (columnNames != null && columnNames.size() > 0) {
                insertColumns += columnNames.get(0);
                insertValues += "?";
            }
            for (int j = 1; j < columnNames.size(); j++) {
                insertColumns += "='?', " + columnNames.get(j);
                insertValues += ", " + "?";
            }
            SQL = "UPDATE " + tablename + " set (" + insertColumns + ") values(" + insertValues + ") where "+tablepk_name+"= '"+ tablepk + "'";
            PreparedStatement ps = localConnection.prepareStatement(SQL);
            for (int column = 1; column <= columnCount; column++) {
                Object value = rs_local.getObject(column);
                ps.setObject(column, value);
            }
            String psa = ps.toString();
            query = psa.substring(psa.indexOf(": ") + 2);
            System.out.println(" quer " + query);
        }
    } catch (SQLException ex) {
        Logger.getLogger(PosSynchronizationPoll.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

<p>Here is the output i am receiving </p>

```<code>UPDATE products set (id='?', reference='?', code='?', codetype='?', name='?',
pricebuy='?', pricesell='?', category='?', taxcat='?', attributeset_id='?',
stockcost='?', stockvolume='?', image='?', iscom='?', isscale='?', isconstant='?',
printkb='?', sendstatus='?', isservice='?', attributes='?', display='?',
isvprice='?', isverpatrib='?', texttip='?', warranty='?', stockunits='?',
printto='?', supplier='?', uom='?', memodate) values('04352e14-f96d-4301-bc72-f80f2ec19740',
'0012', '0012', 'EAN-13', 'text', 0.0, 8.333333333333334, '48eabc71-a100-48a2-9f11-23b60f86257d',
'001', 'd928c6b9-7a87-4bac-8d8c-ce846498393b', 0.0, 0.0, null, 0, 0, 0, 0,
0, 0, _binary'<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>  \n
<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">\n<properties>\n </properties>', '', 0, 0, '', 0, 0.0, '1',
'2ef4a3a1-f610-4eb4-9339-e7e19496b918', '0', null) where id= '04352e14-f96d-4301-bc72-f80f2ec19740';
</code>```

<p>*where as the desired output should </p>

```<code>UPDATE products set (id=?, reference=?, code=?, codetype=?,
name=?, pricebuy=?, pricesell=?, category=?, taxcat=?,
attributeset_id=?, stockcost=?, stockvolume=?, image=?,
 iscom=?, isscale=?, isconstant=?, printkb=?, sendstatus=?,
isservice=?, attributes=?, display=?, isvprice=?, isverpatrib=?,
texttip=?, warranty=?, stockunits=?, printto=?, supplier=?,
uom=?, memodate=?) values('04352e14-f96d-4301-bc72-f80f2ec19740',
'0012', '0012', 'EAN-13', 'text', 0.0, 8.333333333333334, '48eabc71-a100-48a2-9f11-23b60f86257d',
'001', 'd928c6b9-7a87-4bac-8d8c-ce846498393b', 0.0, 0.0, null, 0,
0, 0, 0, 0, 0, _binary'<?xml version=\"1.0\"
 encoding=\"UTF-8\" standalone=\"no\"?>  \n<!DOCTYPE properties SYSTEM
 \"http://java.sun.com/dtd/properties.dtd\">\n<properties>\n </properties>', '', 0, 0, '',
 0, 0.0, '1', '2ef4a3a1-f610-4eb4-9339-e7e19496b918', '0', null)
where id= '04352e14-f96d-4301-bc72-f80f2ec19740'*
</code>```

答:
```<code>try {
    PreparedStatement sv = localConnection.prepareStatement("select * from " + tablename + " where " + tablepk_name + " = '" + tablepk + "'" + " and " + table_sc_name + " = '" + table_sc_id + "'");
    ResultSet rs_local = sv.executeQuery();
    while (rs_local.next()) {
       localConnection.setAutoCommit(false);
        rsmd = rs_local.getMetaData();
        final int columnCount = rsmd.getColumnCount();
        List<List<String>> rowList = new LinkedList<>();
        List<String> columnNames = null;
        String insertColumns = "";
        String insertValues = "";
        columnNames = new ArrayList<>();
        List<String> columnList = new LinkedList<>();
        rowList.add(columnList);
        for (int j = 1; j <= columnCount; j++) {
            columnNames.add(rsmd.getColumnLabel(j));
        }
        if (columnNames != null && columnNames.size() > 0) {
            insertColumns += columnNames.get(0);
            insertValues += "?";
        }
        for (int j = 1; j < columnNames.size(); j++) {
            insertColumns += "='?', " + columnNames.get(j);
            insertValues += ", " + "?";
        }
        SQL = "UPDATE " + tablename + " set " + insertColumns + " = ? where " + tablepk_name +" = '"+ tablepk + "'";
        PreparedStatement ps = localConnection.prepareStatement(SQL);
        for (int column = 1; column <= columnCount; column++) {
            Object value = rs_local.getObject(column);
            ps.setObject(column, value);
        }
        String psa = ps.toString();
        query = psa.substring(psa.indexOf(": ") + 2);
        System.out.println(" quer " + query);
    }
} catch (SQLException ex) {
    Logger.getLogger(PosSynchronizationPoll.class.getName()).log(Level.SEVERE, null, ex);
}
</code>```

Body:
I have written the code for insert into a database for all tables but I am stuck at update query.  tablename, tablepk_name, tablepk, table_sc_name , table_sc_id  are values which I am fetching from another method here is my code

try {
        PreparedStatement sv = localConnection.prepareStatement("select * from " + tablename + " where " + tablepk_name + " = '" + tablepk + "'" + " and " + table_sc_name + " = '" + table_sc_id + "'");
        ResultSet rs_local = sv.executeQuery();
        while (rs_local.next()) {
           localConnection.setAutoCommit(false);
            rsmd = rs_local.getMetaData();
            final int columnCount = rsmd.getColumnCount();
            List<List<String>> rowList = new LinkedList<>();
            List<String> columnNames = null;
            String insertColumns = "";
            String insertValues = "";
            columnNames = new ArrayList<>();
            List<String> columnList = new LinkedList<>();
            rowList.add(columnList);
            for (int j = 1; j <= columnCount; j++) {
                columnNames.add(rsmd.getColumnLabel(j));
            }
            if (columnNames != null && columnNames.size() > 0) {
                insertColumns += columnNames.get(0);
                insertValues += "?";
            }
            for (int j = 1; j < columnNames.size(); j++) {
                insertColumns += "='?', " + columnNames.get(j);
                insertValues += ", " + "?";
            }
            SQL = "UPDATE " + tablename + " set (" + insertColumns + ") values(" + insertValues + ") where "+tablepk_name+"= '"+ tablepk + "'";
            PreparedStatement ps = localConnection.prepareStatement(SQL);
            for (int column = 1; column <= columnCount; column++) {
                Object value = rs_local.getObject(column);
                ps.setObject(column, value);
            }
            String psa = ps.toString();
            query = psa.substring(psa.indexOf(": ") + 2);
            System.out.println(" quer " + query);
        }
    } catch (SQLException ex) {
        Logger.getLogger(PosSynchronizationPoll.class.getName()).log(Level.SEVERE, null, ex);
    }

Here is the output i am receiving

UPDATE products set (id='?', reference='?', code='?', codetype='?', name='?',
pricebuy='?', pricesell='?', category='?', taxcat='?', attributeset_id='?',
stockcost='?', stockvolume='?', image='?', iscom='?', isscale='?', isconstant='?',
printkb='?', sendstatus='?', isservice='?', attributes='?', display='?',
isvprice='?', isverpatrib='?', texttip='?', warranty='?', stockunits='?',
printto='?', supplier='?', uom='?', memodate) values('04352e14-f96d-4301-bc72-f80f2ec19740',
'0012', '0012', 'EAN-13', 'text', 0.0, 8.333333333333334, '48eabc71-a100-48a2-9f11-23b60f86257d',
'001', 'd928c6b9-7a87-4bac-8d8c-ce846498393b', 0.0, 0.0, null, 0, 0, 0, 0,
0, 0, _binary'<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>  \n
<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">\n<properties>\n </properties>', '', 0, 0, '', 0, 0.0, '1',
'2ef4a3a1-f610-4eb4-9339-e7e19496b918', '0', null) where id= '04352e14-f96d-4301-bc72-f80f2ec19740';

*where as the desired output should

UPDATE products set (id=?, reference=?, code=?, codetype=?,
name=?, pricebuy=?, pricesell=?, category=?, taxcat=?,
attributeset_id=?, stockcost=?, stockvolume=?, image=?,
 iscom=?, isscale=?, isconstant=?, printkb=?, sendstatus=?,
isservice=?, attributes=?, display=?, isvprice=?, isverpatrib=?,
texttip=?, warranty=?, stockunits=?, printto=?, supplier=?,
uom=?, memodate=?) values('04352e14-f96d-4301-bc72-f80f2ec19740',
'0012', '0012', 'EAN-13', 'text', 0.0, 8.333333333333334, '48eabc71-a100-48a2-9f11-23b60f86257d',
'001', 'd928c6b9-7a87-4bac-8d8c-ce846498393b', 0.0, 0.0, null, 0,
0, 0, 0, 0, 0, _binary'<?xml version=\"1.0\"
 encoding=\"UTF-8\" standalone=\"no\"?>  \n<!DOCTYPE properties SYSTEM
 \"http://java.sun.com/dtd/properties.dtd\">\n<properties>\n </properties>', '', 0, 0, '',
 0, 0.0, '1', '2ef4a3a1-f610-4eb4-9339-e7e19496b918', '0', null)
where id= '04352e14-f96d-4301-bc72-f80f2ec19740'*


问:
How to prompt the user until the input matches any element of an array?
I'm writing a Perl program where I have to prompt the user for input until the input exists in an array @stops I created earlier. If the user input matches then the program stops prompting and stores it in the scalar variable $first.

This is not my full code - I have use strict; and use warnings; in my code, and I have code from earlier that puts values into the array @stops.

```<code>print "What is your input?\n";
my $first = <STDIN>;
chomp $first;

do {

    if ( grep { $_ eq $first } @stops ) {
        last;
    }
    else {
        print "Invalid stop $first. Enter input again\n";
        my $first = <STDIN>;
        chomp $first;
    }
}
</code>```

答:
You were pretty good already, just two things.
a) if you use my $first in that else-block, you will not be able to check it in the next iteration of the loop. Speaking of loop ...
b) do doesn't run in a loop, which is what you'd want.

```<code>print "What is your input?\n";
my $first = <STDIN>;
chomp $first;
while(1) {
    if (grep { $_ eq $first } @stops) {
        last;
    }
    else {
        print "Invalid stop $first. Enter input again\n";
        $first = <STDIN>;
        chomp $first;
    }
}
</code>```

Will do that, provided that you've defined @stops somewhere.

Body:
I'm writing a Perl program where I have to prompt the user for input until the input exists in an array @stops I created earlier. If the user input matches then the program stops prompting and stores it in the scalar variable $first.

This is not my full code - I have use strict; and use warnings; in my code, and I have code from earlier that puts values into the array @stops.

print "What is your input?\n";
my $first = <STDIN>;
chomp $first;

do {

    if ( grep { $_ eq $first } @stops ) {
        last;
    }
    else {
        print "Invalid stop $first. Enter input again\n";
        my $first = <STDIN>;
        chomp $first;
    }
}

Body:
You were pretty good already, just two things.
a) if you use my $first in that else-block, you will not be able to check it in the next iteration of the loop. Speaking of loop ...
b) do doesn't run in a loop, which is what you'd want.

print "What is your input?\n";
my $first = <STDIN>;
chomp $first;
while(1) {
    if (grep { $_ eq $first } @stops) {
        last;
    }
    else {
        print "Invalid stop $first. Enter input again\n";
        $first = <STDIN>;
        chomp $first;
    }
}

Will do that, provided that you've defined @stops somewhere.


问:
Jquery UI Datepicker Show Additional Disabled Dates
I am trying to show additional disabled dates for the datepicker. For instance, I have min date as 2-1-2018 and max date as 3-1-2018. Is there anyway way to show 1-1-2018 and 4-1-2018 as disabled? Here is what I have right now. I don't need to dynamically set the dates. I need to display additional disabled dates so the user can see a larger range of disabled dates.

```<code>             beforeShow : function () {

             if (attrs.selecteddate) {
                 /*
                  2018-10-29T00:00:00.000+0000 before
                  2018-10-29 after
                  Only need the 00-00-0000 part of the date to avoid time zone issues. QoT always returns 00T for timezone anyways.
                 */
                 var formattedDate = attrs.selecteddate.split("T");
                 attrs["formattedDate"] = formattedDate[0].substring(5) + "-" + formattedDate[0].substring(0, 4);
                 /*z
                 Set the date that the calander will display.
                 Append universal date time zone so correct date will be set in Firefox. It replaces T00:00:00.000+0000 with T12:00:00Z
                 */
                 jQuery(this).datepicker('setDate', new Date(formattedDate[0] + 'T12:00:00Z'));
             }

            jQuery(this).datepicker('option', {
               minDate : ( attrs.edittype === 'single' ) ? incrementDate(attrs.mindate) : attrs.mindate,
               maxDate : ( attrs.edittype === 'single' ) ? convertToDateObj(attrs.maxdate) : attrs.maxdate
            });
         },
</code>```

答:
This below js code will help you to change min and max date dynamically.

$(function(){

$("#fdate").datepicker({
    formatDate:"dd-mm-yy",
    onselect:function(){
      //do stuff here
    },
    onclose:function(){
    //do stuff here
    }
  });

var date1 = "15-11-2017";
var date2 = "17-11-2017"; //you can pass dynamically date

$("#fdate").datepicker("option", "minDate", date1);
$("#fdate").datepicker("option", "maxDate", date2);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input id="fdate" type="text" name="date" /></code>```

Body:
I am trying to show additional disabled dates for the datepicker. For instance, I have min date as 2-1-2018 and max date as 3-1-2018. Is there anyway way to show 1-1-2018 and 4-1-2018 as disabled? Here is what I have right now. I don't need to dynamically set the dates. I need to display additional disabled dates so the user can see a larger range of disabled dates.

             beforeShow : function () {

             if (attrs.selecteddate) {
                 /*
                  2018-10-29T00:00:00.000+0000 before
                  2018-10-29 after
                  Only need the 00-00-0000 part of the date to avoid time zone issues. QoT always returns 00T for timezone anyways.
                 */
                 var formattedDate = attrs.selecteddate.split("T");
                 attrs["formattedDate"] = formattedDate[0].substring(5) + "-" + formattedDate[0].substring(0, 4);
                 /*z
                 Set the date that the calander will display.
                 Append universal date time zone so correct date will be set in Firefox. It replaces T00:00:00.000+0000 with T12:00:00Z
                 */
                 jQuery(this).datepicker('setDate', new Date(formattedDate[0] + 'T12:00:00Z'));
             }

            jQuery(this).datepicker('option', {
               minDate : ( attrs.edittype === 'single' ) ? incrementDate(attrs.mindate) : attrs.mindate,
               maxDate : ( attrs.edittype === 'single' ) ? convertToDateObj(attrs.maxdate) : attrs.maxdate
            });
         },

Body:
This below js code will help you to change min and max date dynamically.

$(function(){

$("#fdate").datepicker({
    formatDate:"dd-mm-yy",
    onselect:function(){
      //do stuff here
    },
    onclose:function(){
    //do stuff here
    }
  });

var date1 = "15-11-2017";
var date2 = "17-11-2017"; //you can pass dynamically date

$("#fdate").datepicker("option", "minDate", date1);
$("#fdate").datepicker("option", "maxDate", date2);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input id="fdate" type="text" name="date" />


问:
How to set the log level for an imported module?
Write your code with a nice logger

```<code>import logging

def init_logging():
     logFormatter = logging.Formatter("[%(asctime)s] %(levelname)s::%(module)s::%(funcName)s() %(message)s")
     rootLogger = logging.getLogger()
     LOG_DIR = os.getcwd() + '/' + 'logs'
     if not os.path.exists(LOG_DIR):
          os.makedirs(LOG_DIR)
     fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
     fileHandler.setFormatter(logFormatter)
     rootLogger.addHandler(fileHandler)
     rootLogger.setLevel(logging.DEBUG)
     consoleHandler = logging.StreamHandler()
     consoleHandler.setFormatter(logFormatter)
     rootLogger.addHandler(consoleHandler)
     return rootLogger

logger = init_logging()
</code>```

works as expected. Logging using logger.debug("Hello! :)") logs to file and console.

In a second step you want to import an external module which is also logging using logging module:

Install it using pip3 install pymisp (or any other external module)

Import it using from pymisp import PyMISP (or any other external module)

Create an object of it using self.pymisp = PyMISP(self.ds_model.api_url, self.ds_model.api_key, False, 'json') (or any other...)

What now happens is, that every debug log output from the imported module is getting logged to the log file and the console. The question now is, how to set a different (higher) log level for the imported module.

答:
As Meet Sinoja and anishtain4 pointed out in the comments, the best and most generic method is to retrieve the logger by the name of the imported module as follows:

```<code>import logging
import some_module_with_logging
logging.getLogger("some_module_with_logging").setLevel(logging.WARNING)
</code>```

Another option (though not recommended if the generic method above works) is to extract the module's logger variable and customize it to your needs. Most third-party modules store it in a module-level variable called logger or _log. In your case:

```<code>import logging
import pymisp

pymisp.logger.setLevel(logging.INFO)
# code of module goes here
</code>```

Body:
Write your code with a nice logger

import logging

def init_logging():
     logFormatter = logging.Formatter("[%(asctime)s] %(levelname)s::%(module)s::%(funcName)s() %(message)s")
     rootLogger = logging.getLogger()
     LOG_DIR = os.getcwd() + '/' + 'logs'
     if not os.path.exists(LOG_DIR):
          os.makedirs(LOG_DIR)
     fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
     fileHandler.setFormatter(logFormatter)
     rootLogger.addHandler(fileHandler)
     rootLogger.setLevel(logging.DEBUG)
     consoleHandler = logging.StreamHandler()
     consoleHandler.setFormatter(logFormatter)
     rootLogger.addHandler(consoleHandler)
     return rootLogger

logger = init_logging()

works as expected. Logging using logger.debug("Hello! :)") logs to file and console.

In a second step you want to import an external module which is also logging using logging module:

Install it using pip3 install pymisp (or any other external module)

Import it using from pymisp import PyMISP (or any other external module)

Create an object of it using self.pymisp = PyMISP(self.ds_model.api_url, self.ds_model.api_key, False, 'json') (or any other...)

What now happens is, that every debug log output from the imported module is getting logged to the log file and the console. The question now is, how to set a different (higher) log level for the imported module.

Body:
As Meet Sinoja and anishtain4 pointed out in the comments, the best and most generic method is to retrieve the logger by the name of the imported module as follows:

import logging
import some_module_with_logging
logging.getLogger("some_module_with_logging").setLevel(logging.WARNING)

Another option (though not recommended if the generic method above works) is to extract the module's logger variable and customize it to your needs. Most third-party modules store it in a module-level variable called logger or _log. In your case:

import logging
import pymisp

pymisp.logger.setLevel(logging.INFO)
# code of module goes here

ContentLicense: CC BY-SA 4.0


问:
Wakanda 2.2.1 Enterprise Server DataBrowser
Regarding the 2.2.1 Wakanda Enterprise Server, I'm looking for basic guidance regarding some of the features that were more easily accessed with prior Studio versions (buttons):

Data Browser - using the simply CRUD example from Wakanda.  Following address does not yield a Data Browser:
http://127.0.0.1:8080/walib/dataBrowser/index.html.  Tried port 8081 as well, the server is published on 8080.

Administration Console.  Possibly due to a license key issue; but should I get the full administration console functionality as with prior versions?  I am seeing only a small subset of features on the admin console.

Thanks

答:
Data Browser is made with WAF of Wakanda V1 and is removed since V2 no longer supports WAF. The V2 CRUD example using Angular is available in latest Wakanda doc.

The Administration Console, aka Admin Dashboard in v2, has received an update in v2 with more features include:

Display the running solution basic information.

Run WakandaDB maintenance actions: run, verify and restore.

Schedule tasks (CRON jobs): create, update, schedule and remove.

Analyze your tasks execution (calendar, output, statistics..).

You will need an enterprise license to access admin dashboard at http://127.0.0.1:8080/admin/.


问:
How do you get the hue of a #xxxxxx colour?
How do you extract the hue component of a color given as #rrggbb?

答:
I have stumbled on this issue as well after years, that's how I have worked around it.

Credits: Brandon Mathis of hslpicker.com, code was taken from here

```<code>function hexToRgb (color) {
  let hex = color[0] === '#' ? color.slice(1) : color;
  let c;

  // expand the short hex by doubling each character, fc0 -> ffcc00
  if (hex.length !== 6) {
    hex = ((() => {
      const result = [];
      for (c of Array.from(hex)) {
        result.push(`${c}${c}`);
      }
      return result;
    })()).join('');
  }
  const colorStr = hex.match(/#?(.{2})(.{2})(.{2})/).slice(1);
  const rgb = colorStr.map(col => parseInt(col, 16));
  rgb.push(1);
  return rgb;
}

function rgbToHsl (rgb) {
  const r = rgb[0] / 255;
  const g = rgb[1] / 255;
  const b = rgb[2] / 255;

  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  const diff = max - min;
  const add = max + min;

  const hue =
    min === max ?
      0
    : r === max ?
      (((60 * (g - b)) / diff) + 360) % 360
    : g === max ?
      ((60 * (b - r)) / diff) + 120
    :
      ((60 * (r - g)) / diff) + 240;

  const lum = 0.5 * add;

  const sat =
    lum === 0 ?
      0
    : lum === 1 ?
      1
    : lum <= 0.5 ?
      diff / add
    :
      diff / (2 - add);

  const h = Math.round(hue);
  const s = Math.round(sat * 100);
  const l = Math.round(lum * 100);
  const a = rgb[3] || 1;

  return [h, s, l, a];
}
</code>```

I have written a small wrapper around those 2 functions to convert array of hex colors to arrays of strings describing H / S / L components

```<code>function hexToHsl (color) {
  const rgb = hexToRgb(color);
  const hsl = rgbToHsl(rgb);
  return `original: ${ color } - H: ${ hsl[0] } S: ${ hsl[1] } L: ${ hsl[2] }`;
}
</code>```

Usage:

```<code>var colors = ['#51bce6','#6dcff6','#829CBD','#565a5c']
colors.map(color => hexToHsl(color))

=> ["original: #51bce6 - H: 197 S: 75 L: 61", "original: #6dcff6 - H: 197 S: 88 L: 70", "original: #829CBD - H: 214 S: 31 L: 63", "original: #565a5c - H: 200 S: 3 L: 35"]
</code>```

Body:
I have stumbled on this issue as well after years, that's how I have worked around it.

Credits: Brandon Mathis of hslpicker.com, code was taken from here

function hexToRgb (color) {
  let hex = color[0] === '#' ? color.slice(1) : color;
  let c;

  // expand the short hex by doubling each character, fc0 -> ffcc00
  if (hex.length !== 6) {
    hex = ((() => {
      const result = [];
      for (c of Array.from(hex)) {
        result.push(`${c}${c}`);
      }
      return result;
    })()).join('');
  }
  const colorStr = hex.match(/#?(.{2})(.{2})(.{2})/).slice(1);
  const rgb = colorStr.map(col => parseInt(col, 16));
  rgb.push(1);
  return rgb;
}

function rgbToHsl (rgb) {
  const r = rgb[0] / 255;
  const g = rgb[1] / 255;
  const b = rgb[2] / 255;

  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  const diff = max - min;
  const add = max + min;

  const hue =
    min === max ?
      0
    : r === max ?
      (((60 * (g - b)) / diff) + 360) % 360
    : g === max ?
      ((60 * (b - r)) / diff) + 120
    :
      ((60 * (r - g)) / diff) + 240;

  const lum = 0.5 * add;

  const sat =
    lum === 0 ?
      0
    : lum === 1 ?
      1
    : lum <= 0.5 ?
      diff / add
    :
      diff / (2 - add);

  const h = Math.round(hue);
  const s = Math.round(sat * 100);
  const l = Math.round(lum * 100);
  const a = rgb[3] || 1;

  return [h, s, l, a];
}

I have written a small wrapper around those 2 functions to convert array of hex colors to arrays of strings describing H / S / L components

function hexToHsl (color) {
  const rgb = hexToRgb(color);
  const hsl = rgbToHsl(rgb);
  return `original: ${ color } - H: ${ hsl[0] } S: ${ hsl[1] } L: ${ hsl[2] }`;
}

Usage:

var colors = ['#51bce6','#6dcff6','#829CBD','#565a5c']
colors.map(color => hexToHsl(color))

=> ["original: #51bce6 - H: 197 S: 75 L: 61", "original: #6dcff6 - H: 197 S: 88 L: 70", "original: #829CBD - H: 214 S: 31 L: 63", "original: #565a5c - H: 200 S: 3 L: 35"]


问:
Preparing debugger support for iPhone
I cant install he app on iphone i'm stuck on this message.

"Preparing debugger support for iPhone"

Tried all answers here and still nothing.

It is followed by itunes could not connect to iphone or whatever...

I'm using a virtual mac machine.

答:
After hours of research and useless downvotes i got the tiny trouble.
My virtualbox was configured to connect the devices over USB 1.0

As soon as i installed extensions pack and switched to USB 2.0 the app started deploying.

Title: Preparing debugger support for iPhone


问:
React Dev environment create a new Session
I have a simple NodeJS & React Webapp that works when I deploy the React build into NodeJS.

when I click login the server will check authorization and redirect to another page. when I try to run the webapp from the React build (port 3000) I notice that once logged in I have a new session and therefore fetching the data from the server (port 8080) will not work.

https://github.com/Yanipo5/MenuCreator

NodeJS - Login Api (Routing to url will work);

```<code>router.post('/',approveUserPassword, function(req, res){

  console.log(new Date() + ":" + req.sessionID)

  if(req.session.auth){
    let url = 'http://localhost:3000/edit-menu';
    res.redirect(url);

  }
  });
function approveUserPassword(req, res, next) {

  let email = req.body.email;
  let psw = req.body.psw;
  let query = "SELECT id FROM Users "             +
              "WHERE email= '" + email + "' AND " +
              "password='" + psw + "'"            ;

  con.query(query, function (err, result, fields) {
    if (err) throw err;

    if(result.length > 0){
      req.session.auth = true;
      req.session.rest_id = result[0].id;

    }else{
      req.session.auth = false;
    }

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

React - will fail on port 3000, since the new session will not be authenticated.

```<code>componentDidMount(){
    let url ='http://localhost:8080/api/menu';
    fetch(url, {credentials: 'same-origin' })
          .then(response => response.json())
          .then(json => {
            this.setState({data: json});
            console.log(json)
          })
  }
</code>```

api/menu

```<code>function checkAuth(req, res, next) {
  console.log(new Date() + ":" + req.sessionID)

  if(!req.session.auth){
    res.json("no auth for menu");

    }else{
      next()

    }
};

router.get('/', checkAuth, function(req, res){

    let sql = "SELECT * FROM Menu_Items " +
                "WHERE rest_id=" + req.session.rest_id + ";";

    con.query(sql, function (err, result, fields) {
      if (err){
        console.log(sql);
        throw err;
      }

      res.json(result);
    });

});
</code>```

Here is the NodeJS log for the sessions (as you can see there are 2 unique):

Mon Nov 13 2017 19:21:59 GMT+0200 (IST):6tu0wi3Lt2RNEMD-SZHCzX2vJ0DljtHL

Mon Nov 13 2017 19:22:00 GMT+0200 (IST):JRBGJjxS109F3C_ghr3ggkQlcC5bapsE

答:
Your local development server, and API, run on different ports. Due to the Same Origin Policy the browser will deny any requests that are not on the same domain, or port.

I've checked the repo and it's using create-react-app which means you should be able to set up a proxy. I've done this many times myself.

In client-src/package.json add the following line:

```<code>"proxy": "http://localhost:8080/"
</code>```

This will proxy requests to the API. You can now make calls to your API like so:

```<code>componentDidMount(){
    let url ='http://localhost:3000/api/menu';
    fetch(url, {credentials: 'same-origin' })
      .then(response => response.json())
      .then(json => {
        this.setState({data: json});
        console.log(json)
      })
}
</code>```

Body:
I have a simple NodeJS & React Webapp that works when I deploy the React build into NodeJS.

when I click login the server will check authorization and redirect to another page. when I try to run the webapp from the React build (port 3000) I notice that once logged in I have a new session and therefore fetching the data from the server (port 8080) will not work.

https://github.com/Yanipo5/MenuCreator

NodeJS - Login Api (Routing to url will work);

router.post('/',approveUserPassword, function(req, res){

  console.log(new Date() + ":" + req.sessionID)

  if(req.session.auth){
    let url = 'http://localhost:3000/edit-menu';
    res.redirect(url);

  }
  });
function approveUserPassword(req, res, next) {

  let email = req.body.email;
  let psw = req.body.psw;
  let query = "SELECT id FROM Users "             +
              "WHERE email= '" + email + "' AND " +
              "password='" + psw + "'"            ;

  con.query(query, function (err, result, fields) {
    if (err) throw err;

    if(result.length > 0){
      req.session.auth = true;
      req.session.rest_id = result[0].id;

    }else{
      req.session.auth = false;
    }

    next();
  });
}

React - will fail on port 3000, since the new session will not be authenticated.

componentDidMount(){
    let url ='http://localhost:8080/api/menu';
    fetch(url, {credentials: 'same-origin' })
          .then(response => response.json())
          .then(json => {
            this.setState({data: json});
            console.log(json)
          })
  }

api/menu

function checkAuth(req, res, next) {
  console.log(new Date() + ":" + req.sessionID)

  if(!req.session.auth){
    res.json("no auth for menu");

    }else{
      next()

    }
};

router.get('/', checkAuth, function(req, res){

    let sql = "SELECT * FROM Menu_Items " +
                "WHERE rest_id=" + req.session.rest_id + ";";

    con.query(sql, function (err, result, fields) {
      if (err){
        console.log(sql);
        throw err;
      }

      res.json(result);
    });

});

Here is the NodeJS log for the sessions (as you can see there are 2 unique):

Mon Nov 13 2017 19:21:59 GMT+0200 (IST):6tu0wi3Lt2RNEMD-SZHCzX2vJ0DljtHL

Mon Nov 13 2017 19:22:00 GMT+0200 (IST):JRBGJjxS109F3C_ghr3ggkQlcC5bapsE

Body:
Your local development server, and API, run on different ports. Due to the Same Origin Policy the browser will deny any requests that are not on the same domain, or port.

I've checked the repo and it's using create-react-app which means you should be able to set up a proxy. I've done this many times myself.

In client-src/package.json add the following line:

"proxy": "http://localhost:8080/"

This will proxy requests to the API. You can now make calls to your API like so:

componentDidMount(){
    let url ='http://localhost:3000/api/menu';
    fetch(url, {credentials: 'same-origin' })
      .then(response => response.json())
      .then(json => {
        this.setState({data: json});
        console.log(json)
      })
}


问:
Create vertical space (gaps) between rows in CSS Grid
Is there any way to have my vertically stacked buttons have a gap between them, other than using the break (
) tag?

I've exhausted every other option and nothing seems to work other than using the break (
) tag in the html sheet after each div.

Here is my code (break tags taken out):

$(document).ready(function() {
  var lat;
  var long;
  $.getJSON("https://freegeoip.net/json/", function(data2) {
    lat = data2.latitude;
    long = data2.longitude;
    console.log(lat);
    console.log(long);
    //creating an api with the user's geolocation
    var api = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=b6e4d569d1718b07a44702443dd0ed77"

    //json call for the api
    $.getJSON(api, function(data) {
      var fTemp;
      var cTemp;
      var tempSwap = true;

      var weatherType = data.weather[0].description;
      var kTemp = data.main.temp;
      var windSpeed = data.wind.speed;
      var city = data.name;
      $("#city").html(city);
      fTemp = (kTemp * (9 / 5) - 459.67).toFixed(2);
      cTemp = (kTemp - 273).toFixed(1);

      $("#api").html(api);
      $("#weatherType").html(weatherType);

      $("#fTemp").html(fTemp + "℉");
      $("#fTemp").click(function() {
        if (tempSwap === false) {
          $("#fTemp").html(fTemp + "℉");
          tempSwap = true;
        } else {
          $("#fTemp").html(cTemp + "℃");
          tempSwap = false;
        }
      });

      $("#windSpeed").html(windSpeed + "m/sec");
    })

    if (fTemp >= 100) {
      $("container").css("background-image", "url(https://s2.postimg.org/6ss6kyuhl/yamaha_yzf_r1-wallpaper-1024x768.jpg)");
    } else if (fTemp < 90) {
      $("container").css("background-image", "url(https://s2.postimg.org/lapdsz8y1/beyonce_knowles_2-wallpaper-1024x768.jpg)")
    } else if (fTemp > 80) {
      $("container").css("background-image", "url(https://s2.postimg.org/i54s2ennd/Beyonce_in_Jamaica.jpg)")
    } else if (fTemp < 70) {
      $("container").css("background-image", "url(https://s2.postimg.org/t4pzebr0p/golf_course_landscape-wallpaper-1024x768.jpg)")
    } else if (fTemp < 60) {
      $("container").css("background-image", "url()")
    } else if (fTemp < 50) {
      $("container").css("background-image", "url(https://s2.postimg.org/8xcjlpoax/rihanna_9-wallpaper-1024x768.jpg)")
    } else if (fTemp = 37.40) {
      $("container").css("background-image", url("https://s2.postimg.org/8xcjlpoax/rihanna_9-wallpaper-1024x768.jpg"))
    } else if (fTemp < 30) {
      $("container").css("background-image", "url(https://s2.postimg.org/nhtmgb6c9/white_snowy_road-wallpaper-1024x768.jpg)")
    } else if (fTemp < 20) {
      $("container").css("background-image", "url(https://s2.postimg.org/9a3xrntnd/rihanna_dior_sunglasses-wallpaper-1024x768.jpg)")
    } else if (fTemp < 10) {
      $("container").css("background-image", "url()")
    } else if (fTemp < 0) {
      $("container").css("background-image", "url(https://s2.postimg.org/r05mdaf49/snowy_cabin_mountains_winter-wallpaper-1024x768.jpg)")
    } else if (fTemp < -10) {
      $("container").css("background-image", "url(https://s2.postimg.org/7v2d3i5l5/skiing-wallpaper-1024x768.jpg)")

    };

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  text-align: center;
  background: url("https://s1.postimg.org/14i3xf2um7/Hummer-_H1-_Snow-_Turn-_Headlights-1024x768.jpg") no-repeat fixed;
  background-size: cover;
  background-position: center;
  /*background-color: blue;*/
  width: 100%;
  height: 1000px;
  margin: auto;
}

.About {
  /*background-color: blue;*/
  /*transform: translateY(650%)*/
  position: fixed;
  top: 35%;
  left: 0;
  right: 0;
  margin: auto;
}

h2 {
  color: white;
  font-size: 1.5em
}

.holder {
  border: 3px;
  background-color: rgba(0, 0, 0, .80);
  width: 55%;
  height: auto;
  position: fixed;
  top: 50%;
  left: 0;
  right: 0;
  margin: auto;
  padding-top: 5px;
  padding-bottom: 10px;
  padding-left: 3px;
  padding-right: 3px;
  border: 3px solid grey;
  border-radius: 10px;
}

#city,
#weatherType,
#fTemp,
#windSpeed {
  transform: translateY(9%);
  background-color: #c6c6c4;
  border-bottom: 2px inset #FFF;
  border-right: 2px inset #FFF;
  border-radius: 5px;
  height: 30px;
  width: 90%;
  margin: auto;
  /*padding-bottom: 2px ;*/
}

.btn.btn-default {
  color: #0040ff;
  font-size: .80em;
  font-family: Orbitron, sans-serif;
  line-height: 2.45em;
}

@media(min-width: 500px) {
  .holder {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
  }
}</code>```

<title></title>

  <link href='https://fonts.googleapis.com/css?family=Orbitron' rel='stylesheet' type='text/css'>

Your Local Weather App

```

Here is my CodePen.

答:
This is what you already have for wider screens:

@media (min-width: 500px) {
  .holder {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr 1fr;
  }
}
```

<p>Add this for smaller screens, where you want your elements vertically stacked in one column:</p>

<pre class="lang-css prettyprint-override"><code>.holder {
   display: grid;
   grid-template-columns: 1fr;
   grid-row-gap: 1em;
}
</code>```

Revised CodePen

Grid provides grid-column-gap, grid-row-gap and grid-gap (the shorthand), which create space between grid items (but not between items and the container).

10.1. Gutters: the grid-column-gap, grid-row-gap, and
  grid-gap
  properties

These properties specify the gutters between grid rows and grid
  columns, respectively.

Body:
Is there any way to have my vertically stacked buttons have a gap between them, other than using the break (
) tag?

I've exhausted every other option and nothing seems to work other than using the break (
) tag in the html sheet after each div.

Here is my code (break tags taken out):

$(document).ready(function() {
  var lat;
  var long;
  $.getJSON("https://freegeoip.net/json/", function(data2) {
    lat = data2.latitude;
    long = data2.longitude;
    console.log(lat);
    console.log(long);
    //creating an api with the user's geolocation
    var api = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=b6e4d569d1718b07a44702443dd0ed77"

    //json call for the api
    $.getJSON(api, function(data) {
      var fTemp;
      var cTemp;
      var tempSwap = true;

      var weatherType = data.weather[0].description;
      var kTemp = data.main.temp;
      var windSpeed = data.wind.speed;
      var city = data.name;
      $("#city").html(city);
      fTemp = (kTemp * (9 / 5) - 459.67).toFixed(2);
      cTemp = (kTemp - 273).toFixed(1);

      $("#api").html(api);
      $("#weatherType").html(weatherType);

      $("#fTemp").html(fTemp + "℉");
      $("#fTemp").click(function() {
        if (tempSwap === false) {
          $("#fTemp").html(fTemp + "℉");
          tempSwap = true;
        } else {
          $("#fTemp").html(cTemp + "℃");
          tempSwap = false;
        }
      });

      $("#windSpeed").html(windSpeed + "m/sec");
    })

    if (fTemp >= 100) {
      $("container").css("background-image", "url(https://s2.postimg.org/6ss6kyuhl/yamaha_yzf_r1-wallpaper-1024x768.jpg)");
    } else if (fTemp < 90) {
      $("container").css("background-image", "url(https://s2.postimg.org/lapdsz8y1/beyonce_knowles_2-wallpaper-1024x768.jpg)")
    } else if (fTemp > 80) {
      $("container").css("background-image", "url(https://s2.postimg.org/i54s2ennd/Beyonce_in_Jamaica.jpg)")
    } else if (fTemp < 70) {
      $("container").css("background-image", "url(https://s2.postimg.org/t4pzebr0p/golf_course_landscape-wallpaper-1024x768.jpg)")
    } else if (fTemp < 60) {
      $("container").css("background-image", "url()")
    } else if (fTemp < 50) {
      $("container").css("background-image", "url(https://s2.postimg.org/8xcjlpoax/rihanna_9-wallpaper-1024x768.jpg)")
    } else if (fTemp = 37.40) {
      $("container").css("background-image", url("https://s2.postimg.org/8xcjlpoax/rihanna_9-wallpaper-1024x768.jpg"))
    } else if (fTemp < 30) {
      $("container").css("background-image", "url(https://s2.postimg.org/nhtmgb6c9/white_snowy_road-wallpaper-1024x768.jpg)")
    } else if (fTemp < 20) {
      $("container").css("background-image", "url(https://s2.postimg.org/9a3xrntnd/rihanna_dior_sunglasses-wallpaper-1024x768.jpg)")
    } else if (fTemp < 10) {
      $("container").css("background-image", "url()")
    } else if (fTemp < 0) {
      $("container").css("background-image", "url(https://s2.postimg.org/r05mdaf49/snowy_cabin_mountains_winter-wallpaper-1024x768.jpg)")
    } else if (fTemp < -10) {
      $("container").css("background-image", "url(https://s2.postimg.org/7v2d3i5l5/skiing-wallpaper-1024x768.jpg)")

    };

  });

});

.container {
  text-align: center;
  background: url("https://s1.postimg.org/14i3xf2um7/Hummer-_H1-_Snow-_Turn-_Headlights-1024x768.jpg") no-repeat fixed;
  background-size: cover;
  background-position: center;
  /*background-color: blue;*/
  width: 100%;
  height: 1000px;
  margin: auto;
}

.About {
  /*background-color: blue;*/
  /*transform: translateY(650%)*/
  position: fixed;
  top: 35%;
  left: 0;
  right: 0;
  margin: auto;
}

h2 {
  color: white;
  font-size: 1.5em
}

.holder {
  border: 3px;
  background-color: rgba(0, 0, 0, .80);
  width: 55%;
  height: auto;
  position: fixed;
  top: 50%;
  left: 0;
  right: 0;
  margin: auto;
  padding-top: 5px;
  padding-bottom: 10px;
  padding-left: 3px;
  padding-right: 3px;
  border: 3px solid grey;
  border-radius: 10px;
}

#city,
#weatherType,
#fTemp,
#windSpeed {
  transform: translateY(9%);
  background-color: #c6c6c4;
  border-bottom: 2px inset #FFF;
  border-right: 2px inset #FFF;
  border-radius: 5px;
  height: 30px;
  width: 90%;
  margin: auto;
  /*padding-bottom: 2px ;*/
}

.btn.btn-default {
  color: #0040ff;
  font-size: .80em;
  font-family: Orbitron, sans-serif;
  line-height: 2.45em;
}

@media(min-width: 500px) {
  .holder {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
  }
}

<title></title>

  <link href='https://fonts.googleapis.com/css?family=Orbitron' rel='stylesheet' type='text/css'>

Your Local Weather App

Here is my CodePen.

Body:
This is what you already have for wider screens:

@media (min-width: 500px) {
  .holder {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr 1fr;
  }
}

Add this for smaller screens, where you want your elements vertically stacked in one column:

.holder {
   display: grid;
   grid-template-columns: 1fr;
   grid-row-gap: 1em;
}

Revised CodePen

Grid provides grid-column-gap, grid-row-gap and grid-gap (the shorthand), which create space between grid items (but not between items and the container).

10.1. Gutters: the grid-column-gap, grid-row-gap, and
  grid-gap
  properties

These properties specify the gutters between grid rows and grid
  columns, respectively.


问:
javascript - missing array
I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. Values of all keys are zero.

Example: input objFromStr("aaabc") should return {a: 0, b: 0, c: 0}

Here is my solution:

```<code>function objFromStr(inStr) {
  let charsArr = inStr.split("");

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  return charsObj;
}
</code>```

This solution works as expected, but I don't understand why.
I check chars duplication using alreadyInArr. However when I log my alreadyInArr, it's empty.

So after running this code:

```<code>function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));
</code>```

My output is:

```<code>charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }
</code>```

Can someone explain, why alreadyInArr is empty and yet function still works as expected?

Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012

答:
As others have already stated, you are not allowing access to push to the array so you are constantly overwriting your object and assigning 0.

You can cut down your code with the following:

```<code>var arr = "aabbc", obj = {};

function objFromStr(inStr) {
    arr.split("").forEach(function(x){
        obj[x] !== undefined ? obj[x]++ : obj[x] = 1;
    });
    return obj;
}

console.log(objFromStr(arr));
</code>```

By doing it this way you don't have to push or track anything in a separate array. It will check the obj to see if the key already exists. If it does it will add 1 to it and if not then it will count it as 1.

Title: javascript - missing array

Body:
I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. Values of all keys are zero.

Example: input objFromStr("aaabc") should return {a: 0, b: 0, c: 0}

Here is my solution:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  return charsObj;
}

This solution works as expected, but I don't understand why.
I check chars duplication using alreadyInArr. However when I log my alreadyInArr, it's empty.

So after running this code:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));

My output is:

charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }

Can someone explain, why alreadyInArr is empty and yet function still works as expected?

Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012

Body:
As others have already stated, you are not allowing access to push to the array so you are constantly overwriting your object and assigning 0.

You can cut down your code with the following:

var arr = "aabbc", obj = {};

function objFromStr(inStr) {
    arr.split("").forEach(function(x){
        obj[x] !== undefined ? obj[x]++ : obj[x] = 1;
    });
    return obj;
}

console.log(objFromStr(arr));

By doing it this way you don't have to push or track anything in a separate array. It will check the obj to see if the key already exists. If it does it will add 1 to it and if not then it will count it as 1.


问:
#1111 - Invalid use of group function
I am using the following query in an attempt to get  total number(sum) of slides retrieving the max number from each project, however I am receiving the following error (#1111 - Invalid use of group function). Here's the query:

```<code>SELECT COALESCE(project,'Total') as Project, SUM(MAX(slides)) as Slides
FROM projects_tbl
WHERE date BETWEEN '2010-01-01' AND '2010-12-31'
GROUP BY Project with ROLLUP
</code>```

If I remove the SUM(), then the it works, however, I do not get an accurate total for all of the projects/slides.

Thanks in advance for any and all replies.

答:
You can try with something like:

```<code>SELECT sum(prjmax)
FROM
(SELECT COALESCE(project,'Total') as Project, MAX(slides) as prjmax
FROM projects_tbl
WHERE date BETWEEN '2010-01-01' AND '2010-12-31'
GROUP BY Project with ROLLUP)
</code>```

You need to obtain the max for each project, and after this you can sum all.

Title: #1111 - Invalid use of group function

Body:
I am using the following query in an attempt to get  total number(sum) of slides retrieving the max number from each project, however I am receiving the following error (#1111 - Invalid use of group function). Here's the query:

SELECT COALESCE(project,'Total') as Project, SUM(MAX(slides)) as Slides
FROM projects_tbl
WHERE date BETWEEN '2010-01-01' AND '2010-12-31'
GROUP BY Project with ROLLUP

If I remove the SUM(), then the it works, however, I do not get an accurate total for all of the projects/slides.

Thanks in advance for any and all replies.

Body:
You can try with something like:

SELECT sum(prjmax)
FROM
(SELECT COALESCE(project,'Total') as Project, MAX(slides) as prjmax
FROM projects_tbl
WHERE date BETWEEN '2010-01-01' AND '2010-12-31'
GROUP BY Project with ROLLUP)

You need to obtain the max for each project, and after this you can sum all.


问:
Maven not discovering ScalaTest unit tests
I have the following unit tests:

```<code>import org.scalatest.FunSpec
import org.scalatest.Matchers._

class MyClassSpec extends FunSpec {

  describe("MyClass"){
    describe("Scenario 1"){
      it("Condition 1") {
        true shouldEqual false
      }

      it("Condition 2"){
        true shouldEqual false
      }
    }
  }

}
</code>```

When I run maven test, this compiles fine but the tests are not found. Here is the output:

```<code>[INFO] --- maven-surefire-plugin:2.7:test (default-test) @ project-name ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- scalatest-maven-plugin:1.0:test (test) @ project-name ---
Discovery starting.
Discovery completed in 202 milliseconds.
Run starting. Expected test count is: 0
DiscoverySuite:
Run completed in 236 milliseconds.
Total number of tests run: 0
Suites: completed 1, aborted 0
Tests: succeeded 0, failed 0, canceled 0, ignored 0, pending 0
No tests were executed.
</code>```

As the output shows, I'm using the scalatest plugin for maven. Here is the relevant section of my pom.xml:

```<code><!-- disable surefire -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.7</version>
    <configuration>
        <skipTests>true</skipTests>
    </configuration>
</plugin>
<!-- enable scalatest -->
<plugin>
    <groupId>org.scalatest</groupId>
    <artifactId>scalatest-maven-plugin</artifactId>
    <version>1.0</version>
    <configuration>
        <reportsDirectory>${project.build.directory}/scalatest-reports</reportsDirectory>
        <junitxml>junit</junitxml>
        <filereports>report.txt</filereports>
    </configuration>
    <executions>
        <execution>
            <id>test</id>
            <goals>
                <goal>test</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

I'm pretty new to getting this stuff set up, so I'm not sure if there is some other thing I'm not checking. I get the exact same results if I run maven clean and then maven test. I'm using ScalaTest version 3.0.1. I have another project with tests running successfully also using 3.0.1 (I've copied everything I can find between the two projects that seems even remotely related).

答:
You have placed <skipTest> true </skipTest> which is used for skipping the test cases. So basically you have disabled the surefire and it is used for:

The Surefire Plugin is used during the test phase of the build
  lifecycle to execute the unit tests of an application. It generates
  reports in two different file formats Plain text files (.txt) XML
  files (.xml)

Update your pom with:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
       <useFile>false</useFile>
       <disableXmlReport>true</disableXmlReport>
       <!-- If you have classpath issue like NoDefClassError,...-->
       <!-- useManifestOnlyJar>false</useManifestOnlyJar -->
       <includes>
           <include>**/*Test.*</include>
            <include>**/*Suite.*</include>
            <include>**/*Spec.*</include>
       </includes>
     </configuration>
</plugin>
</code>```

In include you have to provide the extension of your test file and you can change the version of pluggin.

Thanks

Body:
I have the following unit tests:

import org.scalatest.FunSpec
import org.scalatest.Matchers._

class MyClassSpec extends FunSpec {

  describe("MyClass"){
    describe("Scenario 1"){
      it("Condition 1") {
        true shouldEqual false
      }

      it("Condition 2"){
        true shouldEqual false
      }
    }
  }

}

When I run maven test, this compiles fine but the tests are not found. Here is the output:

[INFO] --- maven-surefire-plugin:2.7:test (default-test) @ project-name ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- scalatest-maven-plugin:1.0:test (test) @ project-name ---
Discovery starting.
Discovery completed in 202 milliseconds.
Run starting. Expected test count is: 0
DiscoverySuite:
Run completed in 236 milliseconds.
Total number of tests run: 0
Suites: completed 1, aborted 0
Tests: succeeded 0, failed 0, canceled 0, ignored 0, pending 0
No tests were executed.

As the output shows, I'm using the scalatest plugin for maven. Here is the relevant section of my pom.xml:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.7</version>
    <configuration>
        <skipTests>true</skipTests>
    </configuration>
</plugin>

<plugin>
    <groupId>org.scalatest</groupId>
    <artifactId>scalatest-maven-plugin</artifactId>
    <version>1.0</version>
    <configuration>
        <reportsDirectory>${project.build.directory}/scalatest-reports</reportsDirectory>
        <junitxml>junit</junitxml>
        <filereports>report.txt</filereports>
    </configuration>
    <executions>
        <execution>
            <id>test</id>
            <goals>
                <goal>test</goal>
            </goals>
        </execution>
    </executions>
</plugin>

I'm pretty new to getting this stuff set up, so I'm not sure if there is some other thing I'm not checking. I get the exact same results if I run maven clean and then maven test. I'm using ScalaTest version 3.0.1. I have another project with tests running successfully also using 3.0.1 (I've copied everything I can find between the two projects that seems even remotely related).

Body:
You have placed <skipTest> true </skipTest> which is used for skipping the test cases. So basically you have disabled the surefire and it is used for:

The Surefire Plugin is used during the test phase of the build
  lifecycle to execute the unit tests of an application. It generates
  reports in two different file formats Plain text files (.txt) XML
  files (.xml)

Update your pom with:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
       <useFile>false</useFile>
       <disableXmlReport>true</disableXmlReport>
       <!-- If you have classpath issue like NoDefClassError,...-->
       <!-- useManifestOnlyJar>false</useManifestOnlyJar -->
       <includes>
           <include>**/*Test.*</include>
            <include>**/*Suite.*</include>
            <include>**/*Spec.*</include>
       </includes>
     </configuration>
</plugin>

In include you have to provide the extension of your test file and you can change the version of pluggin.

Thanks