问:
Using generic types within a foreach loop
I really cannot figure out how to use generic types with IEnumerable so that I can iterate through values contained by a given generic value.

Consider the following class (note that the classes here are only for example purposes):

```<code>public class Parameter<T> : IParameter<T> where T : IEnumerable<T>
{
  public List<UInt64> output = new List<UInt64>();

   private T _value;
   public T Value
   {
       get => ...;
       set
       {

           // I want to be able to apply special treat to the value
           // Value can be of any type: int, int[], bool, bool[]
           foreach (var v in value)
           {
               output.Add(Convert.UInt64(v) + 5);
           }

           ...

       }
   }
}

public interface IParameter<T> where T : IEnumerable<T>
{
   T Value { get; set; }
}
</code>```

I then have a test module that instantiate some parameters as per, but I cannot even compile here. I have even tried to replace bool[] to IEnumerable here below, but the compiler does not like it either.

```<code>public class TestModule : ModuleBase, ITestModule
{
    public IParameter<bool[]> Test1 { get; set; } = new Parameter<bool[]>();
    public IParameter<uint[]> Test2 { get; set; } = new Parameter<uint[]>();
    ...
    public IParameter<int> Test3 { get; set; } = new Parameter<int>();
}
</code>```

I did consider using overload for the Parameter() class, but I thought it to be overkill to create a class per supported type (considering it is only for the Value property).

答:
Your issue is that your generic parameter is specified incorrectly.

public class Parameter<T> : IParameter<T> where T : IEnumerable<T>

implies that whatever comes in of type T is an enumerable of the same type, meaning for instance a T of type bool[] should be an IEnumerable<bool[]> which is clearly incorrect.

One way to get it to compile is this:

```<code>    public class Parameter<TEnumerable, TType> : IParameter<TEnumerable, TType> where TEnumerable : IEnumerable<TType>
    {
        public List<ulong> output = new List<ulong>();

        private TEnumerable _value;
        public TEnumerable Value
        {
            get => { return null; }
            set
            {

                // I want to be able to apply special treat to the value
                // Value can be of any type: int, int[], bool, bool[]
                foreach (Q v in value)
                {
                    output.Add(Convert.ToUInt64(v) + 5);
                }
            }
        }
    }

    public interface IParameter<TEnumerable, TType> where TEnumerable : IEnumerable<TType>
    {
        TEnumerable Value { get; set; }
    }

    public class TestModule
    {
        public IParameter<bool[], bool> Test1 { get; set; } = new Parameter<bool[], bool>();
        public IParameter<uint[], uint> Test2 { get; set; } = new Parameter<uint[], uint>();
        public IParameter<int[], int> Test3 { get; set; } = new Parameter<int[], int>();
    }
</code>```

As for your additional comment, no, there's no way you can avoid having to specify the two types since IEnumerable is not a T in the form you've formulated your code. You have 2 separate parameters here and as such, you will have to use 2 generic parameters if you must do it the way you've done it.

A much simpler solution to your problem would be something like this which serves the same purpose more or less, although I don't really know your requirements so this may or may not suffice (interface omitted for clarity):

```<code>    public class Parameter<TType>
    {
        public List<ulong> output = new List<ulong>();

        private IEnumerable<TType> _value;
        public IEnumerable<TType> Value
        {
            get => { return null; }
            set
            {

                // I want to be able to apply special treat to the value
                // Value can be of any type: int, int[], bool, bool[]
                foreach (TType v in value)
                {
                    output.Add(Convert.ToUInt64(v) + 5);
                }
            }
        }
    }

    public class TestModule
    {
        public Parameter<bool> Test1 { get; set; } = new Parameter<bool>();
        public Parameter<uint> Test2 { get; set; } = new Parameter<uint>();
        public Parameter<int> Test3 { get; set; } = new Parameter<int>();
    }
</code>```

Body:
I really cannot figure out how to use generic types with IEnumerable so that I can iterate through values contained by a given generic value.

Consider the following class (note that the classes here are only for example purposes):

public class Parameter<T> : IParameter<T> where T : IEnumerable<T>
{
  public List<UInt64> output = new List<UInt64>();

   private T _value;
   public T Value
   {
       get => ...;
       set
       {

           // I want to be able to apply special treat to the value
           // Value can be of any type: int, int[], bool, bool[]
           foreach (var v in value)
           {
               output.Add(Convert.UInt64(v) + 5);
           }

           ...

       }
   }
}

public interface IParameter<T> where T : IEnumerable<T>
{
   T Value { get; set; }
}

I then have a test module that instantiate some parameters as per, but I cannot even compile here. I have even tried to replace bool[] to IEnumerable here below, but the compiler does not like it either.

public class TestModule : ModuleBase, ITestModule
{
    public IParameter<bool[]> Test1 { get; set; } = new Parameter<bool[]>();
    public IParameter<uint[]> Test2 { get; set; } = new Parameter<uint[]>();
    ...
    public IParameter<int> Test3 { get; set; } = new Parameter<int>();
}

I did consider using overload for the Parameter() class, but I thought it to be overkill to create a class per supported type (considering it is only for the Value property).

Body:
Your issue is that your generic parameter is specified incorrectly.

public class Parameter<T> : IParameter<T> where T : IEnumerable<T>

implies that whatever comes in of type T is an enumerable of the same type, meaning for instance a T of type bool[] should be an IEnumerable<bool[]> which is clearly incorrect.

One way to get it to compile is this:

    public class Parameter<TEnumerable, TType> : IParameter<TEnumerable, TType> where TEnumerable : IEnumerable<TType>
    {
        public List<ulong> output = new List<ulong>();

        private TEnumerable _value;
        public TEnumerable Value
        {
            get => { return null; }
            set
            {

                // I want to be able to apply special treat to the value
                // Value can be of any type: int, int[], bool, bool[]
                foreach (Q v in value)
                {
                    output.Add(Convert.ToUInt64(v) + 5);
                }
            }
        }
    }

    public interface IParameter<TEnumerable, TType> where TEnumerable : IEnumerable<TType>
    {
        TEnumerable Value { get; set; }
    }

    public class TestModule
    {
        public IParameter<bool[], bool> Test1 { get; set; } = new Parameter<bool[], bool>();
        public IParameter<uint[], uint> Test2 { get; set; } = new Parameter<uint[], uint>();
        public IParameter<int[], int> Test3 { get; set; } = new Parameter<int[], int>();
    }

As for your additional comment, no, there's no way you can avoid having to specify the two types since IEnumerable is not a T in the form you've formulated your code. You have 2 separate parameters here and as such, you will have to use 2 generic parameters if you must do it the way you've done it.

A much simpler solution to your problem would be something like this which serves the same purpose more or less, although I don't really know your requirements so this may or may not suffice (interface omitted for clarity):

    public class Parameter<TType>
    {
        public List<ulong> output = new List<ulong>();

        private IEnumerable<TType> _value;
        public IEnumerable<TType> Value
        {
            get => { return null; }
            set
            {

                // I want to be able to apply special treat to the value
                // Value can be of any type: int, int[], bool, bool[]
                foreach (TType v in value)
                {
                    output.Add(Convert.ToUInt64(v) + 5);
                }
            }
        }
    }

    public class TestModule
    {
        public Parameter<bool> Test1 { get; set; } = new Parameter<bool>();
        public Parameter<uint> Test2 { get; set; } = new Parameter<uint>();
        public Parameter<int> Test3 { get; set; } = new Parameter<int>();
    }


来源: stackexchange

问:
VueJs 'filter is not a function' problem in Vuex getter
I'm completely new to frontend development and Vue js. I want to involve a state managment in my application. I can set the state with the response from my API but when I want to filter the results in getter using filter function (getActiveLeagues) I get an error that 'filter is not a function' as if the result was not an array but I think I declared my state with as an array:

```<code>const state = {
  leagues: [],
};

const getters = {
  getAllLeagues: (state) => state.leagues,
  getActiveLeagues: (state) => state.leagues.filter((league) => league.archivated === false),
};

const actions = {

  async getAllLeagues({ commit }) {
    const response = await axios.get(`${server.baseURL}/api/league`);
    console.log(response);
    commit('setLeagues', response);
  },
};

const mutations = {
  setLeagues(state, leagues) {
    state.leagues = leagues;
  },
};

export default {
  state,
  getters,
  actions,
  mutations,
};
</code>```

and I get an array from API:

Here is how my Vuex.Store call look like:

```<code>import Vue from 'vue';
import Vuex from 'vuex';
import posts from './modules/postModule';
import leagues from './modules/leagueModule';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    posts,
    leagues,
  },
});
</code>```

And the result of state watch:

Probably it's a stupid problem cause i'm new to this but I can't see what is wrong at the moment.
Thanks for any help.

答:
I actually haven't used modules and am not sure how it works compared to flat state. Best thing is to console.log(state) inside the getter to get a better view.

One thing I notice, compared to the docs, is you're not declaring state as a function in the module. E.g.:

```<code>const state = () => ({
  leagues: [],
});
</code>```

Reference: https://vuex.vuejs.org/guide/modules.html

EDIT (in response to your new screenshot)

It looks like state.leagues.leagues what you're looking for (thanks to module namespacing I guess?), but even that is not an array, it's an object with data property that is an array.

So start with this:

```<code>commit('setLeagues', response.data);
</code>```

I think your module state should be receiving it's namespaced substate already, so you shouldn't have to modify anything else. But if it's still broken, try this as well, I'm curious:

```<code>getActiveLeagues: (state) => state.leagues.leagues.filter((league) => league.archivated === false),
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm completely new to frontend development and Vue js. I want to involve a state managment in my application. I can set the state with the response from my API but when I want to filter the results in getter using filter function (getActiveLeagues) I get an error that 'filter is not a function' as if the result was not an array but I think I declared my state with as an array:

const state = {
  leagues: [],
};

const getters = {
  getAllLeagues: (state) => state.leagues,
  getActiveLeagues: (state) => state.leagues.filter((league) => league.archivated === false),
};

const actions = {

  async getAllLeagues({ commit }) {
    const response = await axios.get(`${server.baseURL}/api/league`);
    console.log(response);
    commit('setLeagues', response);
  },
};

const mutations = {
  setLeagues(state, leagues) {
    state.leagues = leagues;
  },
};

export default {
  state,
  getters,
  actions,
  mutations,
};

and I get an array from API:

Here is how my Vuex.Store call look like:

import Vue from 'vue';
import Vuex from 'vuex';
import posts from './modules/postModule';
import leagues from './modules/leagueModule';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    posts,
    leagues,
  },
});

And the result of state watch:

Probably it's a stupid problem cause i'm new to this but I can't see what is wrong at the moment.
Thanks for any help.

Body:
I actually haven't used modules and am not sure how it works compared to flat state. Best thing is to console.log(state) inside the getter to get a better view.

One thing I notice, compared to the docs, is you're not declaring state as a function in the module. E.g.:

const state = () => ({
  leagues: [],
});

Reference: https://vuex.vuejs.org/guide/modules.html

EDIT (in response to your new screenshot)

It looks like state.leagues.leagues what you're looking for (thanks to module namespacing I guess?), but even that is not an array, it's an object with data property that is an array.

So start with this:

commit('setLeagues', response.data);

I think your module state should be receiving it's namespaced substate already, so you shouldn't have to modify anything else. But if it's still broken, try this as well, I'm curious:

getActiveLeagues: (state) => state.leagues.leagues.filter((league) => league.archivated === false),


问:
Communication between the View and Model in MVC
After reading from many different sources, I am very confused about how View and Model should communicate in the MVC pattern. To my understanding, the accepted answer of this post and this article from Apple are saying the communication of the two should be done through controller. While the MVC page in Wikipedia, the ASP.NET MVC page, and this article in MSDN are showing there is a direct association between View and Model. So according to the answer in here, what the article from Apple is referring to is actually MVP not MVC then? Thank you for any help!!</p>

答:
There is more than one answer.
Eventually you can do whatever you thing suits your needs.
I use a controller + ViewModels to connect to the view.
The view never use the model. just what the controller gives him.

There is a nice explanation of all models in steven sandarson book, Page 49
(variation on MVC).

ContentLicense: CC BY-SA 3.0


Title: Python Feature Engineer Movement Data

Body:
Hi I'm trying to feature engineer a Patient dataset from movement level to patient level.

Original df looks like this:

Conditions:

1) Create Last Test<n> Change cols - For CaseNo that encounters the Category value 'ICU', take the Test<n> change before 'ICU' value (189-180 for Test1, CaseNo 1), else take the latest Test<n> change (256-266 for Test1, CaseNo 2).

2) Create Test<n>_Pattern cols - For CaseNo that encounters the Category value 'ICU', pivot all the Test<n> values from start till before 'ICU' value. Else pivot all Test<n> values from start to end.

3)Create Last Test<n> Count cols - For CaseNo that encounters the Category value 'ICU', take the last Test<n> value before 'ICU' encounter. Else take the last Test<n> value.

Expected Outcome:

How do I go about this in Python?

Code for df:

df = pd.DataFrame({'CaseNo':[1,1,1,1,2,2,2,2],
                    'Movement_Sequence_No':[1,2,3,4,1,2,3,4],
                    'Movement_Start_Date':['2020-02-09 22:17:00','2020-02-10 17:19:41','2020-02-17 08:04:19',
                                           '2020-02-18 11:22:52','2020-02-12 23:00:00','2020-02-24 10:26:35',
                                           '2020-03-03 17:50:00','2020-03-17 08:24:19'],
                    'Movement_End_Date':['2020-02-10 17:19:41','2020-02-17 08:04:19','2020-02-18 11:22:52',
                                         '2020-02-25 13:55:37','2020-02-24 10:26:35','2020-03-03 17:50:00',
                                         '2222-12-31 23:00:00','2020-03-18 18:50:00'],
                    'Category':['A','A','ICU','A','B','B','B','B'],
                    'RequestDate':['2020-02-10 16:00:00','2020-02-16 13:04:20','2020-02-18 07:11:11','2020-02-21 21:30:30',
                                   '2020-02-13 22:00:00','NA','2020-03-15 09:40:00','2020-03-18 15:10:10'],
                    'Test1':['180','189','190','188','328','NA','266','256'],
                    'Test2':['20','21','15','10','33','30','28','15'],
                    'Test3':['55','NA','65','70','58','64','68','58'],
                    'Age':['65','65','65','65','45','45','45','45']})

Expected Outcome:

df2 = pd.DataFrame({'CaseNo':[1, 2],
                    'Last Test1 Change':[9, -10],
                    'Test1 Pattern':['180, 189', '328, 266, 256'],
                    'Last Test1 Count':[189, 256],
                    'Last Test2 Change':[1, -13],
                    'Test2 Pattern':['20, 21', '33, 30, 28, 15'],
                    'Last Test2 Count':[21, 15],
                    'Last Test3 Change':[10, -10],
                    'Test3 Pattern':['55', '58, 64, 68, 58'],
                    'Last Test3 Count':[55, 58],
                    'Age':[65, 45]})

Body:
try in this way:

df = pd.DataFrame({'CaseNo':[1,1,1,1,2,2,2,2],
                    'Movement_Sequence_No':[1,2,3,4,1,2,3,4],
                    'Movement_Start_Date':['2020-02-09 22:17:00','2020-02-10 17:19:41','2020-02-17 08:04:19',
                                           '2020-02-18 11:22:52','2020-02-12 23:00:00','2020-02-24 10:26:35',
                                           '2020-03-03 17:50:00','2020-03-17 08:24:19'],
                    'Movement_End_Date':['2020-02-10 17:19:41','2020-02-17 08:04:19','2020-02-18 11:22:52',
                                         '2020-02-25 13:55:37','2020-02-24 10:26:35','2020-03-03 17:50:00',
                                         '2222-12-31 23:00:00','2020-03-18 18:50:00'],
                    'Category':['A','A','ICU','A','B','B','B','B'],
                    'RequestDate':['2020-02-10 16:00:00','2020-02-16 13:04:20','2020-02-18 07:11:11','2020-02-21 21:30:30',
                                   '2020-02-13 22:00:00','NA','2020-03-15 09:40:00','2020-03-18 15:10:10'],
                    'Test1':['180','189','190','188','328','NA','266','256'],
                    'Test2':['20','21','15','10','33','30','28','15'],
                    'Test3':['55','NA','65','70','58','64','68','58'],
                    'Age':['65','65','65','65','45','45','45','45']})

# simple data management
df = df.replace('NA', np.nan)
df[['Test1','Test2','Test3','Age']] = df[['Test1','Test2','Test3','Age']].astype(float)

# create empty df to store results
results = pd.DataFrame()

# split original df in groups based on CaseNo
for jj,(j,gr) in enumerate(df.groupby('CaseNo')):

    group = gr.copy()
    # idenfify the presence of ICU
    group['Category'] = (group['Category'].values == 'ICU').cumsum()
    # replace NaN value with the next useful value
    # this is useful to fill NaN in Test1, Test2, Test3
    group_fill = group.fillna(method='bfill')
    # select part of df before the first ICU matched
    group_fill = group_fill[group_fill.Category == 0]
    group = group[group.Category == 0]
    # at this point we have two copy of our group df (group and group_fill)
    # group contains the raw (inclused NaN) values for a selected CaseNo
    # group_fill contains the filled values for a selected CaseNo

    # create empty df to store partial results
    partial = pd.DataFrame()
    # select unique CaseNo
    partial['CaseNo'] = group['CaseNo'].unique()

    # for loop to make operation on Test1, Test2 and Test3
    for i in range(1,4):

        # these are simply the operation you required
        # NB: 'Last TestN Change' is computed on the group df without NaN
        # this is important to avoid errors when the last obsevarion is NaN
        # 'TestN Pattern' and 'Last TestN Count' can be computed on the filled group df
        partial[f'Last Test{i} Change'] = group_fill[f'Test{i}'].tail(2).diff().tail(1).values
        partial[f'Test{i} Pattern'] = [group[f'Test{i}'].dropna().to_list()]
        partial[f'Last Test{i} Count'] = group[f'Test{i}'].dropna().tail(1).values

    # select unique age
    partial['Age'] = group['Age'].unique()
    # create correct index for the final results
    partial.index = range(jj,jj+1)
    # append partial results to final results df
    results = results.append(partial)

# print final results df
results


问:
ASP.NET Core get user not working when deployed to IIS and launch in browser
This is not a duplicate question ( as far as I researched ). My problem is everything works nice when I run ASP.NET Core 2.1 MVC application in VS 2019 but when I deploy to local IIS and launch my application in browser it is not working. My operating system is Windows 10.

I have below turned on in IIS

I am doing below to get username of person who launched my ASP.NET Core 2.1 MVC application in browser.

In Properties -> launchSettings.json

```<code>"windowsAuthentication": true,
 "anonymousAuthentication": false,
</code>```

In Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
</code>```

In Helper.cs

```<code>public static string GetUserName(IHttpContextAccessor httpContextAccessor)
{
  string userName = string.Empty;
  if(httpContextAccessor != null &&
     httpContextAccessor.HttpContext != null &&
     httpContextAccessor.HttpContext.User != null &&
     httpContextAccessor.HttpContext.User.Identity != null)
    {
        userName = httpContextAccessor.HttpContext.User.Identity.Name;
        string[] usernames = userName.Split('\\');
        userName = usernames[1].ToUpper();
    }
        return userName;
}
</code>```

In MyController.cs

```<code>public class MyController : Controller
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MyController(IHttpContextAccessor httpContextAccessor)
    {
      _httpContextAccessor = httpContextAccessor;
    }

    [HttpPost]
    public JsonResult CreateOrder([FromBody] OrderModel model)
    {
      string username = Helper.GetUserName(_httpContextAccessor);
      .....
    }
}
</code>```

When I run my application in VS 2019 everything is fine but when I publish my application to IIS and launch my application in browser I get error due to httpContextAccessor.HttpContext.User.Identity.Name  null.

