问:
error CS0117: 'EditorUtility' does not contain a definition for 'RequestScriptReload'
In unity I keep on getting this error that keeps on bugging me, I tried to remove packages to leave one of these errors and it kept on going on and on, i am developing a game right now using unity engine and the errors are a big pain for me, this is the code that someone asked for, i dont really have much else to write other than this, stackoverlow isnt letting me just  post it because its too short    </p>

```<code>using System;
using System.IO;
using UnityEngine;

namespace UnityEditor.SettingsManagement
{
    /// <inheritdoc />
    /// <summary>
    /// A settings repository that stores data local to a Unity project.
    /// </summary>
    [Serializable]
    public sealed class PackageSettingsRepository : ISettingsRepository
    {
        const string k_PackageSettingsDirectory = "ProjectSettings/Packages";
        const bool k_PrettyPrintJson = true;

        bool m_Initialized;

        [SerializeField]
        string m_Name;

        [SerializeField]
        string m_Path;

        [SerializeField]
        SettingsDictionary m_Dictionary = new SettingsDictionary();

        /// <summary>
        /// Constructor sets the serialized data path.
        /// </summary>
        /// <param name="package">
        /// The package name.
        /// </param>
        /// <param name="name">
        /// A name for this settings file. Settings are saved in `ProjectSettings/Packages/{package}/{name}.json`.
        /// </param>
        public PackageSettingsRepository(string package, string name)
        {
            m_Name = name;
            m_Path = GetSettingsPath(package, name);
            m_Initialized = false;

            AssemblyReloadEvents.beforeAssemblyReload += Save;
            EditorApplication.quitting += Save;
        }

        void Init()
        {
            if (m_Initialized)
                return;

            m_Initialized = true;

            if (File.Exists(path))
            {
                m_Dictionary = null;
                var json = File.ReadAllText(path);
                EditorJsonUtility.FromJsonOverwrite(json, this);
                if(m_Dictionary == null)
                    m_Dictionary = new SettingsDictionary();
            }
        }

        /// <value>
        /// This repository implementation is relevant to the Project scope.
        /// </value>
        /// <inheritdoc cref="ISettingsRepository.scope"/>
        public SettingsScope scope
        {
            get { return SettingsScope.Project; }
        }

        /// <value>
        /// The full path to the settings file.
        /// This corresponds to `Unity Project/Project Settings/Packages/com.unity.package/name`.
        /// </value>
        /// <inheritdoc cref="ISettingsRepository.path"/>
        public string path
        {
            get { return m_Path; }
        }

        /// <summary>
        /// The name of this settings file.
        /// </summary>
        public string name
        {
            get { return m_Name; }
        }

        // Cannot call FindFromAssembly from a constructor or field initializer
//        static string CreateSettingsPath(Assembly assembly, string name)
//        {
//            var info = PackageManager.PackageInfo.FindForAssembly(assembly);
//            return string.Format("{0}/{1}/{2}.json", k_PackageSettingsDirectory, info.name, name);
//        }

        /// <summary>
        /// Get a path for a settings file relative to the calling assembly package directory.
        /// </summary>
        /// <param name="packageName">The name of the package requesting this setting.</param>
        /// <param name="name">An optional name for the settings file. Default is "Settings."</param>
        /// <returns>A package-scoped path to the settings file within Project Settings.</returns>
        public static string GetSettingsPath(string packageName, string name = "Settings")
        {
            return string.Format("{0}/{1}/{2}.json", k_PackageSettingsDirectory, packageName, name);
        }

        /// <summary>
        /// Save all settings to their serialized state.
        /// </summary>
        /// <inheritdoc cref="ISettingsRepository.Save"/>
        public void Save()
        {
            Init();

            if (!File.Exists(path))
            {
                var directory = Path.GetDirectoryName(path);
                Directory.CreateDirectory(directory);
            }

#if UNITY_2019_3_OR_NEWER
            if (!AssetDatabase.IsOpenForEdit(path))
            {
                if (!AssetDatabase.MakeEditable(path))
                {
                    Debug.LogWarning($"Could not save package settings to {path}");
                    return;
                }
            }
#endif

            try
            {
                File.WriteAllText(path, EditorJsonUtility.ToJson(this, k_PrettyPrintJson));
            }
            catch (UnauthorizedAccessException)
            {
                Debug.LogWarning($"Could not save package settings to {path}");
            }
        }

        /// <summary>
        /// Set a value for key of type T.
        /// </summary>
        /// <param name="key">The settings key.</param>
        /// <param name="value">The value to set. Must be serializable.</param>
        /// <typeparam name="T">Type of value.</typeparam>
        /// <inheritdoc cref="ISettingsRepository.Set{T}"/>
        public void Set<T>(string key, T value)
        {
            Init();
            m_Dictionary.Set<T>(key, value);
        }

        /// <summary>
        /// Get a value with key of type T, or return the fallback value if no matching key is found.
        /// </summary>
        /// <param name="key">The settings key.</param>
        /// <param name="fallback">If no key with a value of type T is found, this value is returned.</param>
        /// <typeparam name="T">Type of value to search for.</typeparam>
        /// <inheritdoc cref="ISettingsRepository.Get{T}"/>
        public T Get<T>(string key, T fallback = default(T))
        {
            Init();
            return m_Dictionary.Get<T>(key, fallback);
        }

        /// <summary>
        /// Does the repository contain a setting with key and type.
        /// </summary>
        /// <param name="key">The settings key.</param>
        /// <typeparam name="T">The type of value to search for.</typeparam>
        /// <returns>True if a setting matching both key and type is found, false if no entry is found.</returns>
        /// <inheritdoc cref="ISettingsRepository.ContainsKey{T}"/>
        public bool ContainsKey<T>(string key)
        {
            Init();
            return m_Dictionary.ContainsKey<T>(key);
        }

        /// <summary>
        /// Remove a key value pair from the settings repository.
        /// </summary>
        /// <param name="key"></param>
        /// <typeparam name="T"></typeparam>
        /// <inheritdoc cref="ISettingsRepository.Remove{T}"/>
        public void Remove<T>(string key)
        {
            Init();
            m_Dictionary.Remove<T>(key);

</code>```

答:
By the definition of 'RequestScriptReload' :

"The Unity Editor reloads script assemblies asynchronously on the next frame. This resets the state of all the scripts, but Unity does not compile any code that has changed since the previous compilation."

That means that your problem is probably with something that you changed.

You can try:

Going back to the last time everything wored and go on from there.

Closing all of you unity and scripting applications and opening it again.

Body:
In unity I keep on getting this error that keeps on bugging me, I tried to remove packages to leave one of these errors and it kept on going on and on, i am developing a game right now using unity engine and the errors are a big pain for me, this is the code that someone asked for, i dont really have much else to write other than this, stackoverlow isnt letting me just  post it because its too short

using System;
using System.IO;
using UnityEngine;

namespace UnityEditor.SettingsManagement
{
    /// <inheritdoc />
    ///
    /// A settings repository that stores data local to a Unity project.
    ///
    [Serializable]
    public sealed class PackageSettingsRepository : ISettingsRepository
    {
        const string k_PackageSettingsDirectory = "ProjectSettings/Packages";
        const bool k_PrettyPrintJson = true;

        bool m_Initialized;

        [SerializeField]
        string m_Name;

        [SerializeField]
        string m_Path;

        [SerializeField]
        SettingsDictionary m_Dictionary = new SettingsDictionary();

        ///
        /// Constructor sets the serialized data path.
        ///
        /// <param name="package">
        /// The package name.
        /// </param>
        /// <param name="name">
        /// A name for this settings file. Settings are saved in `ProjectSettings/Packages/{package}/{name}.json`.
        /// </param>
        public PackageSettingsRepository(string package, string name)
        {
            m_Name = name;
            m_Path = GetSettingsPath(package, name);
            m_Initialized = false;

            AssemblyReloadEvents.beforeAssemblyReload += Save;
            EditorApplication.quitting += Save;
        }

        void Init()
        {
            if (m_Initialized)
                return;

            m_Initialized = true;

            if (File.Exists(path))
            {
                m_Dictionary = null;
                var json = File.ReadAllText(path);
                EditorJsonUtility.FromJsonOverwrite(json, this);
                if(m_Dictionary == null)
                    m_Dictionary = new SettingsDictionary();
            }
        }

        /// <value>
        /// This repository implementation is relevant to the Project scope.
        /// </value>
        /// <inheritdoc cref="ISettingsRepository.scope"/>
        public SettingsScope scope
        {
            get { return SettingsScope.Project; }
        }

        /// <value>
        /// The full path to the settings file.
        /// This corresponds to `Unity Project/Project Settings/Packages/com.unity.package/name`.
        /// </value>
        /// <inheritdoc cref="ISettingsRepository.path"/>
        public string path
        {
            get { return m_Path; }
        }

        ///
        /// The name of this settings file.
        ///
        public string name
        {
            get { return m_Name; }
        }

        // Cannot call FindFromAssembly from a constructor or field initializer
//        static string CreateSettingsPath(Assembly assembly, string name)
//        {
//            var info = PackageManager.PackageInfo.FindForAssembly(assembly);
//            return string.Format("{0}/{1}/{2}.json", k_PackageSettingsDirectory, info.name, name);
//        }

        ///
        /// Get a path for a settings file relative to the calling assembly package directory.
        ///
        /// <param name="packageName">The name of the package requesting this setting.</param>
        /// <param name="name">An optional name for the settings file. Default is "Settings."</param>
        /// <returns>A package-scoped path to the settings file within Project Settings.</returns>
        public static string GetSettingsPath(string packageName, string name = "Settings")
        {
            return string.Format("{0}/{1}/{2}.json", k_PackageSettingsDirectory, packageName, name);
        }

        ///
        /// Save all settings to their serialized state.
        ///
        /// <inheritdoc cref="ISettingsRepository.Save"/>
        public void Save()
        {
            Init();

            if (!File.Exists(path))
            {
                var directory = Path.GetDirectoryName(path);
                Directory.CreateDirectory(directory);
            }

#if UNITY_2019_3_OR_NEWER
            if (!AssetDatabase.IsOpenForEdit(path))
            {
                if (!AssetDatabase.MakeEditable(path))
                {
                    Debug.LogWarning($"Could not save package settings to {path}");
                    return;
                }
            }
#endif

            try
            {
                File.WriteAllText(path, EditorJsonUtility.ToJson(this, k_PrettyPrintJson));
            }
            catch (UnauthorizedAccessException)
            {
                Debug.LogWarning($"Could not save package settings to {path}");
            }
        }

        ///
        /// Set a value for key of type T.
        ///
        /// <param name="key">The settings key.</param>
        /// <param name="value">The value to set. Must be serializable.</param>
        /// <typeparam name="T">Type of value.</typeparam>
        /// <inheritdoc cref="ISettingsRepository.Set{T}"/>
        public void Set<T>(string key, T value)
        {
            Init();
            m_Dictionary.Set<T>(key, value);
        }

        ///
        /// Get a value with key of type T, or return the fallback value if no matching key is found.
        ///
        /// <param name="key">The settings key.</param>
        /// <param name="fallback">If no key with a value of type T is found, this value is returned.</param>
        /// <typeparam name="T">Type of value to search for.</typeparam>
        /// <inheritdoc cref="ISettingsRepository.Get{T}"/>
        public T Get<T>(string key, T fallback = default(T))
        {
            Init();
            return m_Dictionary.Get<T>(key, fallback);
        }

        ///
        /// Does the repository contain a setting with key and type.
        ///
        /// <param name="key">The settings key.</param>
        /// <typeparam name="T">The type of value to search for.</typeparam>
        /// <returns>True if a setting matching both key and type is found, false if no entry is found.</returns>
        /// <inheritdoc cref="ISettingsRepository.ContainsKey{T}"/>
        public bool ContainsKey<T>(string key)
        {
            Init();
            return m_Dictionary.ContainsKey<T>(key);
        }