I also tried various ways like FindFirst using Claims but all those work good when I run in VS 2019 but not publish my application to IIS and launch my application in browser. What mistake I am doing.

Thanks in advance.

答:
Huge thanks to @Ziggler for his answer. Almost all research I came across suggested modifying the web.config and launchSettings.json as well as Enable Windows Authentication and Disable the Anonymous Authentication in the IIS configuration screen which all did not fix the issue. The below did fix my issue...

Pulled the windows authenticated username out and cleaned it up before returning the value

```<code> public class Helper : IHelper{

    private readonly ILogger<Helper> _logger;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public Helper(ILogger<Helper> logger, IHttpContextAccessor httpContextAccessor) {
        _logger = logger;
        _httpContextAccessor = httpContextAccessor;
    }

    public int GetSSO()
    {
        try
        {
            //Remove DSM
            string temp = Regex.Replace(_httpContextAccessor.HttpContext.User.Identity.Name, @"[DSM]", "");
            //Remove special characters
            temp = Regex.Replace(temp, @"[^\w\.@-]", "");
            //Convert string to int
            int sso = Int32.Parse(temp);

            return sso;
        }
        catch (Exception e)
        {
            _logger.LogError("::::Error Getting SSO:::: " + e);
            return 000000000;
        }
    }
</code>```

Body:
This is not a duplicate question ( as far as I researched ). My problem is everything works nice when I run ASP.NET Core 2.1 MVC application in VS 2019 but when I deploy to local IIS and launch my application in browser it is not working. My operating system is Windows 10.

I have below turned on in IIS

I am doing below to get username of person who launched my ASP.NET Core 2.1 MVC application in browser.

In Properties -> launchSettings.json

"windowsAuthentication": true,
 "anonymousAuthentication": false,

In Startup.cs

public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

In Helper.cs

public static string GetUserName(IHttpContextAccessor httpContextAccessor)
{
  string userName = string.Empty;
  if(httpContextAccessor != null &&
     httpContextAccessor.HttpContext != null &&
     httpContextAccessor.HttpContext.User != null &&
     httpContextAccessor.HttpContext.User.Identity != null)
    {
        userName = httpContextAccessor.HttpContext.User.Identity.Name;
        string[] usernames = userName.Split('\\');
        userName = usernames[1].ToUpper();
    }
        return userName;
}

In MyController.cs

public class MyController : Controller
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MyController(IHttpContextAccessor httpContextAccessor)
    {
      _httpContextAccessor = httpContextAccessor;
    }

    [HttpPost]
    public JsonResult CreateOrder([FromBody] OrderModel model)
    {
      string username = Helper.GetUserName(_httpContextAccessor);
      .....
    }
}

When I run my application in VS 2019 everything is fine but when I publish my application to IIS and launch my application in browser I get error due to httpContextAccessor.HttpContext.User.Identity.Name  null.

I also tried various ways like FindFirst using Claims but all those work good when I run in VS 2019 but not publish my application to IIS and launch my application in browser. What mistake I am doing.

Thanks in advance.

Body:
Huge thanks to @Ziggler for his answer. Almost all research I came across suggested modifying the web.config and launchSettings.json as well as Enable Windows Authentication and Disable the Anonymous Authentication in the IIS configuration screen which all did not fix the issue. The below did fix my issue...