        ///
        /// Remove a key value pair from the settings repository.
        ///
        /// <param name="key"></param>
        /// <typeparam name="T"></typeparam>
        /// <inheritdoc cref="ISettingsRepository.Remove{T}"/>
        public void Remove<T>(string key)
        {
            Init();
            m_Dictionary.Remove<T>(key);


来源: stackexchange

问:
OAuth2 | ClientCredentialsResourceDetails | deprecated
I am new to spring security, and i come across to implement OAuth2 with client_credentials as Grant type.
i am using below piece of code, but i am getting suggestion that ClientCredentialsResourceDetails, OAuth2RestTemplate & OAuth2AccessToken are deprecated.

Can someone help with the alternate to this ?

```<code> private String getAuthTocken(){
     final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
     resourceDetails.setClientId("ceapiClientId");
     resourceDetails.setClientSecret("ceapiClientSecret");
     resourceDetails.setGrantType("client_credentials");
     resourceDetails.setAccessTokenUri("https://auth.abcdcommerce.com/oauth-server/oauth/token");

     final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
     final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken();

     final String accessTokenAsString = accessToken.getValue();
     return accessTokenAsString;
 }
</code>```

答:
The alternative is to use the new non-blocking WebClient or a RestTemplate with an interceptor over the deprecated OAuthRestTemplate. Everything in the spring-security-oauth artifacts has an end of life road map.

https://spring.io/blog/2019/11/14/spring-security-oauth-2-0-roadmap-update

https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Features-Matrix

The migration guide can be found here,

https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Migration-Guide

From the migration guide,

Spring Security chooses to favor composition and instead exposes an OAuth2AuthorizedClientService, which is useful for creating RestTemplateinterceptors or WebClient exchange filter functions. Spring Security provides ExchangeFilterFunction s for both Servlet- and WebFlux-based applications that both leverage this service.

There is a migration example available here,

https://github.com/jgrandja/spring-security-oauth-5-2-migrate

ContentLicense: CC BY-SA 4.0

Body:
I am new to spring security, and i come across to implement OAuth2 with client_credentials as Grant type.
i am using below piece of code, but i am getting suggestion that ClientCredentialsResourceDetails, OAuth2RestTemplate & OAuth2AccessToken are deprecated.

Can someone help with the alternate to this ?

 private String getAuthTocken(){
     final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
     resourceDetails.setClientId("ceapiClientId");
     resourceDetails.setClientSecret("ceapiClientSecret");
     resourceDetails.setGrantType("client_credentials");
     resourceDetails.setAccessTokenUri("https://auth.abcdcommerce.com/oauth-server/oauth/token");

     final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
     final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken();

     final String accessTokenAsString = accessToken.getValue();
     return accessTokenAsString;
 }


问:
how compilers detect overflow in numbers while compiling?
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255.

My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this case - against type limits?

I made a simple algorithm to do that for type 'int' for decimal, octal, hexadecimal and little endian binary but i don't think compiler do such thing like that to detect overflow in numbers.

the algorithm i made are coded in C++:

```<code>typedef signed char int8;
typedef signed int  int32;

#define DEC  0
#define HEX  1
#define OCT  2
#define BIN  3

bool isOverflow(const char* value, int32 base)
{
    // left-most digit for maximum and minimum number
    static const char* max_numbers[4][2] =
    {
        //                 INT_MAX                           INT_MIN
        {                       "2147483647",                       "2147483648" }, // decimal
        {                         "7fffffff",                         "80000000" }, // hexadecimal
        {                      "17777777777",                      "20000000000" }, // octal
        { "01111111111111111111111111111111", "10000000000000000000000000000000" }  // binary
    };

    // size of strings in max_numbers array
    static const int32 number_sizes[] = { 10, 8, 11, 32 };

    // input string size
    int32 str_len = strlen(value);

    // is sign mark exist in input string
    int32 signExist = ((base == DEC || base == OCT) && *value == '-');

    // first non zero digit in input number
    int32 non_zero_index = signExist;

    // locate first non zero index
    while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;

    // if non_zero_index equal length then all digits are zero
    if (non_zero_index == str_len) return false;

    // get number of digits that actually represent the number
    int32 diff = str_len - non_zero_index;

    // if difference less than 10 digits then no overflow will happened
    if (diff < number_sizes[base]) return false;
    // if difference greater than 10 digits then overflow will happened
    if (diff > number_sizes[base]) return true;

    // left digit in input and search strings
    int8 left1 = 0, left2 = 0;

    // if digits equal to 10 then loop over digits from left to right and compare
    for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
    {
        // get input digit
        left1 = value[non_zero_index];
        // get match digit
        left2 = max_numbers[signExist][i];

        // if digits not equal then if left1 is greater overflow will occurred, false otherwise
        if (left1 != left2) return left1 > left2;
    }

    // overflow won't happened
    return false;
}
</code>```

This algorithm can be optimized to work with all integers types but with float-point i have to make new one to work with IEEE float-point representation.

i think compilers use efficient algorithm to detect overflow other than mine, don't you?

答:
Seeing that compilers will have to convert to the integral/numeric type anyway, they can just as well let their atoi, atol, atof functions raise an error when the destination capacity gets exceeded.

There is no need to operate on strings beforehand, and convert in a separate step.

Most likely, I'd think, compilers will convert to integral types directly in their (highly optimized) parser's semantic actions.

ContentLicense: CC BY-SA 3.0

Body:
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255.

My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this case - against type limits?

I made a simple algorithm to do that for type 'int' for decimal, octal, hexadecimal and little endian binary but i don't think compiler do such thing like that to detect overflow in numbers.

the algorithm i made are coded in C++:

typedef signed char int8;
typedef signed int  int32;

#define DEC  0
#define HEX  1
#define OCT  2
#define BIN  3

bool isOverflow(const char* value, int32 base)
{
    // left-most digit for maximum and minimum number
    static const char* max_numbers[4][2] =
    {
        //                 INT_MAX                           INT_MIN
        {                       "2147483647",                       "2147483648" }, // decimal
        {                         "7fffffff",                         "80000000" }, // hexadecimal
        {                      "17777777777",                      "20000000000" }, // octal
        { "01111111111111111111111111111111", "10000000000000000000000000000000" }  // binary
    };

    // size of strings in max_numbers array
    static const int32 number_sizes[] = { 10, 8, 11, 32 };

    // input string size
    int32 str_len = strlen(value);

    // is sign mark exist in input string
    int32 signExist = ((base == DEC || base == OCT) && *value == '-');

    // first non zero digit in input number
    int32 non_zero_index = signExist;

    // locate first non zero index
    while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;

    // if non_zero_index equal length then all digits are zero
    if (non_zero_index == str_len) return false;

    // get number of digits that actually represent the number
    int32 diff = str_len - non_zero_index;

    // if difference less than 10 digits then no overflow will happened
    if (diff < number_sizes[base]) return false;
    // if difference greater than 10 digits then overflow will happened
    if (diff > number_sizes[base]) return true;

    // left digit in input and search strings
    int8 left1 = 0, left2 = 0;

    // if digits equal to 10 then loop over digits from left to right and compare
    for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
    {
        // get input digit
        left1 = value[non_zero_index];
        // get match digit
        left2 = max_numbers[signExist][i];

        // if digits not equal then if left1 is greater overflow will occurred, false otherwise
        if (left1 != left2) return left1 > left2;
    }

    // overflow won't happened
    return false;
}

This algorithm can be optimized to work with all integers types but with float-point i have to make new one to work with IEEE float-point representation.

i think compilers use efficient algorithm to detect overflow other than mine, don't you?


问:
Deep-merge with AMP.setState
I can't figure out how to overwrite data via AMP.setState.

I prepared an example:

I have a list of products, output via amp-list.

Each product has a 'quantity' value.

Each product has two buttons: increase the quantity and decrease it.

<!DOCTYPE html>

  <meta charset="utf-8" />

  <title>Hello, AMPs</title>
  <link rel="canonical" href="https://amp.dev/documentation/guides-and-tutorials/start/create/basic_markup/" />
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1" />

  <amp-state id="productData" src="https://alexkazakov.info/layout/amp-edit-array-state/data.json"></amp-state>

Welcome to the AMP web

  <amp-list height="100" items="." src="https://alexkazakov.info/layout/amp-edit-array-state/data.json" single-item [src]="productData">
    <template type="amp-mustache">
      {{#items}}

{{name}}

Quantity: {{quantity}}

        <button class="btn" on="tap:AMP.setState({productData: {items: {quantity: {{quantity}} + 1 } }})">Add +</button>
        <button class="btn" on="tap:AMP.setState({productData: {items: {quantity: {{quantity}} - 1 } }})">Reduce -</button>

      {{/items}}
    </template>
  </amp-list>

```
</div>
</div>
</p>

<p><strong>Here is the JSON that is used there:</strong></p>

<blockquote>
```{
  "items": [
    { "id": "0", "name": "Item 1", "price": 1.99, "quantity": 18 },
    { "id": "1", "name": "Item 2", "price": 2.99, "quantity": 15 },
    { "id": "2", "name": "Item 3", "price": 0.99, "quantity": 33 }
  ],
  "total": "9.94",
  "discount": "0%"
}
```

Codepen: https://codepen.io/alexandr-kazakov/pen/WNQWodZ

In my example, I overwrite the entire value of 'items', this is incorrect. I need that when you click on the button, the quantity of only one product decreases or increases. How do I do this?

答:
After many hours of thinking and trying I came to this decision:

I wrote two amp-bind-macro and completely overwrite the object.

In amp-bind-macro, I pass the index to determine which button was clicked. I searched a lot to see if the loop in amp-list has built-in indexes on each iteration, but I didn't find them. I have to take indexes from JSON.

I tried using the spread operator, but it doesn't seem to be supported in AMP. I had to do this, but the main thing is that I have solved my problem.

<!DOCTYPE html>

    <meta charset="utf-8" />

    <title>Hello, AMPs</title>
    <link rel="canonical" href="https://amp.dev/documentation/guides-and-tutorials/start/create/basic_markup/" />
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1" />

    <amp-state id="productData" src="https://alexkazakov.info/layout/amp-edit-array-state/data.json"></amp-state>

Welcome to the AMP web

    <amp-list height="100" items="." src="https://alexkazakov.info/layout/amp-edit-array-state/data.json" single-item [src]="productData">
      <template type="amp-mustache">
        {{#items}}

{{name}}

Quantity: {{quantity}}

        <amp-bind-macro id="addQuantity" arguments="argIndex" expression="productData.items.map((item, index, array) => index == argIndex ? {id: item.id, name: item.name, price: item.price, quantity: item.quantity + 1} : item )"></amp-bind-macro>
        <amp-bind-macro id="reduceQuantity" arguments="argIndex" expression="productData.items.map((item, index, array) => index == argIndex ? {id: item.id, name: item.name, price: item.price, quantity: item.quantity - 1} : item )"></amp-bind-macro>
        <button class="btn" on="tap:AMP.setState({productData: {items: addQuantity({{id}}) }})">Add +</button>
        <button class="btn" on="tap:AMP.setState({productData: {items: reduceQuantity({{id}}) }})">Reduce -</button>

        {{/items}}
      </template>
    </amp-list>

```

Working demo: https://codepen.io/alexandr-kazakov/pen/ExVJQYL

Title: Deep-merge with AMP.setState

Body:
I can't figure out how to overwrite data via AMP.setState.

I prepared an example:

I have a list of products, output via amp-list.

Each product has a 'quantity' value.

Each product has two buttons: increase the quantity and decrease it.

<!DOCTYPE html>

  <meta charset="utf-8" />

  <title>Hello, AMPs</title>
  <link rel="canonical" href="https://amp.dev/documentation/guides-and-tutorials/start/create/basic_markup/" />
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1" />

  <amp-state id="productData" src="https://alexkazakov.info/layout/amp-edit-array-state/data.json"></amp-state>

Welcome to the AMP web

  <amp-list height="100" items="." src="https://alexkazakov.info/layout/amp-edit-array-state/data.json" single-item [src]="productData">
    <template type="amp-mustache">
      {{#items}}

{{name}}

Quantity: {{quantity}}

        <button class="btn" on="tap:AMP.setState({productData: {items: {quantity: {{quantity}} + 1 } }})">Add +</button>
        <button class="btn" on="tap:AMP.setState({productData: {items: {quantity: {{quantity}} - 1 } }})">Reduce -</button>

      {{/items}}
    </template>
  </amp-list>

Here is the JSON that is used there:

{
  "items": [
    { "id": "0", "name": "Item 1", "price": 1.99, "quantity": 18 },
    { "id": "1", "name": "Item 2", "price": 2.99, "quantity": 15 },
    { "id": "2", "name": "Item 3", "price": 0.99, "quantity": 33 }
  ],
  "total": "9.94",
  "discount": "0%"
}

Codepen: https://codepen.io/alexandr-kazakov/pen/WNQWodZ

In my example, I overwrite the entire value of 'items', this is incorrect. I need that when you click on the button, the quantity of only one product decreases or increases. How do I do this?

Body:
After many hours of thinking and trying I came to this decision:

I wrote two amp-bind-macro and completely overwrite the object.

In amp-bind-macro, I pass the index to determine which button was clicked. I searched a lot to see if the loop in amp-list has built-in indexes on each iteration, but I didn't find them. I have to take indexes from JSON.

I tried using the spread operator, but it doesn't seem to be supported in AMP. I had to do this, but the main thing is that I have solved my problem.

<!DOCTYPE html>
<html amp lang="en">
  <head>
    <meta charset="utf-8" />
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>
    <script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
    <script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>

    <title>Hello, AMPs</title>
    <link rel="canonical" href="https://amp.dev/documentation/guides-and-tutorials/start/create/basic_markup/" />
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1" />
    <script type="application/ld+json">
      {
        "@context": "http://schema.org",
        "@type": "NewsArticle",
        "headline": "Open-source framework for publishing content",
        "datePublished": "2015-10-07T12:02:41Z",
        "image": ["logo.jpg"]
      }
    </script>
    <style amp-boilerplate>
      body {
        -webkit-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
        -moz-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
        -ms-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
        animation: -amp-start 8s steps(1, end) 0s 1 normal both;
      }

      @-webkit-keyframes -amp-start {
        from {
          visibility: hidden;
        }

        to {
          visibility: visible;
        }
      }

      @-moz-keyframes -amp-start {
        from {
          visibility: hidden;
        }

        to {
          visibility: visible;
        }
      }

      @-ms-keyframes -amp-start {
        from {
          visibility: hidden;
        }

        to {
          visibility: visible;
        }
      }

      @-o-keyframes -amp-start {
        from {
          visibility: hidden;
        }

        to {
          visibility: visible;
        }
      }

      @keyframes -amp-start {
        from {
          visibility: hidden;
        }

        to {
          visibility: visible;
        }
      }
    </style>
    <noscript>
      <style amp-boilerplate>
        body {
          -webkit-animation: none;
          -moz-animation: none;
          -ms-animation: none;
          animation: none;
        }
      </style>
    </noscript>
  </head>

  <body>
    <amp-state id="productData" src="https://alexkazakov.info/layout/amp-edit-array-state/data.json"></amp-state>

    <h1>Welcome to the AMP web</h1>

    <amp-list height="100" items="." src="https://alexkazakov.info/layout/amp-edit-array-state/data.json" single-item [src]="productData">
      <template type="amp-mustache">
        {{#items}}
        <h3>{{name}}</h3>
        <p>Quantity: {{quantity}}</p>

        <amp-bind-macro id="addQuantity" arguments="argIndex" expression="productData.items.map((item, index, array) => index == argIndex ? {id: item.id, name: item.name, price: item.price, quantity: item.quantity + 1} : item )"></amp-bind-macro>
        <amp-bind-macro id="reduceQuantity" arguments="argIndex" expression="productData.items.map((item, index, array) => index == argIndex ? {id: item.id, name: item.name, price: item.price, quantity: item.quantity - 1} : item )"></amp-bind-macro>
        <button class="btn" on="tap:AMP.setState({productData: {items: addQuantity({{id}}) }})">Add +</button>
        <button class="btn" on="tap:AMP.setState({productData: {items: reduceQuantity({{id}}) }})">Reduce -</button>
        <hr />
        {{/items}}
      </template>
    </amp-list>
  </body>
</html>

Working demo: https://codepen.io/alexandr-kazakov/pen/ExVJQYL


问:
How to receive the app delegate calls in a Swift Flutter plugin?
I am writing a Flutter plugin in Swift. I have successfully created the plugin and can call my Swift functions from Flutter using the default code that is generated when you create a new Flutter plugin. My Swift code currently looks like this.

public class MyFlutterPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "my_plugin", binaryMessenger: registrar.messenger())
    let instance = MyFlutterPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    if call.method == "hello" {
      result("hello from swift")
    } else {
      result(FlutterMethodNotImplemented)
    }
  }
}
```

I would like app delegate calls (for example when a notification is received) to be sent to my plugin. I would like to know how to make this work with Swift.

I have seen in the source code from some Objective C plugins the line [registrar addApplicationDelegate:instance];. But I don't know how to achieve anything like this in Swift and the official documentation doesn't seem to exist for this.

答:
It turns out it is fairly simple. Use registrar.addApplicationDelegate(instance) to register to receive the calls. Then include app delegate methods like this:

public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
    }
    let token = tokenParts.joined()
    channel.invokeMethod("onToken", arguments: token)
}
```

Body:
I am writing a Flutter plugin in Swift. I have successfully created the plugin and can call my Swift functions from Flutter using the default code that is generated when you create a new Flutter plugin. My Swift code currently looks like this.

public class MyFlutterPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "my_plugin", binaryMessenger: registrar.messenger())
    let instance = MyFlutterPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    if call.method == "hello" {
      result("hello from swift")
    } else {
      result(FlutterMethodNotImplemented)
    }
  }
}

I would like app delegate calls (for example when a notification is received) to be sent to my plugin. I would like to know how to make this work with Swift.

I have seen in the source code from some Objective C plugins the line [registrar addApplicationDelegate:instance];. But I don't know how to achieve anything like this in Swift and the official documentation doesn't seem to exist for this.


问:
Can't upload an image or pdf on codeigniter
I can't upload an image or pdf on my codeigniter

This is my view

```<code> <div class="form-group">
        <label>Upload Gambar</label>
        <input name="foto" type="file" class="form-control">
    </div>
</code>```

This is my controller

```<code> function form_pendaftaran_act(){
    $nik = $this->input->post('nik');
    $nama = $this->input->post('nama_anggota');
    $gender = $this->input->post('gender');
    $ttl = $this->input->post('ttl');
    $email = $this->input->post('email');
    $notelp = $this->input->post('notelp');
    $alamat = $this->input->post('alamat');
    $pendidikan = $this->input->post('pendidikan');
    $status = $this->input->post('status');
    $tinggi_badan = $this->input->post('tinggi_badan');
    $berat_badan = $this->input->post('berat_badan');
    $uk_baju = $this->input->post('uk_baju');
    $uk_celana = $this->input->post('uk_celana');
    $posisi = $this->input->post('posisi');

    $this->form_validation->set_rules('nama_anggota','Nama Anggota',
    'required');
    $this->form_validation->set_rules('email','Email','required');

   if($this->form_validation->run() != false){
      $config['upload_path'] = './assets/upload/';
      $config['allowed_types'] = 'jpg|png|jpeg|pdf';
      $config['max_size'] = '2048';
      $config['file_name'] = 'gambar'.time();

      $this->load->library('upload', $config);

      if($this->upload->do_upload('foto')){
        $image=$this->upload->data();

      $data = array(
        'nik' => $nik,
        'nama_anggota' => $nama,
        'gender' => $gender,
        'ttl' => $ttl,
        'email' => $email,
        'no_telp' => $notelp,
        'alamat' => $alamat,
        'pendidikan' => $pendidikan,
        'status' => $status,
        'tinggi_badan' => $tinggi_badan,
        'berat_badan' => $berat_badan,
        'uk_baju' => $uk_baju,
        'uk_celana' => $uk_celana,
        'posisi' => $posisi,
        'gambar' => $image['file_name']

         );

      $this->m_office->insert_data($data,'anggota');
      redirect(base_url().'member');
      }else{
        $this->session->set_flashdata
        ('alert', 'Anda Belum Memilih Foto');
      }
    }else{
      $this->load->view('member/header');
      $this->load->view('member/form_pendaftaran');
      $this->load->view('member/footer');
    }
      }
    }
</code>```

My problem is i can't upload the image or pdf. After i click submit on my view, the web just viewing a blank white screen. But, before i add the image configuration script, the web was doing well

答:
You have to make sure the form has the enctype specified or no files will upload.</p>

```<code><form action="/route" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label>Upload Gambar</label>
        <input name="foto" type="file" class="form-control">
    </div>
</form>
</code>```

Body:
I can't upload an image or pdf on my codeigniter

This is my view

        Upload Gambar
        <input name="foto" type="file" class="form-control">

This is my controller

 function form_pendaftaran_act(){
    $nik = $this->input->post('nik');
    $nama = $this->input->post('nama_anggota');
    $gender = $this->input->post('gender');
    $ttl = $this->input->post('ttl');
    $email = $this->input->post('email');
    $notelp = $this->input->post('notelp');
    $alamat = $this->input->post('alamat');
    $pendidikan = $this->input->post('pendidikan');
    $status = $this->input->post('status');
    $tinggi_badan = $this->input->post('tinggi_badan');
    $berat_badan = $this->input->post('berat_badan');
    $uk_baju = $this->input->post('uk_baju');
    $uk_celana = $this->input->post('uk_celana');
    $posisi = $this->input->post('posisi');

    $this->form_validation->set_rules('nama_anggota','Nama Anggota',
    'required');
    $this->form_validation->set_rules('email','Email','required');

   if($this->form_validation->run() != false){
      $config['upload_path'] = './assets/upload/';
      $config['allowed_types'] = 'jpg|png|jpeg|pdf';
      $config['max_size'] = '2048';
      $config['file_name'] = 'gambar'.time();

      $this->load->library('upload', $config);

      if($this->upload->do_upload('foto')){
        $image=$this->upload->data();

      $data = array(
        'nik' => $nik,
        'nama_anggota' => $nama,
        'gender' => $gender,
        'ttl' => $ttl,
        'email' => $email,
        'no_telp' => $notelp,
        'alamat' => $alamat,
        'pendidikan' => $pendidikan,
        'status' => $status,
        'tinggi_badan' => $tinggi_badan,
        'berat_badan' => $berat_badan,
        'uk_baju' => $uk_baju,
        'uk_celana' => $uk_celana,
        'posisi' => $posisi,
        'gambar' => $image['file_name']

         );

      $this->m_office->insert_data($data,'anggota');
      redirect(base_url().'member');
      }else{
        $this->session->set_flashdata
        ('alert', 'Anda Belum Memilih Foto');
      }
    }else{
      $this->load->view('member/header');
      $this->load->view('member/form_pendaftaran');
      $this->load->view('member/footer');
    }
      }
    }

My problem is i can't upload the image or pdf. After i click submit on my view, the web just viewing a blank white screen. But, before i add the image configuration script, the web was doing well

Body:
You have to make sure the form has the enctype specified or no files will upload.

<form action="/route" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label>Upload Gambar</label>
        <input name="foto" type="file" class="form-control">
    </div>
</form>


问:
Django how to assign posts to user
I need to assign posts to user in Django. I created

```<code>    user = models.ForeignKey('authentication.CustomUser', on_delete=models.CASCADE)
</code>```

and then if I display this model in my form.html I have to choice one of all users, if I don't display user in my form.html the form's isn't save my views file :

```<code>def formularz(request):
form = DodajForm(request.POST)
if form.is_valid():
    ogloszenie = form.save(commit=False)
    ogloszenie.user = request.user
    ogloszenie.save()
    return redirect('atrakcje:after')
else:
    ogloszenie = DodajForm()
context = {
            'form': form,}
return render(request, 'formularz.html', context)
</code>```

Can i please know how to resolve it?

答:
Rewrite the form to exclude the user field:

```<code>class DodajForm(forms.ModelForm):
    class Meta:
        model = Dodaj
        <b>exclude = ['user']</b></code>```

In the view, you better alter the instance, and let the form do the save logic, since a ModelForm can also save many-to-many fields:

```<code>def formularz(request):
    if request.method == 'POST':
        form = DodajForm(request.POST, request.FILES)
        if form.is_valid():
            form<b>.instance.user = request.user</b>
            <b>form.save()</b>
            return redirect('atrakcje:after')
    else:
        ogloszenie = DodajForm()
    context = {'form': form}
    return render(request, 'formularz.html', context)</code>```

Title: Django how to assign posts to user

Body:
I need to assign posts to user in Django. I created

    user = models.ForeignKey('authentication.CustomUser', on_delete=models.CASCADE)

and then if I display this model in my form.html I have to choice one of all users, if I don't display user in my form.html the form's isn't save my views file :

def formularz(request):
form = DodajForm(request.POST)
if form.is_valid():
    ogloszenie = form.save(commit=False)
    ogloszenie.user = request.user
    ogloszenie.save()
    return redirect('atrakcje:after')
else:
    ogloszenie = DodajForm()
context = {
            'form': form,}
return render(request, 'formularz.html', context)

Can i please know how to resolve it?

Body:
Rewrite the form to exclude the user field:

class DodajForm(forms.ModelForm):
    class Meta:
        model = Dodaj
        exclude = ['user']

In the view, you better alter the instance, and let the form do the save logic, since a ModelForm can also save many-to-many fields:

def formularz(request):
    if request.method == 'POST':
        form = DodajForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            return redirect('atrakcje:after')
    else:
        ogloszenie = DodajForm()
    context = {'form': form}
    return render(request, 'formularz.html', context)


问:
Kuberentes cluster IP vs FQDN of a service
I'm curious what's the benefit of using Cluster IP in kubernetes.
I know if one app needs to access service of other app. It can directly use FQDN of that service, without the trouble of creating Cluster IP.
But i still see lots of places Cluster IP being used. </p>

答:
From my exp FQDN  uses much more, however there are pretty much examples with Cluster IP direct usage. Benefit? dont think so. I think this is more philosophical question and you can do the way you prefer more.

Referring to  Connect a Front End to a Back End Using a Service from kubernetes page will show optimal way how to do similar things


问:
Add Request body Schema in loopback4
I'm new with loopback 4 and I really have difficulty with the documentation that is some time not up to date. I succeed to add an authentification system and a route to log in to the users. My problem is on the "/explorer" URL, I don't know how can I add example value on the request body schema of a custom route.

There is my route:

@post('/users/login', {
    responses: {
      '200': {
        description: 'Token',
        content: {
          'application/json': {
            schema: {
              type: 'object',
              properties: {
                token: {
                  type: 'string'
                }
              }
            }
          }
        }
      }
    }
  })
  async login(
    @requestBody() credentials: Credentials,
  ): Promise<{token: string}> {
    // make sure user exist,password should be valid
    const user = await this.userService.verifyCredentials(credentials);
    // console.log(user);
    const userProfile = await this.userService.convertToUserProfile(user);
    // console.log(userProfile);

    const token = await this.jwtService.generateToken(userProfile);
    return Promise.resolve({token: token})
  }
```

<p>And I wish to add:</p>

<pre class="lang-js prettyprint-override"><code>{
   "username": "string",
   "password": "string"
}
</code>```

Here:

I suppose that there is a simple way to do it but I really can't find anything about it.

答:
Thank you @Madaky. After reading your answer I just directly added the differents object directly in my route to not make extras files (i don't know if its a good practice) but it works.

There is the final code with the information added inside the "@requestBody" function:

  @post('/users/login', {
    responses: {
      '200': {
        description: 'Token',
        content: {
          'application/json': {
            schema: {
              type: 'object',
              properties: {
                token: {
                  type: 'string'
                }
              }
            }
          }
        }
      }
    }
  })
  async login(
    //here above inside @requestBody
    @requestBody(
      {
        description: 'Required input for login',
        required: true,
        content: {
          'application/json': {
            schema: {
              type: 'object',
              required: ['email', 'password'],
              properties: {
                username: {
                  type: 'string',
                },
                password: {
                  type: 'string',
                },
              },
            },
          }
        },
      }
    ) credentials: Credentials,
  ): Promise<{token: string}> {
    // make sure user exist,password should be valid
    const user = await this.userService.verifyCredentials(credentials);
    // console.log(user);
    const userProfile = await this.userService.convertToUserProfile(user);
    // console.log(userProfile);

    const token = await this.jwtService.generateToken(userProfile);
    return Promise.resolve({token: token})
  }

```

It's working like a charm, thank you!

Title: Add Request body Schema in loopback4

Body:
I'm new with loopback 4 and I really have difficulty with the documentation that is some time not up to date. I succeed to add an authentification system and a route to log in to the users. My problem is on the "/explorer" URL, I don't know how can I add example value on the request body schema of a custom route.

There is my route:

@post('/users/login', {
    responses: {
      '200': {
        description: 'Token',
        content: {
          'application/json': {
            schema: {
              type: 'object',
              properties: {
                token: {
                  type: 'string'
                }
              }
            }
          }
        }
      }
    }
  })
  async login(
    @requestBody() credentials: Credentials,
  ): Promise<{token: string}> {
    // make sure user exist,password should be valid
    const user = await this.userService.verifyCredentials(credentials);
    // console.log(user);
    const userProfile = await this.userService.convertToUserProfile(user);
    // console.log(userProfile);

    const token = await this.jwtService.generateToken(userProfile);
    return Promise.resolve({token: token})
  }

And I wish to add:

{
   "username": "string",
   "password": "string"
}

Here:

I suppose that there is a simple way to do it but I really can't find anything about it.

Body:
Thank you @Madaky. After reading your answer I just directly added the differents object directly in my route to not make extras files (i don't know if its a good practice) but it works.

There is the final code with the information added inside the "@requestBody" function:

  @post('/users/login', {
    responses: {
      '200': {
        description: 'Token',
        content: {
          'application/json': {
            schema: {
              type: 'object',
              properties: {
                token: {
                  type: 'string'
                }
              }
            }
          }
        }
      }
    }
  })
  async login(
    //here above inside @requestBody
    @requestBody(
      {
        description: 'Required input for login',
        required: true,
        content: {
          'application/json': {
            schema: {
              type: 'object',
              required: ['email', 'password'],
              properties: {
                username: {
                  type: 'string',
                },
                password: {
                  type: 'string',
                },
              },
            },
          }
        },
      }
    ) credentials: Credentials,
  ): Promise<{token: string}> {
    // make sure user exist,password should be valid
    const user = await this.userService.verifyCredentials(credentials);
    // console.log(user);
    const userProfile = await this.userService.convertToUserProfile(user);
    // console.log(userProfile);

    const token = await this.jwtService.generateToken(userProfile);
    return Promise.resolve({token: token})
  }

It's working like a charm, thank you!


问:
LINQ to JSON in .net 4.0 Client Profile
How would I go about about using LINQ to JSON in the .net 4 Client Profile in C#. I'd like to query certain json responses as shown in msdn blog post without having to write out a contract (datacontract, servicecontract, etc). I really only need to query(read) the response, I don't need to modify the json response. (Also would a datacontract be faster than LINQ to JSON?)

Alternatively I could use XML or the full .net 4 framework, but I'm hoping that this can be avoided. I can use external libraries if it's better than installing the whole framework.

答:
If your service is used by Ajax (jQuery) clients, you will get the best performance by using JSON.

Another recommendation; in order to get rid of the same domain policy, I recommend you to enable crossDomainScriptAccessEnabled functionality:

```<code>    <webHttpBinding>
      <binding name="myHttpBinding" crossDomainScriptAccessEnabled="true" />
    </webHttpBinding>
</code>```

Regarding the DataContract; in your scenario, a DataContract is not really needed.

Example code:

Your Service:

```<code>[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class BlogService {

     [OperationContract]
     [WebGet(ResponseFormat = WebMessageFormat.Json)]
     public List<Article> GetBlogArticles()
     {
         return Article.GetDummyArticles.ToList();
     }

}
</code>```

Article Class (excerpt):

```<code>public class Article    {

     public string Title { get; set; }
     public string Body { get; set; }

     public static IEnumerable<Article> GetDummyArticles() {
         yield return new Article { Title = "Article 1", Body = "sdlkfjsdlkfjskl" };
         yield return new Article { Title = "Article 2", Body = "sfsfsdfd23434wfdfsfdfkfjskl" };
     }
  }
</code>```

For your scenario I actually can't find a reason to use any (3rd-party) library since WCF4 already contains native support for JSON with or without Padding.

Title: LINQ to JSON in .net 4.0 Client Profile

Body:
If your service is used by Ajax (jQuery) clients, you will get the best performance by using JSON.

Another recommendation; in order to get rid of the same domain policy, I recommend you to enable crossDomainScriptAccessEnabled functionality:

    <webHttpBinding>
      <binding name="myHttpBinding" crossDomainScriptAccessEnabled="true" />
    </webHttpBinding>

Regarding the DataContract; in your scenario, a DataContract is not really needed.

Example code:

Your Service:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class BlogService {

     [OperationContract]
     [WebGet(ResponseFormat = WebMessageFormat.Json)]
     public List<Article> GetBlogArticles()
     {
         return Article.GetDummyArticles.ToList();
     }

}

Article Class (excerpt):

public class Article    {

     public string Title { get; set; }
     public string Body { get; set; }

     public static IEnumerable<Article> GetDummyArticles() {
         yield return new Article { Title = "Article 1", Body = "sdlkfjsdlkfjskl" };
         yield return new Article { Title = "Article 2", Body = "sfsfsdfd23434wfdfsfdfkfjskl" };
     }
  }

For your scenario I actually can't find a reason to use any (3rd-party) library since WCF4 already contains native support for JSON with or without Padding.


问:
JPA Criteria query to fetch data from master and child table with entitygraph
I am trying to fetch data from parent to child both based on filter criteria using JPA Criteria query so that can avoid multiple queries to DB, but not able to achieve desired result. Following are my sample entities( without getters/setters)

```<code>@Entity
public class ParentTable implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "ID")
    private String id;

    @Column(name = "KEY_COLUMN",length = 30)
    private String keyColumn;

    @Column(name = "CODE",length = 30)
    private String code;

    @Column(name = "KEY_DESC",length = 240)
    private String desc;

    @OneToMany(mappedBy = "parentTable",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<ChildTable> childTableList;
}

@Entity
public class ChildTable implements Serializable{

    private static final long serialVersionUID = 1L;

    public ChildTable() {
        super();
    }

    @Id
    @Column(name = "ID",length = 80)
    private String id;

    @Column(name = "PARENT_KEY_COLUMN",length = 30,insertable = false,updatable = false)
    private String parentKeyColumn;

    @Column(name = "CHILD_CODE",length = 30)
    private String childCode;

    @Column(name = "CHILD_DESC",length = 240)
    private String chldDesc;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "PARENT_KEY_COLUMN", referencedColumnName = "KEY_COLUMN")
    private ParentTable parentTable;

}
</code>```

Criteria builder snippet -

```<code>CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<ParentTable> query = cb.createQuery(ParentTable.class);
Root<ParentTable> fromParent = query.from(ParentTable.class);
Join<ParentTable, ChildTable> details = fromParent.join("childTableList");

List<Predicate> conditions = new ArrayList();
conditions.add(cb.equal(details.get("childCode"), childCode));
conditions.add(cb.equal(details.get("chldDesc"),chldDesc));

TypedQuery<ParentTable> typedQuery = em.createQuery(query.select(fromParent).where(conditions.toArray(new Predicate[] {})));
List<ParentTable> parentTableList = typedQuery.getResultList();
</code>```

This executes and gives result of parent table only, if i fetch childtable data I can see JPA query getting exceuted again, can this be avoided and fetch list of child entities which matches 3 dynamic params? 1. ParentTable.code, 2. ChildTable.childCode , 3. ChildTable.chldDesc .

Can anyone help me to construct JPA query like below which executes in one DB hit instead of multiple round trip, which is happening in above snippet of code?

```<code>select * from ParentTable p,ChildTable c where p.KEY_COLUMN=c.PARENT_KEY_COLUMN and p.CODE=? and c.CHILD_CODE=? and c.CHILD_DESC=?
</code>```

Update :

```<code>CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<ParentTable> cq = builder.createQuery(ParentTable.class);
Root<ParentTable> root = cq.from(ParentTable.class);
Join<ParentTable, ChildTable> join = root.join("childTableList");

Predicate p1=builder.equal(root.get("code"), "code");
Predicate p2=builder.like(join.get("chldDesc"), "%chldDesc%");
Predicate p3=builder.equal(join.get("childCode"), "childCode");
Predicate andPredicate = builder.and(p1,p2, p3);
cq.select(root).where(andPredicate);

EntityGraph<ParentTable> fetchGraph = entityManager.createEntityGraph(ParentTable.class);
fetchGraph.addSubgraph("childTableList");
List<ParentTable> parentTableList=entityManager.createQuery(cq).setHint("javax.persistence.loadgraph", fetchGraph).getResultList();
parentTableList.forEach(System.out::println);
</code>```

This approach forms the expected query like above mentioned but again one more query is formed like below , why second query is triggered even-though its not required?

```<code>select * from ParentTable  parentTable0_ where parentTable0_.code=?
</code>```

答:
JPA is required to give you managed entity results that reflect the data in the database. The filter you put on the query does not filter the internal relationships.

Your 'join' clause only affects the filter applied to returning ParentTable entities. Every entity returned will have a complete 'childTableList' collection, so even though you are returning ParentTable instances that have specific codes and descriptions, the childTableList shows all its children. That is JPA for you, and specific providers do have a way to filter these mapped collections (AdditionalCriteria ) IMO they are a bad route with many problems.

If you want to have childTableEntries that match the specific codes and descriptions, your query should be more of the form (using JPQL)

```<code>"Select c, p from ChildTable c join c.parentTable p where c.childCode = :code and c.chldDesc = :desc"
</code>```

This will return you a List result, where the Object array has the child and parent entries for each row that matches. So duplicate parents if one has more than one child that matches.

Otherwise, the extra query is being caused by accessing the childTableList on the parentTable entries, because they are marked lazy. Your criteria query is specifying 'join', as you want to use the childTableList entries in filtering parentTable entities. If you want the childTableList fetched with the parentTables, you need to use fetchJoins. Root implements FetchParent, which would allow you to specify a 'fetch' on the childTableList in addition to the join you've defined. In JPQL, something like:

```<code> "select p from ParentTable p fetch join p.childTableList, join p.childTableList c where c.childCode = :code and c.chldDesc = :desc"
</code>```

Body:
I am trying to fetch data from parent to child both based on filter criteria using JPA Criteria query so that can avoid multiple queries to DB, but not able to achieve desired result. Following are my sample entities( without getters/setters)

@Entity
public class ParentTable implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "ID")
    private String id;

    @Column(name = "KEY_COLUMN",length = 30)
    private String keyColumn;

    @Column(name = "CODE",length = 30)
    private String code;

    @Column(name = "KEY_DESC",length = 240)
    private String desc;

    @OneToMany(mappedBy = "parentTable",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<ChildTable> childTableList;
}

@Entity
public class ChildTable implements Serializable{

    private static final long serialVersionUID = 1L;

    public ChildTable() {
        super();
    }

    @Id
    @Column(name = "ID",length = 80)
    private String id;

    @Column(name = "PARENT_KEY_COLUMN",length = 30,insertable = false,updatable = false)
    private String parentKeyColumn;

    @Column(name = "CHILD_CODE",length = 30)
    private String childCode;

    @Column(name = "CHILD_DESC",length = 240)
    private String chldDesc;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "PARENT_KEY_COLUMN", referencedColumnName = "KEY_COLUMN")
    private ParentTable parentTable;

}

Criteria builder snippet -

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<ParentTable> query = cb.createQuery(ParentTable.class);
Root<ParentTable> fromParent = query.from(ParentTable.class);
Join<ParentTable, ChildTable> details = fromParent.join("childTableList");

List<Predicate> conditions = new ArrayList();
conditions.add(cb.equal(details.get("childCode"), childCode));
conditions.add(cb.equal(details.get("chldDesc"),chldDesc));

TypedQuery<ParentTable> typedQuery = em.createQuery(query.select(fromParent).where(conditions.toArray(new Predicate[] {})));
List<ParentTable> parentTableList = typedQuery.getResultList();

This executes and gives result of parent table only, if i fetch childtable data I can see JPA query getting exceuted again, can this be avoided and fetch list of child entities which matches 3 dynamic params? 1. ParentTable.code, 2. ChildTable.childCode , 3. ChildTable.chldDesc .

Can anyone help me to construct JPA query like below which executes in one DB hit instead of multiple round trip, which is happening in above snippet of code?

select * from ParentTable p,ChildTable c where p.KEY_COLUMN=c.PARENT_KEY_COLUMN and p.CODE=? and c.CHILD_CODE=? and c.CHILD_DESC=?

Update :

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<ParentTable> cq = builder.createQuery(ParentTable.class);
Root<ParentTable> root = cq.from(ParentTable.class);
Join<ParentTable, ChildTable> join = root.join("childTableList");

Predicate p1=builder.equal(root.get("code"), "code");
Predicate p2=builder.like(join.get("chldDesc"), "%chldDesc%");
Predicate p3=builder.equal(join.get("childCode"), "childCode");
Predicate andPredicate = builder.and(p1,p2, p3);
cq.select(root).where(andPredicate);

EntityGraph<ParentTable> fetchGraph = entityManager.createEntityGraph(ParentTable.class);
fetchGraph.addSubgraph("childTableList");
List<ParentTable> parentTableList=entityManager.createQuery(cq).setHint("javax.persistence.loadgraph", fetchGraph).getResultList();
parentTableList.forEach(System.out::println);

This approach forms the expected query like above mentioned but again one more query is formed like below , why second query is triggered even-though its not required?

select * from ParentTable  parentTable0_ where parentTable0_.code=?

Body:
JPA is required to give you managed entity results that reflect the data in the database. The filter you put on the query does not filter the internal relationships.

Your 'join' clause only affects the filter applied to returning ParentTable entities. Every entity returned will have a complete 'childTableList' collection, so even though you are returning ParentTable instances that have specific codes and descriptions, the childTableList shows all its children. That is JPA for you, and specific providers do have a way to filter these mapped collections (AdditionalCriteria ) IMO they are a bad route with many problems.

If you want to have childTableEntries that match the specific codes and descriptions, your query should be more of the form (using JPQL)

"Select c, p from ChildTable c join c.parentTable p where c.childCode = :code and c.chldDesc = :desc"

This will return you a List result, where the Object array has the child and parent entries for each row that matches. So duplicate parents if one has more than one child that matches.

Otherwise, the extra query is being caused by accessing the childTableList on the parentTable entries, because they are marked lazy. Your criteria query is specifying 'join', as you want to use the childTableList entries in filtering parentTable entities. If you want the childTableList fetched with the parentTables, you need to use fetchJoins. Root implements FetchParent, which would allow you to specify a 'fetch' on the childTableList in addition to the join you've defined. In JPQL, something like:

 "select p from ParentTable p fetch join p.childTableList, join p.childTableList c where c.childCode = :code and c.chldDesc = :desc"


问:
How to delete last element in array and put new in front?
I have a question concerning Java. I started up new to Java and my google search brought many results but non was the final help.
I created a class to track historical information. I have different values for different days and need to update them un a regular basis. I want to keep track of the last 30 days and created an array with 30 elements. When I call my 'shift' function I want to drop the last n elements and put zeros in front. Here is a minial example for 5 days:

```<code>public class Testclass {

    private int[] histInfo;

    public Element()
    {
        this.histInfo = new int[5];
    }

    public void shift_histInfo(long m)
    {
        //do magic
    }
}
</code>```

What I want shift to do is

```<code>INPUT:
histInfo = [50,21,1,45,901]

OPERATION:
shift_histInfo(2);

RESULT:
histInfo = [0,0,50,21,1]
</code>```

I am thankfull for every kind of help you can support as well for thought-provoking impulses if you think that there is a way more elegant or efficient way.

Best :-)

答:
Unless there are very tight performance constraints using the standard Collection classes will get the job done. Have a look at java.util.LinkedList.

As a programming exercise you might consider creating a ring buffer. The idea being to avoid copying the array on every insertion.

Keep a oldestIndex value.

When writing simply replace item[oldestIndex] and increment oldestIndex.

To iterate you start at oldestIndex and use an increment method to deal with wrapping round to the start of the array.

```<code>int nextIndex(int current) {
   return (current + 1) % arrayLength;
}
</code>```

Writing a nice encapsulating class to hide all this would be a good exercise.

Body:
I have a question concerning Java. I started up new to Java and my google search brought many results but non was the final help.
I created a class to track historical information. I have different values for different days and need to update them un a regular basis. I want to keep track of the last 30 days and created an array with 30 elements. When I call my 'shift' function I want to drop the last n elements and put zeros in front. Here is a minial example for 5 days:

public class Testclass {

    private int[] histInfo;

    public Element()
    {
        this.histInfo = new int[5];
    }

    public void shift_histInfo(long m)
    {
        //do magic
    }
}

What I want shift to do is

INPUT:
histInfo = [50,21,1,45,901]

OPERATION:
shift_histInfo(2);

RESULT:
histInfo = [0,0,50,21,1]

I am thankfull for every kind of help you can support as well for thought-provoking impulses if you think that there is a way more elegant or efficient way.

Best :-)

Body:
Unless there are very tight performance constraints using the standard Collection classes will get the job done. Have a look at java.util.LinkedList.

As a programming exercise you might consider creating a ring buffer. The idea being to avoid copying the array on every insertion.

Keep a oldestIndex value.

When writing simply replace item[oldestIndex] and increment oldestIndex.

To iterate you start at oldestIndex and use an increment method to deal with wrapping round to the start of the array.

int nextIndex(int current) {
   return (current + 1) % arrayLength;
}

Writing a nice encapsulating class to hide all this would be a good exercise.


问:
React route from another file is rendered on every path
I'm trying to separate routes into their own file, but they seem to be always rendered, even if I've added exact to the path.

Home route - home.js:

```<code>import React from 'react';
import { BrowserRouter as Route } from 'react-router-dom';

import { HomePageView } from 'components'

const HomeRoute = () => (
  <Route exact path='/home'>
    <HomePageContainer />
  </Route>
)
export default HomeRoute;
</code>```

HomePageView.js:

```<code>import React from 'react';

class HomePageView extends React.Component {
  render() {
    return (
      <div>Some text here</div>
    )
  }
}

export default HomePageView;
</code>```

index.js:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import HomeRoute from 'routes/home'
import * as serviceWorker from './serviceWorker';

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

The problem is that it renders the HomePageView component on any path and I don't understand why this happens because it works as expected if I replace <HomeRoute /> from index.js with:

```<code>  <Route exact path='/home'>
    <HomePageContainer />
  </Route>
</code>```

答:
I haven't tested this myself, but isn't the problem that you are importing BrowserRouter as Route in your home.js?

The file would looks like this when rendered:

  <BrowserRouter>
    <BrowserRouter>
       <HomePageContainer/>
    <BrowserRouter/>
  <BrowserRouter/>
```

<p>You need to import route from react-router-rom like this <code>import { Route } from "react-router-dom";</code></p>

<p>"as" in import is an alias, not what is imported.</p>

<p>Fixed home.js file:</p>

<pre class="lang-js prettyprint-override"><code>import React from 'react';
import { Route } from "react-router-dom";
import { HomePageView } from 'components'

const HomeRoute = () => (
  <Route exact path='/home'>
    <HomePageContainer />
  </Route>
)
export default HomeRoute;
</code>```

Body:
I'm trying to separate routes into their own file, but they seem to be always rendered, even if I've added exact to the path.

Home route - home.js:

import React from 'react';
import { BrowserRouter as Route } from 'react-router-dom';

import { HomePageView } from 'components'

const HomeRoute = () => (
  <Route exact path='/home'>
    <HomePageContainer />
  </Route>
)
export default HomeRoute;

HomePageView.js:

import React from 'react';

class HomePageView extends React.Component {
  render() {
    return (

Some text here

    )
  }
}

export default HomePageView;

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import HomeRoute from 'routes/home'
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <Router>
    <HomeRoute />
  </Router>,
  document.getElementById('root')
);

The problem is that it renders the HomePageView component on any path and I don't understand why this happens because it works as expected if I replace <HomeRoute /> from index.js with:

  <Route exact path='/home'>
    <HomePageContainer />
  </Route>

Body:
I haven't tested this myself, but isn't the problem that you are importing BrowserRouter as Route in your home.js?

The file would looks like this when rendered:

  <BrowserRouter>
    <BrowserRouter>
       <HomePageContainer/>
    <BrowserRouter/>
  <BrowserRouter/>

You need to import route from react-router-rom like this import { Route } from "react-router-dom";

"as" in import is an alias, not what is imported.

Fixed home.js file:

import React from 'react';
import { Route } from "react-router-dom";
import { HomePageView } from 'components'

const HomeRoute = () => (
  <Route exact path='/home'>
    <HomePageContainer />
  </Route>
)
export default HomeRoute;


问:
Java Script Date Function
Below JS to get current time does not return any value. I am calling the ecmascript function from my jsp page.</p>

```<code>function abc{
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}
</code>```

答:
This code work:</p>

```<code>function abc() {
 var today = new Date();
 return  today.getHours();
}

display.log(abc())
</code>```

Title: Java Script Date Function

Body:
Below JS to get current time does not return any value. I am calling the ecmascript function from my jsp page.

function abc{
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}

Body:
This code work:

function abc() {
 var today = new Date();
 return  today.getHours();
}

display.log(abc())


问:
How do I troubleshoot "simplexml_load_file() parser error: Entity 'nbsp' not defined"?
I use PHP to generate XML files. I have use some code below to avoid error.

```<code>$str = str_ireplace(array('<','>','&','\'','"'),array('<','>','&',''','"'),$str);
</code>```

but still cause fault.

```<code>simplexml_load_file() [function.simplexml-load-file] *[file name]* parser error : Entity 'nbsp' not defined in *[file name] [line]*
</code>```

The error text here:

```<code>Dallas  Dallas () is the third-largest city in Texas and the ninth-largest in the United States.
</code>```

In IE8, it seems to fault in (). So how many symbols should I notice?

Body:
I use PHP to generate XML files. I have use some code below to avoid error.

$str = str_ireplace(array('<','>','&','\'','"'),array('<','>','&',''','"'),$str);

but still cause fault.

simplexml_load_file() [function.simplexml-load-file] *[file name]* parser error : Entity 'nbsp' not defined in *[file name] [line]*

The error text here:

Dallas  Dallas () is the third-largest city in Texas and the ninth-largest in the United States.

In IE8, it seems to fault in (). So how many symbols should I notice?

Body:
&nbsp; is a HTML entity, but doesn't exist in XML.

Either get rid of it (you're not saying where it comes from, so it's hard to give any more specific advice), or wrap your HTML data in CDATA blocks so the parser ignores them.


问:
Css Grid Layout Issues ( with flexbox )
I'm trying to create a layout using the Flex structure. This is exactly the main image I wanted it to be.

This layout will also be compatible with the mobile view.

1- My Sidebar component doesn't stick to the bottom of my hero component. I used "margin-top: -200px;" for this problem. but I don't want that.

2- Between my components, I want to use margin as pictured. But because I calculate the size of each component as a percentage of "%" and they completely cover the page, if I give margin, they become wrap. What's the right way for me to do this ?

3- Do you think the flexbox settings I have applied are correct ? What would be better for me to change ?

Thank you in advance for your help.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.header {
  background-color: #59D4EB;
  text-align: center;
  height: 80px;
}

/* Main Container */

.container {
  display: flex;
  flex-flow: column nowrap;
  text-align: center;
}

/* Container */

.container-main {
  display: flex;
  flex-wrap: wrap;
}

/* Items */

.hero {
  flex: 1 0 40%;
  height: 400px;
  background-color: #D5C9E2;
}

.main-content {
  flex: 1 0 60%;
  height: 600px;
  background-color: #F5C546;
}

.sidebar {
  height: 500px;
  flex: 1 0 40%;
  background-color: #A0C263;
  /* I DONT WANT USE THİS  MARGİN-TOP */
  margin-top: -200px;
}

.extra-content {
  flex: 1 0 60%;
  background-color: #898989;
  height: 300px;
}

/* Container */

.images-posts-cont {
  display: flex;
  height: 150px;
}

/* Items */

.images {
  flex: 1 0 70%;
  background-color: #53B774;
}

.posts {
  flex: 1 0 30%;
  background-color: #F3CDDD;
}

/* Footer */

.footer {
  text-align: center;
  height: 80px;
  background-color: #F4A540;
}

@media screen and (max-width:599px) {
  .hero {
    flex: 1 0 100%;
    order: 1;
  }
  .sidebar {
    flex: 1 0 100%;
    order: 2;
  }
  .main-content {
    order: 3;
  }
  .extra-content {
    order: 4;
  }
}

;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="src/css/test.css">
  <title> Flexbox Layout</title>
</head>

<body>
  <!-- FlexBox Layout -->
  <header class="header">
    <h2>header</h2>
  </header>
  <div class="container">
    <section class="container-main">
      <div class="hero">
        <h2>hero</h2>
      </div>
      <div class="main-content">
        <h2>main-content</h2>
      </div>
      <div class="sidebar">
        <h2>sidebar</h2>
      </div>
      <div class="extra-content">
        <h2>extra content</h2>
      </div>
    </section>
    <section class="images-posts-cont">
      <div class="images">
        <h2>related images</h2>
      </div>
      <div class="posts">
        <h2>related posts</h2>
      </div>
    </section>
    <footer class="footer">
      <h2>footer</h2>
    </footer>
  </div>

</body>

</html></code>```

答:
There can be 2 grids here , one with the header the contents and the footer, and then another grid inside the content area.

Here is a possibility to start from for such a layout with grid  where a break point can turn the second grid into a flex column layout with a mediaquerie (set at 500px for the demo):

body {
  /* first grid of 3 rows , flex can do it too */
  min-height: 100vh;
  margin: 0;
  display: grid;
  grid-template-rows: auto 1fr auto;
}

body main {
  /* second grid for the contents in between header and footer */
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  margin: 5px 0;
  grid-gap: 5px;
}

header {
  background: #74d3e8;
}

/* set each element inside cell(s) of the grid */

.main {
  grid-row: 1 / span 2;
  grid-column: 2 / span 2;
  background: #f0c354;
}

.hero {
  grid-column: 1;
  grid-row: 1;
  background: #d4cbe0;
}

.sidebar {
  grid-column: 1;
  grid-row: 2 / span 2;
  background: #a7be6d;
}

.extra {
  grid-column: 2 / span 2;
  grid-row: 3;
  background: #898989;
}

.relI {
  grid-column: 1 / span 2;
  grid-row: 4;
  background: #58b076;
}

.relP {
  grid-column: 3;
  grid-row: 4;
  background: #edd0de;
}

footer {
  background: #f4a540;
}

/* set here your break point */

@media screen and (max-width: 500px) {
  body main {
    display: flex;
    flex-flow: column;
  }
  .main {
    flex: 1;
  }

  /* from you can use order to reset order of the boxes in main */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>header</header>
<main>
  <article class="main">Main content</article>
  <section class="hero">hero</section>
  <aside class="sidebar">Sidebar</aside>
  <section class="extra">Extra content</section>
  <aside class="relI">Related images</aside>
  <aside class="relP">Related post</aside>
</main>
<footer>Footer</footer></code>```

Usefull ressource to go further : https://gridbyexample.com/ */ https://css-tricks.com/snippets/css/complete-guide-grid/

here is a demo to play with : https://codepen.io/gc-nomade/pen/jObgNOO

Title: Css Grid Layout Issues ( with flexbox )

Body:
I'm trying to create a layout using the Flex structure. This is exactly the main image I wanted it to be.

This layout will also be compatible with the mobile view.

1- My Sidebar component doesn't stick to the bottom of my hero component. I used "margin-top: -200px;" for this problem. but I don't want that.

2- Between my components, I want to use margin as pictured. But because I calculate the size of each component as a percentage of "%" and they completely cover the page, if I give margin, they become wrap. What's the right way for me to do this ?

3- Do you think the flexbox settings I have applied are correct ? What would be better for me to change ?

Thank you in advance for your help.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.header {
  background-color: #59D4EB;
  text-align: center;
  height: 80px;
}

/* Main Container */

.container {
  display: flex;
  flex-flow: column nowrap;
  text-align: center;
}

/* Container */

.container-main {
  display: flex;
  flex-wrap: wrap;
}

/* Items */

.hero {
  flex: 1 0 40%;
  height: 400px;
  background-color: #D5C9E2;
}

.main-content {
  flex: 1 0 60%;
  height: 600px;
  background-color: #F5C546;
}

.sidebar {
  height: 500px;
  flex: 1 0 40%;
  background-color: #A0C263;
  /* I DONT WANT USE THİS  MARGİN-TOP */
  margin-top: -200px;
}

.extra-content {
  flex: 1 0 60%;
  background-color: #898989;
  height: 300px;
}

/* Container */

.images-posts-cont {
  display: flex;
  height: 150px;
}

/* Items */

.images {
  flex: 1 0 70%;
  background-color: #53B774;
}

.posts {
  flex: 1 0 30%;
  background-color: #F3CDDD;
}

/* Footer */

.footer {
  text-align: center;
  height: 80px;
  background-color: #F4A540;
}

@media screen and (max-width:599px) {
  .hero {
    flex: 1 0 100%;
    order: 1;
  }
  .sidebar {
    flex: 1 0 100%;
    order: 2;
  }
  .main-content {
    order: 3;
  }
  .extra-content {
    order: 4;
  }
}

;

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="src/css/test.css">
  <title> Flexbox Layout</title>

header

hero

main-content

sidebar

extra content

related images

related posts

footer

Body:
There can be 2 grids here , one with the header the contents and the footer, and then another grid inside the content area.

Here is a possibility to start from for such a layout with grid  where a break point can turn the second grid into a flex column layout with a mediaquerie (set at 500px for the demo):

body {
  /* first grid of 3 rows , flex can do it too */
  min-height: 100vh;
  margin: 0;
  display: grid;
  grid-template-rows: auto 1fr auto;
}

body main {
  /* second grid for the contents in between header and footer */
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  margin: 5px 0;
  grid-gap: 5px;
}

header {
  background: #74d3e8;
}

/* set each element inside cell(s) of the grid */

.main {
  grid-row: 1 / span 2;
  grid-column: 2 / span 2;
  background: #f0c354;
}

.hero {
  grid-column: 1;
  grid-row: 1;
  background: #d4cbe0;
}

.sidebar {
  grid-column: 1;
  grid-row: 2 / span 2;
  background: #a7be6d;
}

.extra {
  grid-column: 2 / span 2;
  grid-row: 3;
  background: #898989;
}

.relI {
  grid-column: 1 / span 2;
  grid-row: 4;
  background: #58b076;
}

.relP {
  grid-column: 3;
  grid-row: 4;
  background: #edd0de;
}

footer {
  background: #f4a540;
}

/* set here your break point */

@media screen and (max-width: 500px) {
  body main {
    display: flex;
    flex-flow: column;
  }
  .main {
    flex: 1;
  }

  /* from you can use order to reset order of the boxes in main */
}

<header>header</header>
<main>
  <article class="main">Main content</article>
  <section class="hero">hero</section>
  <aside class="sidebar">Sidebar</aside>
  <section class="extra">Extra content</section>
  <aside class="relI">Related images</aside>
  <aside class="relP">Related post</aside>
</main>
<footer>Footer</footer>

Usefull ressource to go further : https://gridbyexample.com/ */ https://css-tricks.com/snippets/css/complete-guide-grid/

here is a demo to play with : https://codepen.io/gc-nomade/pen/jObgNOO


问:
SQL query to find duplicate records and discount from COUNT
I am using below SQL query to count the records.
I would like to discount the duplicate testID after I got the count.

example:

```<code>select COUNT(*)  from PRODUCT where CLASS_TYPE = 'test'
</code>```

above query give 5 records

```<code>testID
1234-00-01
1234-00-01
1234-00-02
1234-00-02
1111222233
</code>```

I want to get the count = 5 - duplicate 2 = 3

Is there SQL query I can use to find out the duplicate records, then calculate the final count?

答:
You want count(distinct):

```<code>select count(distinct testID)
from product p
where p.class_type = 'test'
</code>```

Body:
I am using below SQL query to count the records.
I would like to discount the duplicate testID after I got the count.

example:

select COUNT(*)  from PRODUCT where CLASS_TYPE = 'test'

above query give 5 records

testID
1234-00-01
1234-00-01
1234-00-02
1234-00-02
1111222233

I want to get the count = 5 - duplicate 2 = 3

Is there SQL query I can use to find out the duplicate records, then calculate the final count?

Body:
You want count(distinct):

select count(distinct testID)
from product p
where p.class_type = 'test'


答:
You can use distinct :

```<code>select count(distinct col) as Unique_CNT, COUNT(*) as all_CNT
from PRODUCT
where CLASS_TYPE = 'test';
</code>```

Title: SQL query to find duplicate records and discount from COUNT

Body:
You can use distinct :

select count(distinct col) as Unique_CNT, COUNT(*) as all_CNT
from PRODUCT
where CLASS_TYPE = 'test';


问:
How do you pass a variant dim to a string when concatenating?
I'm trying to export a file with a specific name (where different parts of the name are variables). So far, the first two strings are not causing issues. The problem arises when I perform the index match function and get a variant data type value. I'm unable to convert the variant type to string to use later on in the code. Snippet below:

```<code>Sub Export_Imgs()

    Dim tempSht as Range
    Dim dataSht as Range
    Dim matCell as Range
    Dim jobNum as Range
    Dim buildDate As String
    Dim buildID As String
    Dim imgFile As String
    Dim matID As Variant
    Dim imgMap As String
    Dim imgPDF As String
    Dim imgJPG As String

    Set tempSht = ThisWorkbook.Sheets("Template")
    Set dataSht = ThisWorkbook.Sheets("Machines & Material")
    Set matCell = tempSht.Range("$E$81")
    Set jobNum = tempSht.Range("$E$12")

    'Define file name variables
    buildDate = Format(Date, "YYYY-MM-DD")
    buildID = Left(jobNum, InStr(jobNum, ".") - 1)
    matID = WorksheetFunction.Index((dataSht.ListObjects("AMmat").ListColumns(4).DataBodyRange), _
        WorksheetFunction.Match(matCell, dataSht.ListObjects("AMmat").ListColumns(1).DataBodyRange, 0))

        imgMap = "C:\Users\Example\Desktop\"
        imgJPG = buildDate & "_" & buildID & "_" & CStr(matID) & ".jpg"
        imgFile = imgMap & imgJPG

End Sub
</code>```

I get a "type mismatch" error on the imgJPG line towards the bottom of the code. I feel as if I'm missing something quite simple. Any help would be greatly appreciated.

答:
I wouldn't use Index here, but instead something like the following approach:

```<code>With dataSht.ListObjects("AMmat")
    Dim rw
    rw = Application.Match(matCell.Value, .ListColumns(1).DataBodyRange, 0)

    If Not IsError(rw) Then
        matId = .ListColumns(4).DataBodyRange.Cells(rw).Value
    End If
End With
</code>```

Body:
I'm trying to export a file with a specific name (where different parts of the name are variables). So far, the first two strings are not causing issues. The problem arises when I perform the index match function and get a variant data type value. I'm unable to convert the variant type to string to use later on in the code. Snippet below:

Sub Export_Imgs()