Pulled the windows authenticated username out and cleaned it up before returning the value

 public class Helper : IHelper{

    private readonly ILogger<Helper> _logger;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public Helper(ILogger<Helper> logger, IHttpContextAccessor httpContextAccessor) {
        _logger = logger;
        _httpContextAccessor = httpContextAccessor;
    }

    public int GetSSO()
    {
        try
        {
            //Remove DSM
            string temp = Regex.Replace(_httpContextAccessor.HttpContext.User.Identity.Name, @"[DSM]", "");
            //Remove special characters
            temp = Regex.Replace(temp, @"[^\w\.@-]", "");
            //Convert string to int
            int sso = Int32.Parse(temp);

            return sso;
        }
        catch (Exception e)
        {
            _logger.LogError("::::Error Getting SSO:::: " + e);
            return 000000000;
        }
    }


问:
sqlite3 RuntimeError: no such table: main.user
So I've made a new table called 'buy' in my finance database file. It's to store the user's buying history. I want to insert the data into the new table that I've made but it keeps giving me this Runtime Error that says -

no such table : main.user

but the table I want to insert is 'buy'.

Does anybody know what's causing this error?

```<code>import os

from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash

from helpers import apology, login_required, lookup, usd

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

# Custom filter
app.jinja_env.filters["usd"] = usd

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")

# Make sure API key is set
if not os.environ.get("API_KEY"):
    raise RuntimeError("API_KEY not set")

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    return apology("TODO")

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""

    # User reached route via GET
    if request.method == "GET":
        return render_template("buy.html")

    # User reached route via POST
    else:

        # Ensures the user inputs symbol and number if shares of a company
        if not request.form.get("symbol"):
            return apology("must provide symbol", 403)
        elif not request.form.get("shares"):
            return apology("must provide number of shares", 403)

        # Checks if the symbol is valid
        if not lookup(request.form.get("symbol")):
            return apology("symbol not valid", 403)

        # Queries the data of the user for their balance
        current = db.execute("SELECT cash FROM users WHERE id=:user", user=session["user_id"])

        # Extracts the number of shares the user wants to buy
        quantity = int(request.form.get("shares"))

        # Finds the quote of the holdings based on the symbol the user wants to buy from
        quote = lookup(request.form.get("symbol"))

        # Calculates the cost of the shares according to current price of shares
        cost = quote["price"] * quantity

        # Checks if user has enough money
        if cost > current[0]["cash"]:
            return apology("price of shares exceed cash owned", 403)

        # Error occured here!
        db.execute("INSERT INTO buy (user_id, holdings, quantity, time) VALUES (:user_id, :holdings, :quantity, datetime('now'));",
                  user_id=session["user_id"],
                  holdings=quote["symbol"],
                  quantity=quantity)

        return redirect("/")

@app.route("/history")
@login_required
def history():
    """Show history of transactions"""
    return apology("TODO")

@app.route("/login", methods=["GET", "POST"])
def login():
    """Log user in"""

    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # Query database for username
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

        # Ensure username exists and password is correct
        if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
            return apology("invalid username and/or password", 403)

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # Redirect user to home page
        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")

@app.route("/logout")
def logout():
    """Log user out"""

    # Forget any user_id
    session.clear()

    # Redirect user to login form
    return redirect("/")

@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
    """Get stock quote."""

    # User reached route via POST (submitting symbol)
    if request.method == "POST":

        # Looks up for the information of a company's shares according to symbol
        info = lookup(request.form.get("symbol"))

        # Checks if the symbol is valid
        if info:

            # renders a new template with the corresponding stock quote
            return render_template("quoted.html", info=info)

        else:
            return apology("invalid symbol", 403)

    # User reached route via GET
    else:
        return render_template("quote.html")

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""

    # User reached route via POST (submitting data to be registered)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # Ensure confirmation password was submitted
        elif not request.form.get("confirmation"):
            return apology("must provide confirmation password", 403)

        # Query database for existing username
        name = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

        # Ensures if username is not yet taken
        if len(name) == 1:
            return apology("username already exists", 403)

        # Checks if both passwords match
        if request.form.get("password") != request.form.get("confirmation"):
            return apology("passwords do not match", 403)

        # Inserts new user into database
        db.execute("INSERT INTO users (username, hash) VALUES (:username, :password)",
                   username=request.form.get("username"), password=generate_password_hash(request.form.get("password")))

        return redirect("/")

    # User reached route via GET
    else:
        return render_template("register.html")

@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""
    return apology("TODO")

def errorhandler(e):
    """Handle error"""
    if not isinstance(e, HTTPException):
        e = InternalServerError()
    return apology(e.name, e.code)

# Listen for errors
for code in default_exceptions:
    app.errorhandler(code)(errorhandler)
</code>```

答:
Maybe You need to call

```<code>> sqlite database/finance.db
</code>```

Next you execute python in your console

```<code>>python
from app import db
db.create_all()
</code>```

If this doesnt work, one case its that you need to create the table with a class (this is the case with  sqlite3 and SQLALchemy)

Body:
So I've made a new table called 'buy' in my finance database file. It's to store the user's buying history. I want to insert the data into the new table that I've made but it keeps giving me this Runtime Error that says -

no such table : main.user

but the table I want to insert is 'buy'.

Does anybody know what's causing this error?

import os

from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash

from helpers import apology, login_required, lookup, usd

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

# Custom filter
app.jinja_env.filters["usd"] = usd

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")

# Make sure API key is set
if not os.environ.get("API_KEY"):
    raise RuntimeError("API_KEY not set")

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    return apology("TODO")

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""

    # User reached route via GET
    if request.method == "GET":
        return render_template("buy.html")

    # User reached route via POST
    else:

        # Ensures the user inputs symbol and number if shares of a company
        if not request.form.get("symbol"):
            return apology("must provide symbol", 403)
        elif not request.form.get("shares"):
            return apology("must provide number of shares", 403)

        # Checks if the symbol is valid
        if not lookup(request.form.get("symbol")):
            return apology("symbol not valid", 403)

        # Queries the data of the user for their balance
        current = db.execute("SELECT cash FROM users WHERE id=:user", user=session["user_id"])

        # Extracts the number of shares the user wants to buy
        quantity = int(request.form.get("shares"))

        # Finds the quote of the holdings based on the symbol the user wants to buy from
        quote = lookup(request.form.get("symbol"))

        # Calculates the cost of the shares according to current price of shares
        cost = quote["price"] * quantity

        # Checks if user has enough money
        if cost > current[0]["cash"]:
            return apology("price of shares exceed cash owned", 403)

        # Error occured here!
        db.execute("INSERT INTO buy (user_id, holdings, quantity, time) VALUES (:user_id, :holdings, :quantity, datetime('now'));",
                  user_id=session["user_id"],
                  holdings=quote["symbol"],
                  quantity=quantity)

        return redirect("/")

@app.route("/history")
@login_required
def history():
    """Show history of transactions"""
    return apology("TODO")

@app.route("/login", methods=["GET", "POST"])
def login():
    """Log user in"""

    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # Query database for username
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

        # Ensure username exists and password is correct
        if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
            return apology("invalid username and/or password", 403)

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # Redirect user to home page
        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")

@app.route("/logout")
def logout():
    """Log user out"""

    # Forget any user_id
    session.clear()

    # Redirect user to login form
    return redirect("/")

@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
    """Get stock quote."""

    # User reached route via POST (submitting symbol)
    if request.method == "POST":

        # Looks up for the information of a company's shares according to symbol
        info = lookup(request.form.get("symbol"))

        # Checks if the symbol is valid
        if info:

            # renders a new template with the corresponding stock quote
            return render_template("quoted.html", info=info)

        else:
            return apology("invalid symbol", 403)

    # User reached route via GET
    else:
        return render_template("quote.html")

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""

    # User reached route via POST (submitting data to be registered)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # Ensure confirmation password was submitted
        elif not request.form.get("confirmation"):
            return apology("must provide confirmation password", 403)

        # Query database for existing username
        name = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

        # Ensures if username is not yet taken
        if len(name) == 1:
            return apology("username already exists", 403)

        # Checks if both passwords match
        if request.form.get("password") != request.form.get("confirmation"):
            return apology("passwords do not match", 403)

        # Inserts new user into database
        db.execute("INSERT INTO users (username, hash) VALUES (:username, :password)",
                   username=request.form.get("username"), password=generate_password_hash(request.form.get("password")))

        return redirect("/")

    # User reached route via GET
    else:
        return render_template("register.html")

@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""
    return apology("TODO")

def errorhandler(e):
    """Handle error"""
    if not isinstance(e, HTTPException):
        e = InternalServerError()
    return apology(e.name, e.code)

# Listen for errors
for code in default_exceptions:
    app.errorhandler(code)(errorhandler)

Body:
Maybe You need to call

> sqlite database/finance.db

Next you execute python in your console

>python
from app import db
db.create_all()

If this doesnt work, one case its that you need to create the table with a class (this is the case with  sqlite3 and SQLALchemy)


问:
Jsoup: "Which span does this element belong to?"
Assuming I have found an element using:

```<code>Element link = div.select("a:not([class])").first();
</code>```

I now want to find out whether this particular element is enclosed within a  -- not necessarily a direct descendant.

Is there a way to do that in Jsoup?

Update: I just found the wonderful Element.parent(). I am going to check whether this can be a start...

答:
That's not directly possible from the Element link on. I'd suggest to collect all links in a span.uniqspan first and then check if it contains the link.

E.g.

```<code>Element link = div.select("a:not([class])").first();
Elements linksInUniqspan = document.select("span.uniqspan a:not([class])");

if (linksInUniqspan.contains(link)) {
    // Link is inside span.uniqspan.
} else {
    // Link is not inside span.uniqspan.
}
</code>```

Body:
Assuming I have found an element using:

Element link = div.select("a:not([class])").first();

I now want to find out whether this particular element is enclosed within a  -- not necessarily a direct descendant.

Is there a way to do that in Jsoup?

Update: I just found the wonderful Element.parent(). I am going to check whether this can be a start...

Body:
That's not directly possible from the Element link on. I'd suggest to collect all links in a span.uniqspan first and then check if it contains the link.

E.g.

Element link = div.select("a:not([class])").first();
Elements linksInUniqspan = document.select("span.uniqspan a:not([class])");

if (linksInUniqspan.contains(link)) {
    // Link is inside span.uniqspan.
} else {
    // Link is not inside span.uniqspan.
}


问:
Prevent inverted Flatlist from scrolling to bottom when new items are added
I am building a chat app, using an inverted Flatlist. I add new items to the top of the list when onEndReached is called and everything works fine.

The problem is that if add items to the bottom, it instantly scrolls to the bottom of the list. That means that the user has to scroll back up to read the messages that were just added (which is terrible).

I tried to call scrollToOffset in onContentSizeChange, but this has a one-second delay where the scroll jumps back and forth.

How can I have the list behave the same way when I add items to the top AND to the bottom, by keeping the same messages on screen instead of showing the new ones?

答:
here is demo: https://snack.expo.io/@nomi9995/flatlisttest

Solution 1:

use maintainVisibleContentPosition props for preventing auto scroll in IOS but unfortunately, it's not working on android. but here is PR for android Pull Request. before merge this PR you can patch by own from this PR

```<code><FlatList
  ref={(ref) => { this.chatFlatList = ref; }}
  style={styles.flatList}
  data={this.state.items}
  renderItem={this._renderItem}
  maintainVisibleContentPosition={{
     minIndexForVisible: 0,
  }}
/>
</code>```

Solution 2:

I found another workaround by keep latest y offset with onScroll and also save content height before and after adding new items with onContentSizeChange and calculate the difference of content height, and set new y offset to the latest y offset + content height difference!

Body:
here is demo: https://snack.expo.io/@nomi9995/flatlisttest

Solution 1:

use maintainVisibleContentPosition props for preventing auto scroll in IOS but unfortunately, it's not working on android. but here is PR for android Pull Request. before merge this PR you can patch by own from this PR

<FlatList
  ref={(ref) => { this.chatFlatList = ref; }}
  style={styles.flatList}
  data={this.state.items}
  renderItem={this._renderItem}
  maintainVisibleContentPosition={{
     minIndexForVisible: 0,
  }}
/>

Solution 2:

I found another workaround by keep latest y offset with onScroll and also save content height before and after adding new items with onContentSizeChange and calculate the difference of content height, and set new y offset to the latest y offset + content height difference!


问:
How can I open a .json.gz format file in R?
I am a Data Science student writing my thesis using product review data. However, this is packed in a .gz file.

The file name when downloaded is 'xxx.json.gz' and when I look into the properties it says the type of file is gz Archive (.gz), Opens with 7-Zip File Manager.

I found the following code:

```<code>z <- gzfile("xxx.json.gz")
data = read.csv(z)
</code>```

But the object 'data' is now a list. All columns are factors and the column with the review text is not right at all. I think the read.csv() part is wrong since it's supposed to be a json file.

Does anyone have solution? I also have the URL address of the data if that's better to use: http://deepyeti.ucsd.edu/jianmo/amazon/categoryFilesSmall/Electronics_5.json.gz

答:
Loading it at the moment, I got 5,152,500 records right now, it is probably the review text that is clogging it up </p>

```<code>library(jsonlite)
happy_data <-stream_in(
gzcon(
   url("http://deepyeti.ucsd.edu/jianmo/amazon/categoryFilesSmall/Electronics_5.json.gz")
 )
                       )
</code>```

Body:
I am a Data Science student writing my thesis using product review data. However, this is packed in a .gz file.

The file name when downloaded is 'xxx.json.gz' and when I look into the properties it says the type of file is gz Archive (.gz), Opens with 7-Zip File Manager.

I found the following code:

z <- gzfile("xxx.json.gz")
data = read.csv(z)

But the object 'data' is now a list. All columns are factors and the column with the review text is not right at all. I think the read.csv() part is wrong since it's supposed to be a json file.

Does anyone have solution? I also have the URL address of the data if that's better to use: http://deepyeti.ucsd.edu/jianmo/amazon/categoryFilesSmall/Electronics_5.json.gz

Body:
Loading it at the moment, I got 5,152,500 records right now, it is probably the review text that is clogging it up

library(jsonlite)
happy_data <-stream_in(
gzcon(
   url("http://deepyeti.ucsd.edu/jianmo/amazon/categoryFilesSmall/Electronics_5.json.gz")
 )
                       )


问:
Disable Airplay with allowsExternalPlayback but audio is still playing
I've disabled Airplay with allowsExternalPlayback , the video on AVPlayer is finished but audio is still playing .
   Please, help me, I tried to find solution with the help of google but I am not able to solve this problem:(</p>

答: This is expected behaviour as you can also use it to define what audio-output should be used e.G. bluetooth, headphones, speakers and so on...</p>


问:
DATEDIFF between two dates to return timestamp
SOLVED

```<code>CONCAT((DATEDIFF(Minute,START_DTTM,END_DTTM)/60),'h:',
       (DATEDIFF(Minute,START_DTTM,END_DTTM)%60) 'm') AS TotalTimeMissing
</code>```

Produces TotalTimeMissing: 5h:13m

________

I'm trying to return a timestamp value between two specific dates to work out the time between a package going missing and it being found.

EDIT: Code has been updated to include code from Sami. I have also added additional code that I excluded from the original.

Here is the current code:

```<code>USE PACKAGE

GO

SELECT

        dp.LEGACY_ID

       ,dp.SURNAME

       ,dp.FORENAME

       ,dp.ETHNICITY_DESCRIPTION

       ,dp.BIRTH_DTTM

       ,DATEDIFF(YY, dp.BIRTH_DTTM, GETDATE()) -

            CASE

                  WHEN RIGHT(CONVERT(VARCHAR(6), GETDATE(), 12), 4) >=

                        RIGHT(CONVERT(VARCHAR(6), dp.BIRTH_DTTM, 12), 4)

                        THEN 0

                  ELSE 1

            END AS [Current Age]

--^Precise age calc due to potential LL inaccuracy

       ,mp.DIM_PERSON_ID

       ,mp.MISSING_STATUS

       ,mp.START_DTTM

       ,mp.END_DTTM

       ,dp.LEGACY_ID

       ,mp.RETURN_INT_OFFERED

       ,mp.RETURN_INT_ACCEPTED

       ,mp.RETURN_INT_DATE

FROM C_S.FACT_MISSING_PACKAGE AS mp

JOIN C_S.FACT_MISSING_PACKAGE AS dp ON mp.DIM_PERSON_ID = dp.DIM_PERSON_ID

WHERE CAST (mp.START_DTTM AS DATE)

              BETWEEN DATEADD(YY, -1, CAST (GETDATE() AS DATE)) AND CAST (GETDATE() AS DATE)

--^Displays all records within exactly 1 year of run date

       UNION (SELECT CONCAT(Value / 3600 / 24,

              ' Days ',

              RIGHT(CONCAT('00', Value / 3600 % 24), 2),

              ':',

              RIGHT(CONCAT('00', Value / 60 % 60), 2),

              ':',

              RIGHT(CONCAT('00',Value % 3600 % 60), 2)

       ) AS TotalTimeMissing

FROM

(

  SELECT mp.DIM_PERSON_ID, DATEDIFF(Second, mp.START_DTTM, mp.END_DTTM) Value

  FROM C_S.FACT_MISSING_PACKAGE AS mp

) T(Value))

ORDER BY START_DTTM ASC;
</code>```

Sami got me most of the way there but when I run the above code I get an error in relation to the UNION and T, with T not stating the required number of columns. To solve this I tried putting the initial round of SELECT columns into the (SELECT CONCAT() statement but it generates errors so I'm at a bit of loss when it comes to how fix it?

I need to return all of these columns with an additional column at the end as TotalTimeMissing

Thanks

答:
You can calculate the difference in minutes first using the DATEDIFF function and then calculate hours and days knowing that 1 hour is 60 minutes and 1 day is 1440 minutes.

Be aware of how the DATEDIFF
 works in SQL Server:

This function returns the count (as a signed integer value) of the
  specified datepart boundaries crossed between the specified startdate
  and enddate.

So,

```<code>DATEDIFF(day, '2020-01-13 23:59:58', '2020-01-14 00:00:08')
</code>```

will return 1, even though the difference is only few seconds, because the given interval crosses the boundary of a day (midnight).

That's why you should not be using DATEDIFF(day, ...) here, but use DATEDIFF(minute, ...) or DATEDIFF(second, ...) and calculate the number of hours and days based on the total number of elapsed minutes or seconds.

I will use the CROSS APPLY to avoid typing the long expression many times.
I also use integer division / here which discards the fractional part, e.g. 200 / 60 = 3.

```<code>Total days = total minutes / 1440 (discard fractional part)
Total hours = total minutes / 60 (discard fractional part)
</code>```

But, we don't need total hours, we need hours that are left extra after the total days, so we need to take mod 24.

```<code>Hours = Total hours % 24
</code>```

For final minutes we need just the remainder of the minutes after total days and hours, hence

```<code>Minutes = total minutes mod 60.
</code>```

The query:

```<code>SELECT
     dp.LEGACY_ID
    ,dp.SURNAME
    ,dp.FORENAME
    ,mp.DIM_PERSON_ID
    ,mp.MISSING_STATUS
    ,mp.START_DTTM
    ,mp.END_DTTM
    ,dp.LEGACY_ID
    ,STR(DiffMinutes / 1440) + ':' +        -- total days
     STR(DiffMinutes / 60 % 24) + ':' +     -- hours (0 .. 23)
     STR(DiffMinutes % 60) AS TimeMissing   -- minutes (0 .. 59)
FROM
    MissingPackages AS mp
    JOIN DIM_PERSON AS dp ON mp.DIM_PERSON_ID = dp.DIM_PERSON_ID
    CROSS APPLY
    (
        SELECT DATEDIFF(minute, mp.START_DTTM, mp.END_DTTM) AS DiffMinutes
    ) AS A
ORDER BY START_DTTM ASC;
</code>```

Body:
SOLVED

CONCAT((DATEDIFF(Minute,START_DTTM,END_DTTM)/60),'h:',
       (DATEDIFF(Minute,START_DTTM,END_DTTM)%60) 'm') AS TotalTimeMissing

Produces TotalTimeMissing: 5h:13m

________

I'm trying to return a timestamp value between two specific dates to work out the time between a package going missing and it being found.

EDIT: Code has been updated to include code from Sami. I have also added additional code that I excluded from the original.

Here is the current code:

USE PACKAGE

GO

SELECT

        dp.LEGACY_ID

       ,dp.SURNAME

       ,dp.FORENAME

       ,dp.ETHNICITY_DESCRIPTION

       ,dp.BIRTH_DTTM

       ,DATEDIFF(YY, dp.BIRTH_DTTM, GETDATE()) -

            CASE

                  WHEN RIGHT(CONVERT(VARCHAR(6), GETDATE(), 12), 4) >=

                        RIGHT(CONVERT(VARCHAR(6), dp.BIRTH_DTTM, 12), 4)

                        THEN 0

                  ELSE 1

            END AS [Current Age]

--^Precise age calc due to potential LL inaccuracy

       ,mp.DIM_PERSON_ID

       ,mp.MISSING_STATUS

       ,mp.START_DTTM

       ,mp.END_DTTM

       ,dp.LEGACY_ID

       ,mp.RETURN_INT_OFFERED

       ,mp.RETURN_INT_ACCEPTED

       ,mp.RETURN_INT_DATE

FROM C_S.FACT_MISSING_PACKAGE AS mp

JOIN C_S.FACT_MISSING_PACKAGE AS dp ON mp.DIM_PERSON_ID = dp.DIM_PERSON_ID

WHERE CAST (mp.START_DTTM AS DATE)

              BETWEEN DATEADD(YY, -1, CAST (GETDATE() AS DATE)) AND CAST (GETDATE() AS DATE)

--^Displays all records within exactly 1 year of run date

       UNION (SELECT CONCAT(Value / 3600 / 24,

              ' Days ',

              RIGHT(CONCAT('00', Value / 3600 % 24), 2),

              ':',

              RIGHT(CONCAT('00', Value / 60 % 60), 2),

              ':',

              RIGHT(CONCAT('00',Value % 3600 % 60), 2)

       ) AS TotalTimeMissing

FROM

(

  SELECT mp.DIM_PERSON_ID, DATEDIFF(Second, mp.START_DTTM, mp.END_DTTM) Value

  FROM C_S.FACT_MISSING_PACKAGE AS mp

) T(Value))

ORDER BY START_DTTM ASC;

Sami got me most of the way there but when I run the above code I get an error in relation to the UNION and T, with T not stating the required number of columns. To solve this I tried putting the initial round of SELECT columns into the (SELECT CONCAT() statement but it generates errors so I'm at a bit of loss when it comes to how fix it?

I need to return all of these columns with an additional column at the end as TotalTimeMissing

Thanks

Body:
You can calculate the difference in minutes first using the DATEDIFF function and then calculate hours and days knowing that 1 hour is 60 minutes and 1 day is 1440 minutes.

Be aware of how the DATEDIFF
 works in SQL Server:

This function returns the count (as a signed integer value) of the
  specified datepart boundaries crossed between the specified startdate
  and enddate.

So,

DATEDIFF(day, '2020-01-13 23:59:58', '2020-01-14 00:00:08')

will return 1, even though the difference is only few seconds, because the given interval crosses the boundary of a day (midnight).

That's why you should not be using DATEDIFF(day, ...) here, but use DATEDIFF(minute, ...) or DATEDIFF(second, ...) and calculate the number of hours and days based on the total number of elapsed minutes or seconds.

I will use the CROSS APPLY to avoid typing the long expression many times.
I also use integer division / here which discards the fractional part, e.g. 200 / 60 = 3.

Total days = total minutes / 1440 (discard fractional part)
Total hours = total minutes / 60 (discard fractional part)

But, we don't need total hours, we need hours that are left extra after the total days, so we need to take mod 24.

Hours = Total hours % 24

For final minutes we need just the remainder of the minutes after total days and hours, hence

Minutes = total minutes mod 60.

The query:

SELECT
     dp.LEGACY_ID
    ,dp.SURNAME
    ,dp.FORENAME
    ,mp.DIM_PERSON_ID
    ,mp.MISSING_STATUS
    ,mp.START_DTTM
    ,mp.END_DTTM
    ,dp.LEGACY_ID
    ,STR(DiffMinutes / 1440) + ':' +        -- total days
     STR(DiffMinutes / 60 % 24) + ':' +     -- hours (0 .. 23)
     STR(DiffMinutes % 60) AS TimeMissing   -- minutes (0 .. 59)
FROM
    MissingPackages AS mp
    JOIN DIM_PERSON AS dp ON mp.DIM_PERSON_ID = dp.DIM_PERSON_ID
    CROSS APPLY
    (
        SELECT DATEDIFF(minute, mp.START_DTTM, mp.END_DTTM) AS DiffMinutes
    ) AS A
ORDER BY START_DTTM ASC;


问:
Set textbox focus in mobile safari
Hey, I was wondering how to set the focus to a text box in Mobile Safari.

I've tried document.myForm.myTextArea.focus() which works in regular Safari, but it does not seem to work in Mobile Safari.

To clarify, I want to set focus to a text box as soon as the user loads a page, and have the iPhone keyboard pop up.

答:
Nothing to do with the timer, focus() doesnt work at all... im doing mine through an AJAX function. i guess my web application will have to suffer in mobile safari.

Bye the way, this also affects HP webOS devices and any other device using mobile safari

ContentLicense: CC BY-SA 2.5

Title: Set textbox focus in mobile safari


问:
MUIDataTable: In react application viewColumns options how to display the Checkbox List for column vertically
I have a MUI Table Implementation such that the options object viewColumns is set to true, which is supposed to display the popper to choose the columns to be displayed in vertical list of checkbox as shown below:

, but I am getting it horizontally as displayed in screenshot below:

The options to be passed in MUIDataTable components is defined as:

```<code>const options = {
      filter: true,
      filterType: "dropdown",
      print: false,
      viewColumns: true,
      selectableRows: false,
      onRowClick: (rowData) => {
        console.log("RowClicked->", rowData);
      },
      responsive: "stacked",
      fixedHeaderOptions: {
        xAxis: false,
        yAxis: true,
      },
    };
</code>```

columns defines as:

```<code>export const DEAL_GRID_COLUMNS = [
  {
    name: "someReference",
    label: "Some Reference",
    options: {
      filter: true,
      sort: true,
    },
  },
  {
    name: "businessTeam",
    label: "Business Teams",
    options: {
      filter: true,
      sort: true,
    },
  },
  {
    name: "keyContact",
    label: "Key Contact Lead",
    options: {
      filter: true,
      sort: true,
    },
  },
.....
.....
.....
.....
];
</code>```

and the component is consumed as

```<code><MUIDataTable data={gridData} columns={DEAL_GRID_COLUMNS} options={options} />
</code>```

here gridData is recieved from Api response

答:
I fixed this by overriding its maxWidth as</p>

```<code>MuiPopover: {
    paper: {
      maxWidth: "16%",
    },
  }
</code>```

Body:
I have a MUI Table Implementation such that the options object viewColumns is set to true, which is supposed to display the popper to choose the columns to be displayed in vertical list of checkbox as shown below:

, but I am getting it horizontally as displayed in screenshot below:

The options to be passed in MUIDataTable components is defined as:

const options = {
      filter: true,
      filterType: "dropdown",
      print: false,
      viewColumns: true,
      selectableRows: false,
      onRowClick: (rowData) => {
        console.log("RowClicked->", rowData);
      },
      responsive: "stacked",
      fixedHeaderOptions: {
        xAxis: false,
        yAxis: true,
      },
    };

columns defines as:

export const DEAL_GRID_COLUMNS = [
  {
    name: "someReference",
    label: "Some Reference",
    options: {
      filter: true,
      sort: true,
    },
  },
  {
    name: "businessTeam",
    label: "Business Teams",
    options: {
      filter: true,
      sort: true,
    },
  },
  {
    name: "keyContact",
    label: "Key Contact Lead",
    options: {
      filter: true,
      sort: true,
    },
  },
.....
.....
.....
.....
];

and the component is consumed as

<MUIDataTable data={gridData} columns={DEAL_GRID_COLUMNS} options={options} />

here gridData is recieved from Api response

Body:
I fixed this by overriding its maxWidth as

MuiPopover: {
    paper: {
      maxWidth: "16%",
    },
  }


Title: Awk conditional if else

Body:
i have a file that doesn't want to messed up the sequence so i'm trying to work out my awk conditional statement.

if $3 has TB(string), remove it and multiply it by 1024 and if it has GB just remove it(remove the string GB) and do nothing.

sast1sis01_002          iresas-p2-ris03    100.00GB   60050912017086C7700000000000021E
sast1sis01_004          iresas-p2-ris03    50.00TB    60050912017086C77000000000000AAF
sast1sis01_003          iresas-p2-ris03    100.00GB   60050912017086C77000000000000BB0
sast1sis01_008          iresas-p2-ris03    100.00GB   60050912017086C77000000000000OO1
sast1sis01_005          iresas-p2-ris03    100.00GB   60050912017086C77000000000000212
sast1sis01_001          iresas-p2-ris03    100.00GB   60050912017086C77000000000000993
arrysas1_356            cbscc-u8-msas1     600.00GB   60050912017086C77000000000000BBA
N8DVP01ABC_007          iresas-z1-pit02    2.44TB     60050912017086C770000000000005EE
n2sql90abc_052          iresas-p2-sql57a   1.00TB     60050912017086C7700000000000089C
n3sq321abc_055          iresas-p2-sql57b   0          60050912017086C7700000000000011C
n6sq222abc_056          iresas-p2-sql57a   1.00GB     60050912017086C7700000000000022D
n7sqbascka_058          iresas-p2-sql57b   0          60050912017086C7700000000000039D

Trying this out:

awk '{s=($3=="TB")?"-":$3=$3*1024; print}';awk '{s=($3=="GB")?"-":'s/GB//g'; print}' file

Body:
Since this is fixed-width data, with GNU awk you can write:

gawk '
  BEGIN {FIELDWIDTHS = "24 19 11 *"; OFS=""}
  {$3 = sprintf("%-11.2f", $3 * ($3 ~ /TB/ ? 1000  : 1))}
  1
' file

outputs:

sast1sis01_002          iresas-p2-ris03    100.00     60050912017086C7700000000000021E
sast1sis01_004          iresas-p2-ris03    50000.00   60050912017086C77000000000000AAF
sast1sis01_003          iresas-p2-ris03    100.00     60050912017086C77000000000000BB0
sast1sis01_008          iresas-p2-ris03    100.00     60050912017086C77000000000000OO1
sast1sis01_005          iresas-p2-ris03    100.00     60050912017086C77000000000000212
sast1sis01_001          iresas-p2-ris03    100.00     60050912017086C77000000000000993
arrysas1_356            cbscc-u8-msas1     600.00     60050912017086C77000000000000BBA
N8DVP01ABC_007          iresas-z1-pit02    2440.00    60050912017086C770000000000005EE
n2sql90abc_052          iresas-p2-sql57a   1000.00    60050912017086C7700000000000089C
n3sq321abc_055          iresas-p2-sql57b   0.00       60050912017086C7700000000000011C
n6sq222abc_056          iresas-p2-sql57a   1.00       60050912017086C7700000000000022D
n7sqbascka_058          iresas-p2-sql57b   0.00       60050912017086C7700000000000039D


答:
How to find result whereby latest record Status=A, and second latest record Status=B?

You can use window functions and a little bit of boolean logic:

```<code>select id, status, date
from (
    select t.*, row_number() over(partition by status order by date desc) rn
    from mytable t
    where status in ('A', 'B')
) t
where (status = 'A' and rn = 1) or (status = 'B' and rn = 2)
</code>```

Title: How to find latest 2 result with specific alpabet but with same ID

Body:
Raw Data

+---------+--------+------------+
|   ID    | STATUS |    DATE    |
+---------+--------+------------+
| ABC1234 | P      | 2020-01-01 |
| ABC1234 | P      | 2020-01-02 |
| ABC1234 | B      | 2020-01-03 |
| ABC1234 | A      | 2020-01-04 |
| ABC1234 | A      | 2020-01-05 |
| BCD     | P      | 2020-01-01 |
| BCD     | P      | 2020-01-02 |
| BCD     | P      | 2020-01-03 |
| BCD     | B      | 2020-01-04 |
| BCD     | A      | 2020-01-05 |
| 12XY    | P      | 2020-01-01 |
| 12XY    | P      | 2020-01-02 |
| 12XY    | P      | 2020-01-03 |
| 12XY    | B      | 2020-01-04 |
| 12XY    | B      | 2020-01-05 |
+---------+--------+------------+

Result I want

+-----+--------+------------+
| ID  | STATUS |    DATE    |
+-----+--------+------------+
| BCD | B      | 2020-01-04 |
| BCD | A      | 2020-01-05 |
+-----+--------+------------+

How to find result whereby latest record Status=A, and second latest record Status=B?

Tried on below but still missing idea how get for ID=BCD

select ROW_NUMBER()
        OVER (PARTITION BY ID ORDER BY date2 DESC) AS rownum
         ,*
         into testingtable
         from mytable
         WHERE status in ('b', 'a')

Body:
How to find result whereby latest record Status=A, and second latest record Status=B?

You can use window functions and a little bit of boolean logic:

select id, status, date
from (
    select t.*, row_number() over(partition by status order by date desc) rn
    from mytable t
    where status in ('A', 'B')
) t
where (status = 'A' and rn = 1) or (status = 'B' and rn = 2)


问:
Oracle SQL - How to merge multiple columns into new one
I need to merge multiple columns (there are quite a lot of columns and rows) into new one column.

Eg. shortened test_table

```<code>Col1    Col2    Col3    Col4    Col5    Col6
942 72987   14759   441277503   73553030    null
943 72987   14759   441278315   73553166    null
944 72987   14759   441362593   73570082    null
945 72987   14759   441380217   73572619    null
946 72987   14759   441394189   73574533    null
947 72987   14759   441394189   73574533    null
</code>```

and I'd like to merge Col1-Col5 with comma separator (",") and put created String into Col6

So in Col6 I'd like to have eg:
942,72987,14759,441277503,73553030

Is there any solution how can I do it in SQL / PL/SQL?
As I said there are a lot of column so I'd like to avoid to add them manually by using Col1 || Col2 || Col3 || Col4 || Col5

Thanks in advance,
Michał

答:
You can use trim() with some conditional logic:

```<code>select trim(leading ',' from
            (case when col1 is not null then ',' || col1 else '' end) ||
            (case when col2 is not null then ',' || col2 else '' end) ||
            (case when col3 is not null then ',' || col3 else '' end) ||
            (case when col4 is not null then ',' || col4 else '' end) ||
            (case when col5 is not null then ',' || col5 else '' end)
           )
</code>```

Body:
I need to merge multiple columns (there are quite a lot of columns and rows) into new one column.

Eg. shortened test_table

Col1    Col2    Col3    Col4    Col5    Col6
942 72987   14759   441277503   73553030    null
943 72987   14759   441278315   73553166    null
944 72987   14759   441362593   73570082    null
945 72987   14759   441380217   73572619    null
946 72987   14759   441394189   73574533    null
947 72987   14759   441394189   73574533    null

and I'd like to merge Col1-Col5 with comma separator (",") and put created String into Col6

So in Col6 I'd like to have eg:
942,72987,14759,441277503,73553030

Is there any solution how can I do it in SQL / PL/SQL?
As I said there are a lot of column so I'd like to avoid to add them manually by using Col1 || Col2 || Col3 || Col4 || Col5

Thanks in advance,
Michał

Body:
You can use trim() with some conditional logic:

select trim(leading ',' from
            (case when col1 is not null then ',' || col1 else '' end) ||
            (case when col2 is not null then ',' || col2 else '' end) ||
            (case when col3 is not null then ',' || col3 else '' end) ||
            (case when col4 is not null then ',' || col4 else '' end) ||
            (case when col5 is not null then ',' || col5 else '' end)
           )


问:
How to I insert a video link within an image file
How do I link a video (hosted on a server) to an image? I keep getting the first frame of the video instead of a specific image that I want to display. I also need to get the video to play in the right size on multiple devices. At the moment I can set the height and width but this doesn't adapt to mobiles.

Example:

```<code><p><a href="THIS IS THE VIDEO FILE I WANT TO LINK"><img src="/resources/Pictures/Website%20Pages/Members/Club%20TV/Summer%20Camp%20Nutrition.jpg" border="0" alt=""></a><br></p>
</code>```

答:
You can use controls poster property in order to give your video a poster instead of showing the first frame

CSS property object-fit to fill the poster based on width and height of the video

video{
   object-fit: inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video width="400px" height=200px" controls poster="https://images.unsplash.com/photo-1590573124389-83f2133e0307?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60">
   <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4">
   <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg" type="video/ogg">
 </video></code>```

Body:
You can use controls poster property in order to give your video a poster instead of showing the first frame

CSS property object-fit to fill the poster based on width and height of the video

video{
   object-fit: inherit;
}

<video width="400px" height=200px" controls poster="https://images.unsplash.com/photo-1590573124389-83f2133e0307?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60">
   <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4">
   <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg" type="video/ogg">
 </video>


问:
Rails 3 - help with Atom Feed?
Feel like I have been going around in circles, have followed different tutorials all proposing to achieve the promised result and none of them are working for me. I'm using the Kaminari plug-in and my articles are on the index page (6).Can anyone help me with this? Thx

application.html.rb

```<code>auto_discovery_link_tag(:atom) # =>
<link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com" />
</code>```

routes.rb

```<code>match '/feed' => 'articles#feed', :as => :feed, :defaults => { :format => 'atom' }
</code>```

articles_controller.rb

```<code>def index
@articles = Article.published.page(params[:page]).per(6).ordered

respond_to do |format|
  format.html # index.html.erb
  format.atom  { @articles = Article.published }
  format.xml  { render :xml => @articles }
end
end
</code>```

articles/index.atom.builder

```<code>atom_feed do |feed|
feed.title "Title"
feed.updated(@articles.blank? ? Time.now : @articles.first.created_at)

@articles.each do |article|
feed.entry article do |entry|
entry.title article.title
entry.content article.body, :type => 'html'

entry.author do |author|
author.name article.author
end
end
end
end
</code>```

答:
In your application template (application.html.rb), try this instead:

```<code><%= auto_discovery_link_tag(:atom, feed_path, { :title => "My ATOM Feed" }) %>
</code>```

Title: Rails 3 - help with Atom Feed?

Body:
Feel like I have been going around in circles, have followed different tutorials all proposing to achieve the promised result and none of them are working for me. I'm using the Kaminari plug-in and my articles are on the index page (6).Can anyone help me with this? Thx

application.html.rb

auto_discovery_link_tag(:atom) # =>
<link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com" />

routes.rb

match '/feed' => 'articles#feed', :as => :feed, :defaults => { :format => 'atom' }

articles_controller.rb

def index
@articles = Article.published.page(params[:page]).per(6).ordered

respond_to do |format|
  format.html # index.html.erb
  format.atom  { @articles = Article.published }
  format.xml  { render :xml => @articles }
end
end

articles/index.atom.builder

atom_feed do |feed|
feed.title "Title"
feed.updated(@articles.blank? ? Time.now : @articles.first.created_at)

@articles.each do |article|
feed.entry article do |entry|
entry.title article.title
entry.content article.body, :type => 'html'

entry.author do |author|
author.name article.author
end
end
end
end

Body:
In your application template (application.html.rb), try this instead:

<%= auto_discovery_link_tag(:atom, feed_path, { :title => "My ATOM Feed" }) %>


问:
Don't output same items from array
I'm using react js. I try to map an array with objects and to output the name of each object from array:

const arr = [
  {
    name:"Bill",
    age:88
  },
   {
    name:"Bill",
    age:18
  },
   {
    name:"Jack",
    age:55
  },
]
  {arr.map(i => (

          {i.name}

   ))}```
</div>
</div>
</p>

<p>I want to avoid the same name when i do <code>{i.name}</code>. For this i made this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{new Set(i.name)}</code>```

.. but it does not help. How to avoid displaying the same name in map function?

答:
You need to create a Set of names before mapping and rendering. You can do it like below</p>

```<code>  {[...new Set(arr.map(i => i.name))].map(i => (
        <li key={i.id}>
          {i.name}
        </li>
   ))}
</code>```

Title: Don't output same items from array

Body:
I'm using react js. I try to map an array with objects and to output the name of each object from array:

const arr = [
  {
    name:"Bill",
    age:88
  },
   {
    name:"Bill",
    age:18
  },
   {
    name:"Jack",
    age:55
  },
]
  {arr.map(i => (

          {i.name}

   ))}

I want to avoid the same name when i do {i.name}. For this i made this:

{new Set(i.name)}

.. but it does not help. How to avoid displaying the same name in map function?

Body:
You need to create a Set of names before mapping and rendering. You can do it like below

  {[...new Set(arr.map(i => i.name))].map(i => (
        <li key={i.id}>
          {i.name}
        </li>
   ))}


问:
Deep Security Management Console
asked DSM and solved Thank you very much.</p>

答:
Check out this list for Deep Security system requirements, including the browsers supported for connecting to the DSM console: https://help.deepsecurity.trendmicro.com/12_0/on-premise/Get-Started/Install/system-requirements.html#Deep

P.S. I work for Trend Micro in R&D

Title: Deep Security Management Console


问:
AMQP 1.0 Library for Python
I'm looking for a AMQP 1.0 compliant Python library. I've gone through several libraries but they all seem to support only AMQP 0.9.1.

amqp - https://pypi.python.org/pypi/amqp/1.4.7

pika - https://github.com/pika/pika

amqplib - https://code.google.com/p/py-amqplib/

Puka (https://github.com/majek/puka) doesn't seem to mention the specific AMQP version it supports, but it only says it's a RabbitMQ client.

答: For AMQP 1.0 I have found uamqp: https://github.com/Azure/azure-uamqp-python (MIT License)</p>

Title: AMQP 1.0 Library for Python


问:
Zend - How to enable cache(MetaData) on session table?
i am using Zend_Session_SaveHandler_DbTable to store the session in a table

my profiler tells me that on each page request zend does:

#  Query   Time

(1)     connect     0.0032038688659668

(2)     DESCRIBE session  0.0041539669036865

(3)     SELECT session.* FROM session WHERE (((session.session_id = '7nnan8ltd6h64sigs6dlkicvh0' AND session.save_path = '' AND session.name = 'PHPSESSID')))   0.00057697296142578

Total time : 0.008 sec

when i do queries on other tables, zend DESCRIBEs them once(the first time it access that table), then if i refresh the page it only does the query with no Describe, on the session table it does DESCRIBE on every page (since i use authentication ... )

how can i cache only the metadata on the session table?

i am currently using this

```<code>class Gestionale_Application_Resource_Cache extends Zend_Application_Resource_ResourceAbstract{
public function init ()
{
    $options = $this->getOptions();

    // Get a Zend_Cache_Core object

    //valori che vengono presi dal file di configurazione
    $cache = Zend_Cache::factory(
        $options['frontEnd'],
        $options['backEnd'],
        $options['frontEndOptions'],
        $options['backEndOptions']);
    Zend_Registry::set('cache', $cache);

    Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);//per mettere in cache la meta-info
    return $cache;
}
</code>```

this is my config file

```<code>...
;cache stuff
resources.cache.frontEnd = core
resources.cache.backEnd = file
resources.cache.frontEndOptions.lifetime = 1200 ; in secondi
resources.cache.frontEndOptions.automatic_serialization = true
resources.cache.backEndOptions.lifetime = 3600 ; in secondi
resources.cache.backEndOptions.cache_dir = APPLICATION_PATH "/../cache"
pluginPaths.Gestionale_Application_Resource = APPLICATION_PATH "/../library/Gestionale/Application/Resource"
;;fine cache stuff

resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.db.params.charset = "utf8"
resources.db.adapter = "pdo_mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.params.dbname = "gestionale"
resources.db.isDefaultTableAdapter = true
autoloaderNamespaces[] = "Gestionale_";serve per caricare il plugin di sotto quando si usa anche ZFdebug
resources.frontController.plugins.acl = "Gestionale_Controller_Plugin_Acl"
resources.db.params.profiler = true
...
</code>```

this is my session table

```<code>CREATE TABLE IF NOT EXISTS `session` (
  `session_id` char(32) NOT NULL,
  `save_path` varchar(32) NOT NULL,
  `name` varchar(32) NOT NULL DEFAULT '',
  `modified` int(11) DEFAULT NULL,
  `lifetime` int(11) DEFAULT NULL,
  `session_data` text,
  PRIMARY KEY (`session_id`,`save_path`,`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

thanks :D

答:
Wherever you are initializing the session save handler, either in the bootstrap or the config file, make sure that you call Zend_Db_Table_Abstract::setDefaultMetadataCache() first.

To specify it in your config file, put the session config after the ;;fine cache stuff line:

```<code>...
;cache stuff
resources.cache.frontEnd = core
resources.cache.backEnd = file
resources.cache.frontEndOptions.lifetime = 1200 ; in secondi
resources.cache.frontEndOptions.automatic_serialization = true
resources.cache.backEndOptions.lifetime = 3600 ; in secondi
resources.cache.backEndOptions.cache_dir = APPLICATION_PATH "/../cache"
pluginPaths.Gestionale_Application_Resource = APPLICATION_PATH "/../library/Gestionale/Application/Resource"
;;fine cache stuff

resources.session.saveHandler.class = "Zend_Session_SaveHandler_DbTable"
resources.session.saveHandler.options.name = "session"
resources.session.saveHandler.options.primary[] = "session_id"
resources.session.saveHandler.options.primary[] = "save_path"
resources.session.saveHandler.options.primary[] = "name"
resources.session.saveHandler.options.primaryAssignment[] = "sessionId"
resources.session.saveHandler.options.primaryAssignment[] = "sessionSavePath"
resources.session.saveHandler.options.primaryAssignment[] = "sessionName"
resources.session.saveHandler.options.modifiedColumn = "modified"
resources.session.saveHandler.options.dataColumn = "session_data"
resources.session.saveHandler.options.lifetimeColumn = "lifetime"

resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.db.params.charset = "utf8"
...
</code>```

Or, if you don't want to rely on their order in the config file, you can add an _initSession() method to your bootstrap class that specifically loads them in the correct order:

```<code>protected function _initSession()
{
    $this->bootstrap('cache');
    $this->bootstrap('session');
}
</code>```

Body:
i am using Zend_Session_SaveHandler_DbTable to store the session in a table

my profiler tells me that on each page request zend does:

#  Query   Time

(1)     connect     0.0032038688659668

(2)     DESCRIBE session  0.0041539669036865

(3)     SELECT session.* FROM session WHERE (((session.session_id = '7nnan8ltd6h64sigs6dlkicvh0' AND session.save_path = '' AND session.name = 'PHPSESSID')))   0.00057697296142578

Total time : 0.008 sec

when i do queries on other tables, zend DESCRIBEs them once(the first time it access that table), then if i refresh the page it only does the query with no Describe, on the session table it does DESCRIBE on every page (since i use authentication ... )

how can i cache only the metadata on the session table?

i am currently using this

class Gestionale_Application_Resource_Cache extends Zend_Application_Resource_ResourceAbstract{
public function init ()
{
    $options = $this->getOptions();

    // Get a Zend_Cache_Core object

    //valori che vengono presi dal file di configurazione
    $cache = Zend_Cache::factory(
        $options['frontEnd'],
        $options['backEnd'],
        $options['frontEndOptions'],
        $options['backEndOptions']);
    Zend_Registry::set('cache', $cache);

    Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);//per mettere in cache la meta-info
    return $cache;
}

this is my config file

...
;cache stuff
resources.cache.frontEnd = core
resources.cache.backEnd = file
resources.cache.frontEndOptions.lifetime = 1200 ; in secondi
resources.cache.frontEndOptions.automatic_serialization = true
resources.cache.backEndOptions.lifetime = 3600 ; in secondi
resources.cache.backEndOptions.cache_dir = APPLICATION_PATH "/../cache"
pluginPaths.Gestionale_Application_Resource = APPLICATION_PATH "/../library/Gestionale/Application/Resource"
;;fine cache stuff

resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.db.params.charset = "utf8"
resources.db.adapter = "pdo_mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.params.dbname = "gestionale"
resources.db.isDefaultTableAdapter = true
autoloaderNamespaces[] = "Gestionale_";serve per caricare il plugin di sotto quando si usa anche ZFdebug
resources.frontController.plugins.acl = "Gestionale_Controller_Plugin_Acl"
resources.db.params.profiler = true
...

this is my session table

CREATE TABLE IF NOT EXISTS `session` (
  `session_id` char(32) NOT NULL,
  `save_path` varchar(32) NOT NULL,
  `name` varchar(32) NOT NULL DEFAULT '',
  `modified` int(11) DEFAULT NULL,
  `lifetime` int(11) DEFAULT NULL,
  `session_data` text,
  PRIMARY KEY (`session_id`,`save_path`,`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

thanks :D

Body:
Wherever you are initializing the session save handler, either in the bootstrap or the config file, make sure that you call Zend_Db_Table_Abstract::setDefaultMetadataCache() first.

To specify it in your config file, put the session config after the ;;fine cache stuff line:

...
;cache stuff
resources.cache.frontEnd = core
resources.cache.backEnd = file
resources.cache.frontEndOptions.lifetime = 1200 ; in secondi
resources.cache.frontEndOptions.automatic_serialization = true
resources.cache.backEndOptions.lifetime = 3600 ; in secondi
resources.cache.backEndOptions.cache_dir = APPLICATION_PATH "/../cache"
pluginPaths.Gestionale_Application_Resource = APPLICATION_PATH "/../library/Gestionale/Application/Resource"
;;fine cache stuff

resources.session.saveHandler.class = "Zend_Session_SaveHandler_DbTable"
resources.session.saveHandler.options.name = "session"
resources.session.saveHandler.options.primary[] = "session_id"
resources.session.saveHandler.options.primary[] = "save_path"
resources.session.saveHandler.options.primary[] = "name"
resources.session.saveHandler.options.primaryAssignment[] = "sessionId"
resources.session.saveHandler.options.primaryAssignment[] = "sessionSavePath"
resources.session.saveHandler.options.primaryAssignment[] = "sessionName"
resources.session.saveHandler.options.modifiedColumn = "modified"
resources.session.saveHandler.options.dataColumn = "session_data"
resources.session.saveHandler.options.lifetimeColumn = "lifetime"

resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.db.params.charset = "utf8"
...

Or, if you don't want to rely on their order in the config file, you can add an _initSession() method to your bootstrap class that specifically loads them in the correct order:

protected function _initSession()
{
    $this->bootstrap('cache');
    $this->bootstrap('session');
}


问:
Load child entity in Hibernate based on boolean flag
is there a way in Hibernate 3.6 to only load a child entity if a boolean flag in the parent entity is set to true?

For example:

```<code>@Entity
class Parent {
  @OneToOne
  private Child child;
  private boolean loadChild;
}
</code>```

So if loadChild == false, the child should not be loaded from the db and always be null, otherwise it should be loaded (if available, of course). Currently, the child is loaded eagerly and it would be nice to keep it that way.

Bascially, what we want to prevent here is the actual loading of the child and all the performance impact this may have. It would be easy to load it and then use a getter to return null, but this would have performance impacts by loading a child that is not actually needed.

答:
I am not sure if JPA and/or Hibernate supports this directly. One workaround can be:

Move down loadChild to Child and then use @Where in Parent.

But, at field level, @Where works only for collection-valued attributes. So you will have to wrap the child with a Collection for @Where to work.

```<code>@Where(clause = "load_with_parent = true") // lets say the column name is load_with_parent
@OneToMany
private List<Child> childs;
</code>```

Further Reading:

@Where in Hibernate user guide

See this SO question: Hibernate @OneToOne mapping with a @Where clause

Body:
is there a way in Hibernate 3.6 to only load a child entity if a boolean flag in the parent entity is set to true?

For example:

@Entity
class Parent {
  @OneToOne
  private Child child;
  private boolean loadChild;
}

So if loadChild == false, the child should not be loaded from the db and always be null, otherwise it should be loaded (if available, of course). Currently, the child is loaded eagerly and it would be nice to keep it that way.

Bascially, what we want to prevent here is the actual loading of the child and all the performance impact this may have. It would be easy to load it and then use a getter to return null, but this would have performance impacts by loading a child that is not actually needed.

Body:
I am not sure if JPA and/or Hibernate supports this directly. One workaround can be:

Move down loadChild to Child and then use @Where in Parent.

But, at field level, @Where works only for collection-valued attributes. So you will have to wrap the child with a Collection for @Where to work.

@Where(clause = "load_with_parent = true") // lets say the column name is load_with_parent
@OneToMany
private List<Child> childs;

Further Reading:

@Where in Hibernate user guide

See this SO question: Hibernate @OneToOne mapping with a @Where clause


问:
Scroll div horizontally instead of page, then scroll page
it isn't a duplicate as I've read the others question but everyone assume that the scroll is vertical, while i need this for horizontal scroll.
What i'm trying to do is to scroll a div, placed somewhere in a page, when it reach the center of the screen or it is almost visible, then when it end its scroll i need to continue the page scrolll.

Actually i have a "slider" like this: JSFIDDLE

Actually, I can get an advise when the element is visible on the page after scrolling, but I don't know how to disable vertical scroll, scroll my div, and then scroll page again. The important thing is that the div scroll how much i continue the scrolling (intended with mouse, keyboard and maybe touch, it will be awesome)

```<code>function testInView($el){
var wTop = $(window).scrollTop();
var wBot = wTop + $(window).height();
var eTop = $el.offset().top;
var eBot = eTop + $el.height()+50;
return ((eBot <= wBot) && (eTop >= wTop));
}
function setInView(){
$(".slider-wrapper").each(function(){
    var $zis = $(this);
    $zis.removeClass("inview");
    if(testInView($zis)){
       alert("eccolo");
    }
});
}
$(document).scroll(function(){
    setInView();
});
$(document).resize(function(){
    setInView();
});
$(document).ready(function(){
    setInView();
});
</code>```

答:
If you want to disable vertical scrolling then just set overflow-y: hidden on body element</p>

```<code>body {
    overflow-y: hidden;
}
</code>```

Body:
it isn't a duplicate as I've read the others question but everyone assume that the scroll is vertical, while i need this for horizontal scroll.
What i'm trying to do is to scroll a div, placed somewhere in a page, when it reach the center of the screen or it is almost visible, then when it end its scroll i need to continue the page scrolll.

Actually i have a "slider" like this: JSFIDDLE

Actually, I can get an advise when the element is visible on the page after scrolling, but I don't know how to disable vertical scroll, scroll my div, and then scroll page again. The important thing is that the div scroll how much i continue the scrolling (intended with mouse, keyboard and maybe touch, it will be awesome)

function testInView($el){
var wTop = $(window).scrollTop();
var wBot = wTop + $(window).height();
var eTop = $el.offset().top;
var eBot = eTop + $el.height()+50;
return ((eBot <= wBot) && (eTop >= wTop));
}
function setInView(){
$(".slider-wrapper").each(function(){
    var $zis = $(this);
    $zis.removeClass("inview");
    if(testInView($zis)){
       alert("eccolo");
    }
});
}
$(document).scroll(function(){
    setInView();
});
$(document).resize(function(){
    setInView();
});
$(document).ready(function(){
    setInView();
});

Body:
If you want to disable vertical scrolling then just set overflow-y: hidden on body element

body {
    overflow-y: hidden;
}


问:
IntelliJ, remove scrollbar
Especially when using split screen in JetBrains products, the scrollbar often gets in the way and takes up important screen real estate. Is there a way to disable it? I cannot find an option in IntelliJ/JetBrains-IDE settings.</p>

答:
There is no actual way to disable the scrollbar. However, one can go into

```<code>Color Scheme > General > Vertical Scrollbar > *
</code>```

and turn Background property to Opacity: 0

I cannot find an option for the horizontal scrollbar.

Title: IntelliJ, remove scrollbar

Body:
There is no actual way to disable the scrollbar. However, one can go into

Color Scheme > General > Vertical Scrollbar > *

and turn Background property to Opacity: 0

I cannot find an option for the horizontal scrollbar.