    Dim tempSht as Range
    Dim dataSht as Range
    Dim matCell as Range
    Dim jobNum as Range
    Dim buildDate As String
    Dim buildID As String
    Dim imgFile As String
    Dim matID As Variant
    Dim imgMap As String
    Dim imgPDF As String
    Dim imgJPG As String

    Set tempSht = ThisWorkbook.Sheets("Template")
    Set dataSht = ThisWorkbook.Sheets("Machines & Material")
    Set matCell = tempSht.Range("$E$81")
    Set jobNum = tempSht.Range("$E$12")

    'Define file name variables
    buildDate = Format(Date, "YYYY-MM-DD")
    buildID = Left(jobNum, InStr(jobNum, ".") - 1)
    matID = WorksheetFunction.Index((dataSht.ListObjects("AMmat").ListColumns(4).DataBodyRange), _
        WorksheetFunction.Match(matCell, dataSht.ListObjects("AMmat").ListColumns(1).DataBodyRange, 0))

        imgMap = "C:\Users\Example\Desktop\"
        imgJPG = buildDate & "_" & buildID & "_" & CStr(matID) & ".jpg"
        imgFile = imgMap & imgJPG

End Sub

I get a "type mismatch" error on the imgJPG line towards the bottom of the code. I feel as if I'm missing something quite simple. Any help would be greatly appreciated.

Body:
I wouldn't use Index here, but instead something like the following approach:

With dataSht.ListObjects("AMmat")
    Dim rw
    rw = Application.Match(matCell.Value, .ListColumns(1).DataBodyRange, 0)

    If Not IsError(rw) Then
        matId = .ListColumns(4).DataBodyRange.Cells(rw).Value
    End If
End With


问:
SQLAlchemy query db with filter for all tables
I have SQLAlchemy models on top of the MySQL db. I need to query almost all models (string or text fields) and find everything that contains a specific substring. And also, apply common filtering like object_type=type1. For exsmple:

```<code>class Model1(Model):
    name = Column(String(100), nullable=False, unique=True)
    version = Column(String(100))
    description = Column(String(100))
    updated_at = Column(TIMESTAMP(timezone=True))
    # other fields

class Model2(Model):
    name = Column(String(100), nullable=False, unique=True)
    version = Column(String(100))
    description = Column(String(100))
    updated_at = Column(TIMESTAMP(timezone=True))
    # other fields

class Model3(Model):
    name = Column(String(100), nullable=False, unique=True)
    version = Column(String(100))
    description = Column(String(100))
    updated_at = Column(TIMESTAMP(timezone=True))
    # other fields
</code>```

And then do query something like:

```<code>db.query(
    Model1.any_of_all_columns.contains('sub_string') or
    Model2.any_of_all_columns.contains('sub_string') or
    Model3.any_of_all_columns.contains('sub_string')
).all()
</code>```

Is it possible to build such an ORM query in one SQL to the db and dynamically add Model(table) names and columns?

答:
For applying common filtering for all the columns, you can subscribe to sqlachemy events as following:

```<code>@event.listens_for(Query, "before_compile", retval=True)
def before_compile(query):

for ent in query.column_descriptions:
    entity = ent['entity']
    if entity is None:
        continue

    inspect_entity_for_mapper = inspect(ent['entity'])
    mapper = getattr(inspect_entity_for_mapper, 'mapper', None)

    if mapper and has_tenant_id:

        query = query.enable_assertions(False).filter(
            ent['entity’].object == object)

return query
</code>```

This function will be called whenever you do Model.query() and add filter for your object.

Body:
I have SQLAlchemy models on top of the MySQL db. I need to query almost all models (string or text fields) and find everything that contains a specific substring. And also, apply common filtering like object_type=type1. For exsmple:

class Model1(Model):
    name = Column(String(100), nullable=False, unique=True)
    version = Column(String(100))
    description = Column(String(100))
    updated_at = Column(TIMESTAMP(timezone=True))
    # other fields

class Model2(Model):
    name = Column(String(100), nullable=False, unique=True)
    version = Column(String(100))
    description = Column(String(100))
    updated_at = Column(TIMESTAMP(timezone=True))
    # other fields

class Model3(Model):
    name = Column(String(100), nullable=False, unique=True)
    version = Column(String(100))
    description = Column(String(100))
    updated_at = Column(TIMESTAMP(timezone=True))
    # other fields

And then do query something like:

db.query(
    Model1.any_of_all_columns.contains('sub_string') or
    Model2.any_of_all_columns.contains('sub_string') or
    Model3.any_of_all_columns.contains('sub_string')
).all()

Is it possible to build such an ORM query in one SQL to the db and dynamically add Model(table) names and columns?

Body:
For applying common filtering for all the columns, you can subscribe to sqlachemy events as following:

@event.listens_for(Query, "before_compile", retval=True)
def before_compile(query):

for ent in query.column_descriptions:
    entity = ent['entity']
    if entity is None:
        continue

    inspect_entity_for_mapper = inspect(ent['entity'])
    mapper = getattr(inspect_entity_for_mapper, 'mapper', None)

    if mapper and has_tenant_id:

        query = query.enable_assertions(False).filter(
            ent['entity’].object == object)

return query

This function will be called whenever you do Model.query() and add filter for your object.


问:
OneToMany SQL Relationships
I want to have a OneToMany relationship with SQL, and a ManyToOne relationship. I have a Ticket entity, and a TeamMember entity. However, when I first save the Ticket entity, I will not know the TeamMember, and if I set it to null I get this:

2020-05-29 23:49:55.754
ERROR 24020 --- [onPool-worker-2]  o.h.engine.jdbc.spi.SqlExceptionHelper:
Column 'team_member_id' cannot be null
```

<p>What should I do?</p>

<p>Ticket:</p>

<pre class="lang-kotlin prettyprint-override"><code>data class Ticket(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id:Long = 0,
    val ticketId:String,
    var price:Int? = null,
    val openDate:LocalDateTime = LocalDateTime.now(),
    var closeDate:LocalDateTime? = null,
    var paypalId:String? = null,
    var paid:Boolean = false,
    var status:TicketStatus = TicketStatus.OPEN,
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "team_member_id", nullable = false)
    val teamMember: TeamMember? = null,
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "customer_id", nullable = false)
    val customer:Customer
)
</code>```

TeamMember:

@Entity
data class TeamMember(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id:Long = 0,
    val discordId:String,
    val joinDate:LocalDateTime,
    val ordersCompleted:Int,
    val amountMade:Int,
    val email:String,
    val pastWork:String,
    @OneToMany(mappedBy = "teamMember", cascade = [CascadeType.ALL],
            orphanRemoval = true, fetch = FetchType.EAGER)
    val tickets:Set<Ticket> = setOf()
)
```

答:
Look at this part of your code (of Ticket):

@JoinColumn(name = "team_member_id", nullable = false)
val teamMember: TeamMember? = null
```

You set the SQL column to be non-null using nullable=false.

However, you declared the attribute as TeamMember? and you set it to null.

You can either set teamMember to something that is not null before persisting it or set nullable to true (depending on what you need).

Title: OneToMany SQL Relationships

Body:
I want to have a OneToMany relationship with SQL, and a ManyToOne relationship. I have a Ticket entity, and a TeamMember entity. However, when I first save the Ticket entity, I will not know the TeamMember, and if I set it to null I get this:

2020-05-29 23:49:55.754
ERROR 24020 --- [onPool-worker-2]  o.h.engine.jdbc.spi.SqlExceptionHelper:
Column 'team_member_id' cannot be null

What should I do?

Ticket:

data class Ticket(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id:Long = 0,
    val ticketId:String,
    var price:Int? = null,
    val openDate:LocalDateTime = LocalDateTime.now(),
    var closeDate:LocalDateTime? = null,
    var paypalId:String? = null,
    var paid:Boolean = false,
    var status:TicketStatus = TicketStatus.OPEN,
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "team_member_id", nullable = false)
    val teamMember: TeamMember? = null,
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "customer_id", nullable = false)
    val customer:Customer
)

TeamMember:

@Entity
data class TeamMember(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id:Long = 0,
    val discordId:String,
    val joinDate:LocalDateTime,
    val ordersCompleted:Int,
    val amountMade:Int,
    val email:String,
    val pastWork:String,
    @OneToMany(mappedBy = "teamMember", cascade = [CascadeType.ALL],
            orphanRemoval = true, fetch = FetchType.EAGER)
    val tickets:Set<Ticket> = setOf()
)

Body:
Look at this part of your code (of Ticket):

@JoinColumn(name = "team_member_id", nullable = false)
val teamMember: TeamMember? = null

You set the SQL column to be non-null using nullable=false.

However, you declared the attribute as TeamMember? and you set it to null.

You can either set teamMember to something that is not null before persisting it or set nullable to true (depending on what you need).