问:
Batch script: \MyProg was unexpected at this time
I have a simple batch script test.bat that iterates thru command-line arguments:

```<code>@echo off
set prefix=C:\Program Files\MyProg
for %%x in (%*) do (
    echo %prefix%
)
</code>```

this version of the script works without issue in cmd.exe:

```<code>C:\>test a b
C:\Program Files\MyProg
C:\Program Files\MyProg
</code>```

However, if I modify the batch file to have a different prefix value, adding (x86):

```<code>set prefix=C:\Program Files (x86)\MyProg
</code>```

the script fails:

```<code>C:\>test a b
\MyProg was unexpected at this time.
</code>```

what a disaster! How can I resolve this issue?

答:
I recommend to first read How does the Windows Command Interpreter (CMD.EXE) parse scripts?

Windows command processor parses an entire code block starting with ( and ending with the matching ) before executing the command making use of the command block. During processing of a command block all environment variable references in the form %variable% are replaced by the current value of the environment variables or removed on an environment variable not existing at all. So the command block finally executed does not contain anymore any %variable%. That behavior is very good explained at Variables are not behaving as expected.

So the code

```<code>set prefix=C:\Program Files (x86)\MyProg
for %%x in (%*) do (
    echo %prefix%
)
</code>```

results in executing FOR with

```<code>echo C:\Program Files (x86)\MyProg
</code>```

The closing parenthesis ) is not inside an argument string being enclosed in ". For that reason the Windows command processor interprets it as end of the command block of command FOR.

It is syntactically not correct to specify one more command on same line after ) being interpreted as end of a command block without usage of an operator like & or && or ||. For that reason \MyProg is interpreted as syntactically invalid command after ) marking end of the command block.

The help output by running cmd /? in a command prompt window explains at end of last page that a file name containing a space or one of these characters &()[]{}^=;!'+,`~ must be enclosed in " to get all these characters interpreted literally with exception of ! if delayed environment variable expansion is enabled, too.

The usage of " around an argument string is not only required for file names, but for any argument string containing a space or one of these characters &()[]{}^=;!'+,`~ or the redirection operators <|> which should be also interpreted literally by cmd.exe.

So one solution would be:

```<code>set prefix=C:\Program Files (x86)\MyProg
for %%x in (%*) do (
    echo "%prefix%"
)
</code>```

ECHO outputs the prefix with both ", but it is good practice to output file/folder names with ECHO always enclosed in double quotes.

Another solution is escaping ) with ^ to be interpreted as literal character. In this case it is important that the line with echo still has ^) after replacing %prefix% by the string value assigned to the environment variable prefix. For that reason it is necessary to define the prefix string with caret character interpreted as literal character which means two ^ are necessary left to ) on environment variable definition.

```<code>set prefix=C:\Program Files (x86^^)\MyProg
for %%x in (%*) do (
    echo %prefix%
)
</code>```

The environment variable prefix is defined now with the string value:

```<code>C:\Program Files (x86^)\MyProg
</code>```

This results in the FOR command block in getting ) interpreted as literal character.

It is also possible to define environment variable prefix with being enclosed in double quotes to get caret character ^ interpreted as literal character which avoids the need to double this character being otherwise interpreted as escape character.

```<code>set "prefix=C:\Program Files (x86^)\MyProg"
for %%x in (%*) do (
    echo %prefix%
)
</code>```

One more solution is using delayed environment variable expansion:

```<code>@echo off
set prefix=C:\Program Files (x86)\MyProg
setlocal EnableDelayedExpansion
for %%x in (%*) do (
    echo !prefix!
)
endlocal
</code>```

But there is a problem with this solution caused by double parsing of the command lines because of enabled delayed expansion as it can be seen on modifying the code to

```<code>@echo off
set prefix=C:\Program Files (x86)\MyProg
setlocal EnableDelayedExpansion
for %%x in (%*) do (
    echo !prefix!\%%~x
)
endlocal
</code>```

and executing the batch file with the three arguments Hello! and Test and Start!. The exclamation marks are no longer interpreted as literal characters because of enabled delayed expansion. For that reason the output is:

```<code>C:\Program Files (x86)\MyProg\Hello
</code>```

But the output should be:

```<code>C:\Program Files (x86)\MyProg\Hello!
C:\Program Files (x86)\MyProg\Test
C:\Program Files (x86)\MyProg\Start!
</code>```

This output can be get with:

```<code>echo C:\Program Files (x86)\MyProg
</code>```0

However, really safe is printing the concatenated strings enclosed in double quotes.

```<code>echo C:\Program Files (x86)\MyProg
</code>```1

The output is in this case for the above example with the three arguments Hello! and Test and Start!:

```<code>echo C:\Program Files (x86)\MyProg
</code>```2

See also my answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? It explains why the environment variable prefix is defined with using " left to variable name and at end of the string value assigned to the environment variable. That is the recommended syntax on definition of an environment variable.

Further, it is good practice not using as loop variable a case-sensitive interpreted letter for which a case-insensitive interpreted modifier exists as otherwise the results can be unexpected, especially on variable strings being concatenated dynamically.

Example:

```<code>@echo off
cls
echo Loop with %%~Xx:
for %%x in ("1" 2 3) do echo %%~Xx run.
echo Loop with %%~xX:
for %%X in ("1" 2 3) do echo %%~xX run.
echo Loop with %%~Ix:
for %%I in ("1" 2 3) do echo %%~Ix run.
echo Loop with %%~#x:
for %%# in ("1" 2 3) do echo %%~#x run.
pause
</code>```

The output of this small batch file is:

```<code>Loop with %~Xx:
 run.
 run.
 run.
Loop with %~xX:
 run.
 run.
 run.
Loop with %~Ix:
1x run.
2x run.
3x run.
Loop with %~#x:
1x run.
2x run.
3x run.
</code>```

The intention is here to get output the number with x appended and not to reference the not existing file extension of the three strings in set of command FOR.

Therefore the modifier letters ADFNPSTXZadfnpstxz should not be used as loop variable although it is possible in most cases.

Body:
I have a simple batch script test.bat that iterates thru command-line arguments:

@echo off
set prefix=C:\Program Files\MyProg
for %%x in (%*) do (
    echo %prefix%
)

this version of the script works without issue in cmd.exe:

C:\>test a b
C:\Program Files\MyProg
C:\Program Files\MyProg

However, if I modify the batch file to have a different prefix value, adding (x86):

set prefix=C:\Program Files (x86)\MyProg

the script fails:

C:\>test a b
\MyProg was unexpected at this time.

what a disaster! How can I resolve this issue?

Body:
I recommend to first read How does the Windows Command Interpreter (CMD.EXE) parse scripts?

Windows command processor parses an entire code block starting with ( and ending with the matching ) before executing the command making use of the command block. During processing of a command block all environment variable references in the form %variable% are replaced by the current value of the environment variables or removed on an environment variable not existing at all. So the command block finally executed does not contain anymore any %variable%. That behavior is very good explained at Variables are not behaving as expected.

So the code

set prefix=C:\Program Files (x86)\MyProg
for %%x in (%*) do (
    echo %prefix%
)

results in executing FOR with

echo C:\Program Files (x86)\MyProg

The closing parenthesis ) is not inside an argument string being enclosed in ". For that reason the Windows command processor interprets it as end of the command block of command FOR.

It is syntactically not correct to specify one more command on same line after ) being interpreted as end of a command block without usage of an operator like & or && or ||. For that reason \MyProg is interpreted as syntactically invalid command after ) marking end of the command block.

The help output by running cmd /? in a command prompt window explains at end of last page that a file name containing a space or one of these characters &()[]{}^=;!'+,`~ must be enclosed in " to get all these characters interpreted literally with exception of ! if delayed environment variable expansion is enabled, too.

The usage of " around an argument string is not only required for file names, but for any argument string containing a space or one of these characters &()[]{}^=;!'+,`~ or the redirection operators <|> which should be also interpreted literally by cmd.exe.

So one solution would be:

set prefix=C:\Program Files (x86)\MyProg
for %%x in (%*) do (
    echo "%prefix%"
)

ECHO outputs the prefix with both ", but it is good practice to output file/folder names with ECHO always enclosed in double quotes.

Another solution is escaping ) with ^ to be interpreted as literal character. In this case it is important that the line with echo still has ^) after replacing %prefix% by the string value assigned to the environment variable prefix. For that reason it is necessary to define the prefix string with caret character interpreted as literal character which means two ^ are necessary left to ) on environment variable definition.

set prefix=C:\Program Files (x86^^)\MyProg
for %%x in (%*) do (
    echo %prefix%
)

The environment variable prefix is defined now with the string value:

C:\Program Files (x86^)\MyProg

This results in the FOR command block in getting ) interpreted as literal character.

It is also possible to define environment variable prefix with being enclosed in double quotes to get caret character ^ interpreted as literal character which avoids the need to double this character being otherwise interpreted as escape character.

set "prefix=C:\Program Files (x86^)\MyProg"
for %%x in (%*) do (
    echo %prefix%
)

One more solution is using delayed environment variable expansion:

@echo off
set prefix=C:\Program Files (x86)\MyProg
setlocal EnableDelayedExpansion
for %%x in (%*) do (
    echo !prefix!
)
endlocal

But there is a problem with this solution caused by double parsing of the command lines because of enabled delayed expansion as it can be seen on modifying the code to

@echo off
set prefix=C:\Program Files (x86)\MyProg
setlocal EnableDelayedExpansion
for %%x in (%*) do (
    echo !prefix!\%%~x
)
endlocal

and executing the batch file with the three arguments Hello! and Test and Start!. The exclamation marks are no longer interpreted as literal characters because of enabled delayed expansion. For that reason the output is:

C:\Program Files (x86)\MyProg\Hello

But the output should be:

C:\Program Files (x86)\MyProg\Hello!
C:\Program Files (x86)\MyProg\Test
C:\Program Files (x86)\MyProg\Start!

This output can be get with:

set "prefix=C:\Program Files (x86^)\MyProg"
for %%x in (%*) do (
    echo %prefix%\%%~x
)

However, really safe is printing the concatenated strings enclosed in double quotes.

set "prefix=%ProgramFiles(x86)%\MyProg"
for %%I in (%*) do (
    echo "%prefix%\%%~I"
)

The output is in this case for the above example with the three arguments Hello! and Test and Start!:

"C:\Program Files (x86)\MyProg\Hello!"
"C:\Program Files (x86)\MyProg\Test"
"C:\Program Files (x86)\MyProg\Start!"

See also my answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? It explains why the environment variable prefix is defined with using " left to variable name and at end of the string value assigned to the environment variable. That is the recommended syntax on definition of an environment variable.

Further, it is good practice not using as loop variable a case-sensitive interpreted letter for which a case-insensitive interpreted modifier exists as otherwise the results can be unexpected, especially on variable strings being concatenated dynamically.

Example:

@echo off
cls
echo Loop with %%~Xx:
for %%x in ("1" 2 3) do echo %%~Xx run.
echo Loop with %%~xX:
for %%X in ("1" 2 3) do echo %%~xX run.
echo Loop with %%~Ix:
for %%I in ("1" 2 3) do echo %%~Ix run.
echo Loop with %%~#x:
for %%# in ("1" 2 3) do echo %%~#x run.
pause

The output of this small batch file is:

Loop with %~Xx:
 run.
 run.
 run.
Loop with %~xX:
 run.
 run.
 run.
Loop with %~Ix:
1x run.
2x run.
3x run.
Loop with %~#x:
1x run.
2x run.
3x run.

The intention is here to get output the number with x appended and not to reference the not existing file extension of the three strings in set of command FOR.

Therefore the modifier letters ADFNPSTXZadfnpstxz should not be used as loop variable although it is possible in most cases.


来源: stackexchange

问:
How to generate mocks for open API spec file by using openapi-generator
faq-generators says generating the server code as a starting point to implement the API backend, here are some use cases of the server generators:

mocking - easily provide an API backend for mocking based on the examples field defined in the response object.

I'm curious how to do that by using Gradle plugin for spring (did not the proper example).

答:
I generate a mocks.json based on my swagger examples in swagger.json and swager-codegen using a this mustache template:

```<code>
{
    {{#apiInfo}}
        {{#apis}}"{{classname}}":
            { {{#operations}}
                {{#operation}}
                    {{#examples}}
                        "{{nickname}}": {{#example}}{{{example}}}{{/example}}{{^example}}null{{/example}}{{#hasMore}},{{/hasMore}}
                    {{/examples}}
                {{/operation}}
              {{/operations}}
            } {{#hasMore}},{{/hasMore}}
        {{/apis}}
    {{/apiInfo}}
}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I generate a mocks.json based on my swagger examples in swagger.json and swager-codegen using a this mustache template:

{
    {{#apiInfo}}
        {{#apis}}"{{classname}}":
            { {{#operations}}
                {{#operation}}
                    {{#examples}}
                        "{{nickname}}": {{#example}}{{{example}}}{{/example}}{{^example}}null{{/example}}{{#hasMore}},{{/hasMore}}
                    {{/examples}}
                {{/operation}}
              {{/operations}}
            } {{#hasMore}},{{/hasMore}}
        {{/apis}}
    {{/apiInfo}}
}


问:
Migrate a SharePoint 2013 WSP (web part) to SharePoint 2019 (On-Prem)
I'm fairly new to SP 2019 (On-prem), but haven't had much luck finding information regarding moving a SP13 web part to SP 2019. It looks like I may have to recreate it using the SharePoint Framework. Does anyone have experience with migrating an existing SP 2013 webpart successfully to SP 2019 (on-prem) or is the Framework the only way to do that now?</p>

答:
In SharePoint 2019, still support to use WSP Web Part in classic page.

You can copy the web part solution into SharePoint 2019 and open with Visual Studio, change the SharePoint.dll reference to SharePoint 2019's version, rebuild and test if this web part have some exception, then deploy with Visual Studio directly.

Here are some points you will need to care:

Consideration when upgrading WSP'S from One SharePoint version to another

For Modern Page experience, it's necessary to recreate SPFX Solution and achieve the same function.

Build your first SharePoint client-side web part


问:
How to remove the back button in the header react native
I want to remove the button back, but leave the header.

My component is as follows. I want to leave the title, and I don’t need the back button.

```<code>import React from 'react';
import { View } from 'react-native';

export const TrucksScreen = () => {
    return (
        <View>
           ....
        </View>
    );
});

TrucksScreen.navigationOptions = {
    headerTitle: 'Trucks Screen',
};
</code>```

How can I remove the button back?

答:
According to the docs you can replace the header back button with whatever you want by passing options param in stack navigator . Do find the working example : expo-snack:

```<code>import * as React from 'react';
import { View, Text, Button, Image } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function HomeScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
    </View>
  );
}

function LogoTitle() {
  return (
    <Image
      style={{ width: 50, height: 50 }}
      source={require('@expo/snack-static/react-native-logo.png')}
    />
  );
}

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={HomeScreen}
          options={{
            headerTitle: props => <LogoTitle {...props} />,
            headerRight: () => (
              <Button
                onPress={() => alert('This is a button!')}
                title="Info"
                color="#00cc00"
              />
            ),
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;
</code>```

Hopeit helps. feel free for doubts

Body:
I want to remove the button back, but leave the header.

My component is as follows. I want to leave the title, and I don’t need the back button.

import React from 'react';
import { View } from 'react-native';

export const TrucksScreen = () => {
    return (
        <View>
           ....
        </View>
    );
});

TrucksScreen.navigationOptions = {
    headerTitle: 'Trucks Screen',
};

How can I remove the button back?

Body:
According to the docs you can replace the header back button with whatever you want by passing options param in stack navigator . Do find the working example : <a href="https://snack.expo.io/?platform=android&name=header%20button&dependencies=%40react-native-community%2Fmasked-view%40%5E0.1.1%2C%40react-navigation%2Fnative%40%5E5.0.1%2C%40react-navigation%2Fbottom-tabs%40%5E5.0.1%2C%40react-navigation%2Fdrawer%40%5E5.0.1%2C%40react-navigation%2Fmaterial-bottom-tabs%40%5E5.0.1%2C%40react-navigation%2Fmaterial-top-tabs%40%5E5.0.1%2C%40react-navigation%2Fnative-stack%40%5E5.0.1%2C%40react-navigation%2Fstack%40%5E5.0.1%2Creact-native-gesture-handler%401.5.2%2Creact-native-reanimated%401.4.0%2Creact-native-safe-area-context%400.6.0%2Creact-native-screens%402.0.0-alpha.12&sourceUrl=https%3A%2F%2Freactnavigation.org%2Fexamples%2F5.x%2Fsimple-header-button.js" rel="nofollow noreferrer">expo-snack:

import * as React from 'react';
import { View, Text, Button, Image } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function HomeScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
    </View>
  );
}

function LogoTitle() {
  return (
    <Image
      style={{ width: 50, height: 50 }}
      source={require('@expo/snack-static/react-native-logo.png')}
    />
  );
}

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={HomeScreen}
          options={{
            headerTitle: props => <LogoTitle {...props} />,
            headerRight: () => (
              <Button
                onPress={() => alert('This is a button!')}
                title="Info"
                color="#00cc00"
              />
            ),
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Hopeit helps. feel free for doubts


问:
How to insert Ansible std_outlines output JSON into MongoDB with Python
I am running the following task in my playbook

```<code>- name: get system info
shell: uname -r
register: uname_out
- debug: var=uname_out
when: conn_out is success
- name: copy
copy:
  content={{ uname_out.stdout_lines }} dest={{inventory_hostname}}.json
</code>```

I get the JSON output like this

```<code>["rhel", "linux", "7", "basevesrion"]
</code>```

To insert this data into MongoDB, I am writing the script as follows

```<code>import json
from pymongo import MongoClient
fileName = "data.json"
print(fileName)

client = MongoClient('10.*.*.*',27017)
db = client['test']
collection_cmdbFact = db['facts']
with open(fileName,'r') as data_file:
  data_json = json.loads(data_file.read())
collection.insert_one(data_json)
client.close()
</code>```

I am getting this error

TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

Can someone tell me how do I insert this data?

答:
I ran a quick test.  This works fine:

```<code>collection.insert_one(json.loads("{\"a\":1}"))
</code>```

While this returns the exact error you noted:

```<code>collection.insert_one(json.loads("[{\"a\":1},{\"a\":2}]"))
</code>```

If your file contains an array of documents, you might need to use insert_many:

```<code>collection.insert_many(json.loads("[{\"a\":1},{\"a\":2}]"))
</code>```

Body:
I am running the following task in my playbook

- name: get system info
shell: uname -r
register: uname_out
- debug: var=uname_out
when: conn_out is success
- name: copy
copy:
  content={{ uname_out.stdout_lines }} dest={{inventory_hostname}}.json

I get the JSON output like this

["rhel", "linux", "7", "basevesrion"]

To insert this data into MongoDB, I am writing the script as follows

import json
from pymongo import MongoClient
fileName = "data.json"
print(fileName)

client = MongoClient('10.*.*.*',27017)
db = client['test']
collection_cmdbFact = db['facts']
with open(fileName,'r') as data_file:
  data_json = json.loads(data_file.read())
collection.insert_one(data_json)
client.close()

I am getting this error

TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

Can someone tell me how do I insert this data?

Body:
I ran a quick test.  This works fine:

collection.insert_one(json.loads("{\"a\":1}"))

While this returns the exact error you noted:

collection.insert_one(json.loads("[{\"a\":1},{\"a\":2}]"))

If your file contains an array of documents, you might need to use insert_many:

collection.insert_many(json.loads("[{\"a\":1},{\"a\":2}]"))


问:
Select min date value and calculate date value?
I have a table called "SUMMARYDATA" which has columns "STATUSIN,STATUSOUT,LATECOME" and I want to select min value on column "STATUSIN". And make a condition: IF MIN(STATUSIN) > "08.00 AM" Then LATECOME = MIN(STATUSIN) - "08.00 AM". How to select min date value? And how to calculate MIN(STATUSIN) - "08.00 AM"?

This is my code to display data from database:

```<code>    <asp:Repeater ID="rptrSUMMARYDATA" runat="server">
        <HeaderTemplate>
            <table class="table">
                <thead>
                    <tr>
                        <th>IN</th>
                        <th>OUT</th>
                        <th>LATECOME</th>
                    </tr>
                </thead>
                <tbody>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td><%# Eval("STATUSIN") %></td>
                <td><%# Eval("STATUSOUT") %></td>
                <td><%# Eval("LATECOME") %></td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
                </tbody>
            </table>
        </FooterTemplate>
    </asp:Repeater>
</code>```

This is my code on backend:

```<code>     private void BindSUMMARYDATARptr()
    {
        String CS = ConfigurationManager.ConnectionStrings["MANHOURConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM SUMMARYDATA", con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dtDaily = new DataTable();
                    sda.Fill(dtDaily);

                    rptrSUMMARYDATA.DataSource = dtDaily;
                    rptrSUMMARYDATA.DataBind();
                }

            }

        }
    }
</code>```

答:
Get the MIN from datatable and use DateTime.Subtract

```<code>var minIN = Convert.ToDateTime(dt.AsEnumerable().Min(row => row["IN"]));
Console.WriteLine($"LATECOME {minIN.Subtract(minIN.Date + new TimeSpan(8, 0, 0))}");
</code>```

Note: AsEnumerable is part of System.Data.DataSetExtensions. Install this package from nuget

To Update directly in Database (I would not recommend this, unless it is absolutely needed)

```<code>UPDATE SUMMARYDATA
  SET LATECOME =  CASE WHEN DATEDIFF(s,DATEADD(HOUR, 8, CAST(CAST((select MIN(STATUSIN) from SUMMARYDATA)  AS DATE) AS DATETIME)),(select MIN(STATUSIN) from SUMMARYDATA)) > 0 THEN
  (CONVERT(TIME,(select MIN(STATUSIN) from SUMMARYDATA)-DATEADD(HOUR, 8, CAST(CAST((select MIN(STATUSIN) from SUMMARYDATA)  AS DATE) AS DATETIME)))) ELSE NULL END
</code>```

Body:
I have a table called "SUMMARYDATA" which has columns "STATUSIN,STATUSOUT,LATECOME" and I want to select min value on column "STATUSIN". And make a condition: IF MIN(STATUSIN) > "08.00 AM" Then LATECOME = MIN(STATUSIN) - "08.00 AM". How to select min date value? And how to calculate MIN(STATUSIN) - "08.00 AM"?

This is my code to display data from database:

    <asp:Repeater ID="rptrSUMMARYDATA" runat="server">
        <HeaderTemplate>

                        IN
                        OUT
                        LATECOME

        </HeaderTemplate>
        <ItemTemplate>

                <%# Eval("STATUSIN") %>
                <%# Eval("STATUSOUT") %>
                <%# Eval("LATECOME") %>

        </ItemTemplate>
        <FooterTemplate>

        </FooterTemplate>
    </asp:Repeater>

This is my code on backend:

     private void BindSUMMARYDATARptr()
    {
        String CS = ConfigurationManager.ConnectionStrings["MANHOURConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM SUMMARYDATA", con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dtDaily = new DataTable();
                    sda.Fill(dtDaily);

                    rptrSUMMARYDATA.DataSource = dtDaily;
                    rptrSUMMARYDATA.DataBind();
                }

            }

        }
    }

Body:
Get the MIN from datatable and use DateTime.Subtract

var minIN = Convert.ToDateTime(dt.AsEnumerable().Min(row => row["IN"]));
Console.WriteLine($"LATECOME {minIN.Subtract(minIN.Date + new TimeSpan(8, 0, 0))}");

Note: AsEnumerable is part of System.Data.DataSetExtensions. Install this package from nuget

To Update directly in Database (I would not recommend this, unless it is absolutely needed)

UPDATE SUMMARYDATA
  SET LATECOME =  CASE WHEN DATEDIFF(s,DATEADD(HOUR, 8, CAST(CAST((select MIN(STATUSIN) from SUMMARYDATA)  AS DATE) AS DATETIME)),(select MIN(STATUSIN) from SUMMARYDATA)) > 0 THEN
  (CONVERT(TIME,(select MIN(STATUSIN) from SUMMARYDATA)-DATEADD(HOUR, 8, CAST(CAST((select MIN(STATUSIN) from SUMMARYDATA)  AS DATE) AS DATETIME)))) ELSE NULL END


问:
Cannot read property 'length' of null on Angular Service method call?
I'm modifying an existing Angular project (not mine), adding a new call to my external API.

This is the service method:

getUserName(): Observable<any> {
    return this.http.get<any>(environment.apiUrl + URLS.USER_NAME)
}
```

<p>And I use it on <strong>appcomponent.ts</strong> as following:</p>

<pre class="lang-js prettyprint-override"><code>this.userService.getUserName().subscribe((name) => {
  this.user = name
})
</code>```

When executing I get the following error:

core.js:1673 ERROR TypeError: Cannot read property 'length' of null
      at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.applyUpdate
  (http.js:199)
      at http.js:170
      at Array.forEach ()
      at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.init
  (http.js:170)
      at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.forEach
  (http.js:235)
      at Observable._subscribe (http.js:1435)
      at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe
  (Observable.js:43)
      at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
  (Observable.js:29)
      at MapOperator.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call
  (map.js:18)
      at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
  (Observable.js:24)

It seems to be a headers problem or some subscribe/observable error, but I can't find where the error is.

Is there something wrong with my code?

It could be an existing interceptor that is modifying the request?

Note that the exception is thrown before making the request, so it must be a client problem when creating that request.

Edit:

This is the only interceptor I found:

```<code>@Injectable({
  providedIn: 'root'
})
export class TenantHttpInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.url.indexOf(environment.apiTFSmin) === -1) {
      let tenantReq = req.clone({ headers: req.headers.set('current', sessionStorage.getItem('current')) })
      if (sessionStorage.getItem('tenant') != null && sessionStorage.getItem('newTenant') == null) {
        tenantReq = tenantReq.clone({ headers: tenantReq.headers.append('Tenant', sessionStorage.getItem('tenant')) })
      } else if (sessionStorage.getItem('newTenant') != null) {
        tenantReq = tenantReq.clone({ headers: tenantReq.headers.append('Tenant', sessionStorage.getItem('newTenant')) })
        sessionStorage.removeItem('newTenant')
      }
      if (req.method === 'POST' || req.method === 'PUT') {
        tenantReq = tenantReq.clone({ headers: tenantReq.headers.append('Content-Type', 'application/json') })
      }
      return next.handle(tenantReq)
    } else {
      const tenantReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + btoa('pescanilla-ext:m12345678*')) })
      // const tenantReq = req.clone()
      return next.handle(tenantReq)
    }
  }
}
</code>```

答:
You are not checking the 'current' header to actually exist in the storage.

```<code>let tenantReq = req.clone({ headers: req.headers.set('current', sessionStorage.getItem('current')) })
</code>```

Edit: The HttpClient will throw an error once you try to send a request with header with null value. Try replacing the sessionStorage.getItem('current') with a static value and test it.

Body:
I'm modifying an existing Angular project (not mine), adding a new call to my external API.

This is the service method:

getUserName(): Observable<any> {
    return this.http.get<any>(environment.apiUrl + URLS.USER_NAME)
}

And I use it on appcomponent.ts as following:

this.userService.getUserName().subscribe((name) => {
  this.user = name
})

When executing I get the following error:

core.js:1673 ERROR TypeError: Cannot read property 'length' of null
      at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.applyUpdate
  (http.js:199)
      at http.js:170
      at Array.forEach ()
      at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.init
  (http.js:170)
      at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.forEach
  (http.js:235)
      at Observable._subscribe (http.js:1435)
      at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe
  (Observable.js:43)
      at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
  (Observable.js:29)
      at MapOperator.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call
  (map.js:18)
      at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
  (Observable.js:24)

It seems to be a headers problem or some subscribe/observable error, but I can't find where the error is.

Is there something wrong with my code?

It could be an existing interceptor that is modifying the request?

Note that the exception is thrown before making the request, so it must be a client problem when creating that request.

Edit:

This is the only interceptor I found:

@Injectable({
  providedIn: 'root'
})
export class TenantHttpInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.url.indexOf(environment.apiTFSmin) === -1) {
      let tenantReq = req.clone({ headers: req.headers.set('current', sessionStorage.getItem('current')) })
      if (sessionStorage.getItem('tenant') != null && sessionStorage.getItem('newTenant') == null) {
        tenantReq = tenantReq.clone({ headers: tenantReq.headers.append('Tenant', sessionStorage.getItem('tenant')) })
      } else if (sessionStorage.getItem('newTenant') != null) {
        tenantReq = tenantReq.clone({ headers: tenantReq.headers.append('Tenant', sessionStorage.getItem('newTenant')) })
        sessionStorage.removeItem('newTenant')
      }
      if (req.method === 'POST' || req.method === 'PUT') {
        tenantReq = tenantReq.clone({ headers: tenantReq.headers.append('Content-Type', 'application/json') })
      }
      return next.handle(tenantReq)
    } else {
      const tenantReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + btoa('pescanilla-ext:m12345678*')) })
      // const tenantReq = req.clone()
      return next.handle(tenantReq)
    }
  }
}

Body:
You are not checking the 'current' header to actually exist in the storage.

let tenantReq = req.clone({ headers: req.headers.set('current', sessionStorage.getItem('current')) })

Edit: The HttpClient will throw an error once you try to send a request with header with null value. Try replacing the sessionStorage.getItem('current') with a static value and test it.


问:
Wordpress Category Image in Categories response using Advanced Custom Fields returning null
I am trying to add a category image field category image in categories response using Advanced Custom Field.

But the field is returning null, here is my code.

```<code>function addCategoryImage(){
    register_rest_field('category', 'categoryImage', array(
        'taxonomy' => 'category',
        'get_callback' => function() {
            $category = get_the_category();
            return get_field('category_image', 'category_' . $category_id);
        }

    ));
};

add_action('rest_api_init', 'addCategoryImage');
</code>```

答:
After doing some research I found the exact answer I am looking for. The call back functions has these args.

```<code>    'get_callback' => function ( $object, $field_name, $request, $object_type ) {
    // ...
}
</code>```

So I get the $object for each category from which I can get the term id. Here is the updated code.

```<code>function addCategoryImage(){
    register_rest_field('category', 'categoryImage', array(
        'get_callback' => function($cat) {
            return get_field('category_image', 'category_' . $cat['id']);
        }

    ));
};
add_action('rest_api_init', 'addCategoryImage');
</code>```

Body:
I am trying to add a category image field category image in categories response using Advanced Custom Field.

But the field is returning null, here is my code.

function addCategoryImage(){
    register_rest_field('category', 'categoryImage', array(
        'taxonomy' => 'category',
        'get_callback' => function() {
            $category = get_the_category();
            return get_field('category_image', 'category_' . $category_id);
        }

    ));
};

add_action('rest_api_init', 'addCategoryImage');

Body:
After doing some research I found the exact answer I am looking for. The call back functions has these args.

    'get_callback' => function ( $object, $field_name, $request, $object_type ) {
    // ...
}

So I get the $object for each category from which I can get the term id. Here is the updated code.

function addCategoryImage(){
    register_rest_field('category', 'categoryImage', array(
        'get_callback' => function($cat) {
            return get_field('category_image', 'category_' . $cat['id']);
        }

    ));
};
add_action('rest_api_init', 'addCategoryImage');


问:
Problem with mochawesome: TypeError: Cannot set property 'testsRegistered' of undefined
After running autotest instead of getting mochawesome report I get "Problem with mochawesome: TypeError: Cannot set property 'testsRegistered' of undefined"

I've tried to update to "mochawesome": "^4.1.0" and reinstall package but these didn't help

答: Need to install mocha globally. That solved my issue</p>


问:
How to search on mongoose with exclude
i have 2 Schema like bellow, i need to get 50 item from videoInfos which not have in userInfos.watched (this array content _id of videoInfos). Please use syntax like videoInfos.find().exce if you can.</p>

```<code>const userSchema = new mongoose.Schema({
    username:String,
    password:String,
    point: Number,
    watched: Array,//content _id of videoInfos
    running: Array,
});

const userInfos = mongoose.model('userInfos', userSchema);
//======================================================
const videoSchema = new mongoose.Schema({
    owner:String,
    videoID:String,
    totalTime: Number,
    totalView:Number,
    finish: Number,
    didFinish:Boolean,
});

const videoInfos = mongoose.model('videoInfos', videoSchema);
</code>```

答:
Since you are using mongoose you can achieve it like this.

Change the schema like this:

```<code>const userSchema = new mongoose.Schema({
    username:String,
    password:String,
    point: Number,
    watched: [{ type: Schema.Types.ObjectId, ref: 'videoInfos' }],
    running: Array,
});
</code>```

And query like this:

```<code>userInfos.find({}).populate('watched');
</code>```

The watched array should be populated with videoInfo data.

For more, take a look at mongoose populate.

Title: How to search on mongoose with exclude

Body:
i have 2 Schema like bellow, i need to get 50 item from videoInfos which not have in userInfos.watched (this array content _id of videoInfos). Please use syntax like videoInfos.find().exce if you can.

const userSchema = new mongoose.Schema({
    username:String,
    password:String,
    point: Number,
    watched: Array,//content _id of videoInfos
    running: Array,
});

const userInfos = mongoose.model('userInfos', userSchema);
//======================================================
const videoSchema = new mongoose.Schema({
    owner:String,
    videoID:String,
    totalTime: Number,
    totalView:Number,
    finish: Number,
    didFinish:Boolean,
});

const videoInfos = mongoose.model('videoInfos', videoSchema);

Body:
Since you are using mongoose you can achieve it like this.

Change the schema like this:

const userSchema = new mongoose.Schema({
    username:String,
    password:String,
    point: Number,
    watched: [{ type: Schema.Types.ObjectId, ref: 'videoInfos' }],
    running: Array,
});

And query like this:

userInfos.find({}).populate('watched');

The watched array should be populated with videoInfo data.

For more, take a look at mongoose populate.


问:
Logging in without using password and username
I am able to login to my user page and admin page without giving password and username. when usertype is selected and click on login both are getting loggedin. here is my login.php code

```<code><?php
$servername="SERVER";
$username="USER";
$password="PWD";
$dbname="DB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
echo("conneciton");
if(isset($_POST['Login'])){
$user=$_POST['user'];
$pass = $_POST['pass'];
$usertype=$_POST['usertype'];
$query = "SELECT * FROM multiuserlogin WHERE username='".$user."' and password = '".$pass."' and usertype='".$usertype."'";
$result = mysqli_query($conn, $query);
if($result){
while($row=mysqli_fetch_array($result)){
echo'<script type="text/javascript">alert("you are login successfully and you are logined as ' .$row['usertype'].'")</script>';

}
if($usertype=="admin"){
?>
<script type="text/javascript">
window.location.href="index.php"</script>
<?php

}else{
?>
<script type="text/javascript">
window.location.href="user.php"</script>
<?php

}
}else{
echo 'no result';
}
}

?>

<html>

<head>
<!-- title and meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>admin</title>
   <!-- /title and meta -->
   <script src="js/jquery.js"></script>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->

    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
     <link href="css/adminindex.css" rel="stylesheet">
</head>
<body class='bg-image'>
    <center><div class="col-md-4 col-sm-4 col-xs-10 formclass">
<form action="" method="post" name="Login_Form">
 <table>
<tr>
      <td colspan="2" align="left" valign="top"><h3>Login</h3></td>
    </tr>
    <tr>
<td  valign="top">Username:</td><td><input type="text" name="user" placeholder="enter your username"
 </td>
</tr>
<tr>
<td >Password:</td><td><input type="text" name="pass" placeholder="enter your password"</td>
</tr>
<tr>
<td>
Select user type:</td><td> <select name="usertype">

<option value="admin">admin</option>
<option value="user">user</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" name="Login" value="Login"></td>
</tr>
</table>
       </form>   </div>

 </center>
</body>
</html>
</code>```

my database table name is multiuserlogin and column are username password usertype
Please help me on this, i need to verify my username password and then only able to login

答:
Your if statement

```<code>if($result){
</code>```

is always true, because it contains the query not the results. So you are logged in as the usertype you have selected.

Adjust the db information and try this out:

```<code>$conn = new mysqli("SERVER", "USER", "PWD", "DB");

if (!$conn->connect_error) {
  echo("connected");

  if(isset($_POST['Login'])){
    $user = $_POST['user'];
    $pass = $_POST['pass'];

    $query = "SELECT * FROM multiuserlogin WHERE username='".$user."' and password = '".$pass."' LIMIT 1";
    $result = $conn->query($query);
    $logged_user = $result->fetch_array(MYSQLI_ASSOC);
    $conn->close();

    if(is_array($logged_user) && $logged_user['username'] == $user)  {
      echo '<script type="text/javascript">alert("you are login successfully and you are logined as ' . $logged_user['usertype'] .'")</script>';
      if($logged_user['usertype'] == "admin"){
        echo '<script type="text/javascript">window.location.href="index.php"</script>';
      } else {
        echo '<script type="text/javascript">window.location.href="user.php"</script>';
      }
    } else {
    echo 'no result';
    }
  }
}
</code>```

Dont forget to validate for preventing SQL injections.

Body:
I am able to login to my user page and admin page without giving password and username. when usertype is selected and click on login both are getting loggedin. here is my login.php code

<?php
$servername="SERVER";
$username="USER";
$password="PWD";
$dbname="DB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
echo("conneciton");
if(isset($_POST['Login'])){
$user=$_POST['user'];
$pass = $_POST['pass'];
$usertype=$_POST['usertype'];
$query = "SELECT * FROM multiuserlogin WHERE username='".$user."' and password = '".$pass."' and usertype='".$usertype."'";
$result = mysqli_query($conn, $query);
if($result){
while($row=mysqli_fetch_array($result)){
echo'';

}
if($usertype=="admin"){
?>

<?php

}else{
?>

<?php

}
}else{
echo 'no result';
}
}

?>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>admin</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

     <link href="css/adminindex.css" rel="stylesheet">

<form action="" method="post" name="Login_Form">

Login

Username:	<input type="text" name="user" placeholder="enter your username"

Password:	<input type="text" name="pass" placeholder="enter your password"

Select user type:	 <select name="usertype">

<option value="admin">admin</option>
<option value="user">user</option>
</select>

<input type="submit" name="Login" value="Login">

       </form>

my database table name is multiuserlogin and column are username password usertype
Please help me on this, i need to verify my username password and then only able to login

Body:
Your if statement

if($result){

is always true, because it contains the query not the results. So you are logged in as the usertype you have selected.

Adjust the db information and try this out:

$conn = new mysqli("SERVER", "USER", "PWD", "DB");

if (!$conn->connect_error) {
  echo("connected");

  if(isset($_POST['Login'])){
    $user = $_POST['user'];
    $pass = $_POST['pass'];

    $query = "SELECT * FROM multiuserlogin WHERE username='".$user."' and password = '".$pass."' LIMIT 1";
    $result = $conn->query($query);
    $logged_user = $result->fetch_array(MYSQLI_ASSOC);
    $conn->close();

    if(is_array($logged_user) && $logged_user['username'] == $user)  {
      echo '<script type="text/javascript">alert("you are login successfully and you are logined as ' . $logged_user['usertype'] .'")</script>';
      if($logged_user['usertype'] == "admin"){
        echo '<script type="text/javascript">window.location.href="index.php"</script>';
      } else {
        echo '<script type="text/javascript">window.location.href="user.php"</script>';
      }
    } else {
    echo 'no result';
    }
  }
}

Dont forget to validate for preventing SQL injections.


问:
Is Heroku dependable?
I have been hosting a site on Heroku for a few months that is very soon to go into production.

Since I began with them, there have been at least three significant outages, one of which was the disastrous Amazon outage last month and another of which is a multi-hour outage happening today.

I believe in Heroku's vision and I think they are a great company, but I am faced with the ultimate problem: if they can't keep sites up and running, everything I like about them doesn't really matter.

Is Heroku a reliable provider to run a production site on Rails?

Are there any other providers I might look into that have a better reputation for reliability than Heroku?

答: So far Heroku does not offer multiple availability zone redundancy. If you want something more reliable than Heroku you can create your own EC2 instances in multiple availability zones. Of course this will require significantly more server upkeep, admin, and deployment time.</p>

ContentLicense: CC BY-SA 3.0

Title: Is Heroku dependable?


问:
Get rotated rectangle UIView corners' coordinates iOS
I'm trying to find a rotated rectangle UIView's four corners' coordinates.

I think one way I can do is to use recognizer.rotation, find the rotated angle then calculate the origins. But that requires some geometry calculation.

```<code>- (IBAction)handlePan:(UIRotationGestureRecognizer*)recognizer {
    NSLog(@"Rotation in degrees since last change: %f", [recognizer rotation] * (180 / M_PI));
    recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);
    NSLog(@"%@",recognizer);

    recognizer.rotation = 0;
    NSLog(@"bound is %f and %f, frame is %f and %f, %f and %f.",recognizer.view.bounds.size.width,recognizer.view.bounds.size.height, recognizer.view.frame.size.width,recognizer.view.frame.size.height, recognizer.view.frame.origin.x, recognizer.view.frame.origin.y);
}
</code>```

I'm just wondering if there are any other easier ways to get the coordinates?
Thanks!

EDIT:

Looks like we have a great answer here(see answer below). I have managed to calculate the corners through a stupid way -- using rotation angle and geometry. It works but not easy and light. I'm sharing my code here just in case some one may want to use it(Even though I doubt it.)

```<code>    float r = 100;
    NSLog(@"radius is %f.",r);
    float AAngle = M_PI/3+self.rotatedAngle;
    float AY = recognizer.view.center.y - sin(AAngle)*r;
    float AX = recognizer.view.center.x - cos(AAngle)*r;
    self.pointPADA = CGPointMake(AX, AY);
    NSLog(@"View Center is (%f,%f)",recognizer.view.center.x,recognizer.view.center.y);
    NSLog(@"Point A has coordinate (%f,%f)",self.pointPADA.x,self.pointPADA.y);

    float BAngle = M_PI/3-self.rotatedAngle;
    float BY = recognizer.view.center.y - sin(BAngle)*r;
    float BX = recognizer.view.center.x + cos(BAngle)*r;
    self.pointPADB = CGPointMake(BX, BY);
    NSLog(@"Point B has coordinate (%f,%f)",BX,BY);

    float CY = recognizer.view.center.y + sin(AAngle)*r;
    float CX = recognizer.view.center.x + cos(AAngle)*r;
    self.pointPADC = CGPointMake(CX, CY);
    NSLog(@"Point C has coordinate (%f,%f)",CX,CY);

    float DY = recognizer.view.center.y + sin(BAngle)*r;
    float DX = recognizer.view.center.x - cos(BAngle)*r;
    self.pointPADD = CGPointMake(DX, DY);
    NSLog(@"Point D has coordinate (%f,%f)",DX,DY);
</code>```

答:
Using Swift 4, We can get the bounds of rotated view by simple way.

let transformedBounds = view.bounds.applying(view.transform)

Body:
I'm trying to find a rotated rectangle UIView's four corners' coordinates.

I think one way I can do is to use recognizer.rotation, find the rotated angle then calculate the origins. But that requires some geometry calculation.

- (IBAction)handlePan:(UIRotationGestureRecognizer*)recognizer {
    NSLog(@"Rotation in degrees since last change: %f", [recognizer rotation] * (180 / M_PI));
    recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);
    NSLog(@"%@",recognizer);

    recognizer.rotation = 0;
    NSLog(@"bound is %f and %f, frame is %f and %f, %f and %f.",recognizer.view.bounds.size.width,recognizer.view.bounds.size.height, recognizer.view.frame.size.width,recognizer.view.frame.size.height, recognizer.view.frame.origin.x, recognizer.view.frame.origin.y);
}

I'm just wondering if there are any other easier ways to get the coordinates?
Thanks!

EDIT:

Looks like we have a great answer here(see answer below). I have managed to calculate the corners through a stupid way -- using rotation angle and geometry. It works but not easy and light. I'm sharing my code here just in case some one may want to use it(Even though I doubt it.)

    float r = 100;
    NSLog(@"radius is %f.",r);
    float AAngle = M_PI/3+self.rotatedAngle;
    float AY = recognizer.view.center.y - sin(AAngle)*r;
    float AX = recognizer.view.center.x - cos(AAngle)*r;
    self.pointPADA = CGPointMake(AX, AY);
    NSLog(@"View Center is (%f,%f)",recognizer.view.center.x,recognizer.view.center.y);
    NSLog(@"Point A has coordinate (%f,%f)",self.pointPADA.x,self.pointPADA.y);

    float BAngle = M_PI/3-self.rotatedAngle;
    float BY = recognizer.view.center.y - sin(BAngle)*r;
    float BX = recognizer.view.center.x + cos(BAngle)*r;
    self.pointPADB = CGPointMake(BX, BY);
    NSLog(@"Point B has coordinate (%f,%f)",BX,BY);

    float CY = recognizer.view.center.y + sin(AAngle)*r;
    float CX = recognizer.view.center.x + cos(AAngle)*r;
    self.pointPADC = CGPointMake(CX, CY);
    NSLog(@"Point C has coordinate (%f,%f)",CX,CY);

    float DY = recognizer.view.center.y + sin(BAngle)*r;
    float DX = recognizer.view.center.x - cos(BAngle)*r;
    self.pointPADD = CGPointMake(DX, DY);
    NSLog(@"Point D has coordinate (%f,%f)",DX,DY);


问:
Fetch all records from #tbl1 which are not in #tbl2 without use of 'NOT' keyword

Here we have two tables (#tbl1 and #tbl2)

tbl1 Record

```<code>Id  Name
---------
1  Durgesh
2  Ashish
3  Ramesh
4  Steve
5  Pradeep
</code>```

tbl2 Record

```<code>Id  Name
---------
2  Ashish
5  Pradeep
</code>```

Result Should be given below without using 'NOT' Keyword

```<code>Id  Name
---------
1  Durgesh
3  Ramesh
4  Steve
</code>```

答:
You can use EXISTS :

```<code>SELECT t1.*
FROM #tbl1 t1
WHERE EXISTS (SELECT 1 FROM #tbl2 t2 WHERE t2.id <> t1.id);
</code>```

Some DBMS supports lateral JOIN :

```<code>SELECT t1.*
FROM #tbl1 t1 OUTER APPLY
     ( SELECT T2.*
       FROM #tbl2 t2
       WHERE t2.id = t.id
     ) t2
WHERE t2.id IS NULL;
</code>```

Body:
Here we have two tables (#tbl1 and #tbl2)

tbl1 Record

Id  Name
---------
1  Durgesh
2  Ashish
3  Ramesh
4  Steve
5  Pradeep

tbl2 Record

Id  Name
---------
2  Ashish
5  Pradeep

Result Should be given below without using 'NOT' Keyword

Id  Name
---------
1  Durgesh
3  Ramesh
4  Steve

Body:
You can use EXISTS :

SELECT t1.*
FROM #tbl1 t1
WHERE EXISTS (SELECT 1 FROM #tbl2 t2 WHERE t2.id <> t1.id);

Some DBMS supports lateral JOIN :

SELECT t1.*
FROM #tbl1 t1 OUTER APPLY
     ( SELECT T2.*
       FROM #tbl2 t2
       WHERE t2.id = t.id
     ) t2
WHERE t2.id IS NULL;


问:
What does `span 1/ span 1` mean in CSS Grid?
I am using Tailwind’s new CSS Grid feature. It has Grid Column with values span 1/span 1 for class col-span-1, span 2/ span 2 for class col-span-2 and so on until span 12/span 12 for class col-span-12.

I am however unable to understand span 1/ span 1 in practice. I can understand 1 / span 1. I can also understand span 1/ 3 but can’t seem to grasp span 1/ span 1.

答:
While asking the question, I was tinkering with the following CodePen and I seem to have found the solution.

1

2

3

4

```

<p>The above HTML assumes you have Tailwind CSS linked. It shows the following output -</p>

<p><img src="https://i.stack.imgur.com/YKjmg.png" alt="Col Span 1"></p>

<p>Notice, the <code>col-span-1</code> in <code>1</code>. <code>col-span-1</code> refers to <code>span 1 / span 1</code>.</p>

<p>Now let’s change the code to the following:</p>

<pre class="lang-html prettyprint-override"><code><div class="grid grid-cols-3 gap-3 bg-gray-300">
    <div class="bg-green-500 text-white text-6xl flex items-center justify-center border-8 border-black col-span-2">1</div>
    <div class="bg-indigo-500 text-white text-6xl flex items-center justify-center border-8 border-black">2</div>
    <div class="bg-red-500 text-white text-6xl flex items-center justify-center border-8 border-black">3</div>
    <div class="bg-yellow-500 text-white text-6xl flex items-center justify-center border-8 border-black">4</div>
</div>
</code>```

1 contains col-span-2 which is span 2 / span 2. It makes it cover 2‘s space as well.

The output looks as follows:

If we put col-span-4 in 1, it won’t work as we have specified the Grid to be of Column 3 in the parent div with grid-cols-3. Other than that, span covers space from where it starts.

Body:
While asking the question, I was tinkering with the following CodePen and I seem to have found the solution.

<div class="grid grid-cols-3 gap-3 bg-gray-300">
    <div class="bg-green-500 text-white text-6xl flex items-center justify-center border-8 border-black col-span-1">1</div>
    <div class="bg-indigo-500 text-white text-6xl flex items-center justify-center border-8 border-black">2</div>
    <div class="bg-red-500 text-white text-6xl flex items-center justify-center border-8 border-black">3</div>
    <div class="bg-yellow-500 text-white text-6xl flex items-center justify-center border-8 border-black">4</div>
</div>

The above HTML assumes you have Tailwind CSS linked. It shows the following output -

Notice, the col-span-1 in 1. col-span-1 refers to span 1 / span 1.

Now let’s change the code to the following:

<div class="grid grid-cols-3 gap-3 bg-gray-300">
    <div class="bg-green-500 text-white text-6xl flex items-center justify-center border-8 border-black col-span-2">1</div>
    <div class="bg-indigo-500 text-white text-6xl flex items-center justify-center border-8 border-black">2</div>
    <div class="bg-red-500 text-white text-6xl flex items-center justify-center border-8 border-black">3</div>
    <div class="bg-yellow-500 text-white text-6xl flex items-center justify-center border-8 border-black">4</div>
</div>

1 contains col-span-2 which is span 2 / span 2. It makes it cover 2‘s space as well.

The output looks as follows:

If we put col-span-4 in 1, it won’t work as we have specified the Grid to be of Column 3 in the parent div with grid-cols-3. Other than that, span covers space from where it starts.


问:
Ajax file upload with formData fails on large files
I'm sending via ajax a FormData object containing uploads files but when I try to upload large files (> 5M), I receive empty $_POST and $_FILES variables.

Reading so much posts about this issue I applied almost everything but didn't work.

```<code>I've tried on php.ini:
- max_execution_time = 300
- max_input_time = 300
- post_max_size = 2048M (large but compulsory)
- upload_max_filesize = 2048M (large but compulsory)
- max_input_vars = 2000 (trying different values)

On HTTP/HTTPS directives (some have no sense but I was trying in a desperately way to see the behaviour):
- FcgidConnectTimeout 300
- FcgidIOTimeout 300
- FcgidIdleTimeout 300
- FcgidBusyTimeout 300
- IPCCommTimeout 9999
- FcgidMaxRequestLen 21474836480
</code>```

My code looks as follows:

```<code>var form = $('form[name="myform"]');
var formData = new FormData(form[0]);

/*
Also tried this:
   var file = $("form[name='myform'] input[name='filename']");
   formData.append("my_upload", (file[0]).files[0]);
*/

$.ajax({
   type: 'post',
   data: formData,
   dataType: 'json',
   async: true,
   url: '/mysite/controllers/Controller.php',
   processData: false,
   contentType: false,
   ...
});
</code>```

So, for files < 5M everything works perfect in both my local server and production server. For files > 5M only works on my local server but not in the production server (where I receive empty $_POST and $_FILES variables). They have in general some variables configuration although production server is under a WAF on CloudFlare.

答: Finally I got the reason. Thank you to all of you and sorry for forgetting to explain what happened finally. It was the WAF from CloudFlare!, which limits the upload size to 5M. Yes, that's the reason. So I changed my code to make uploads divided in parts smaller than 5M and then join them again in the server once they are uploaded. I didn't find any better approach but hey, it works!.</p>

Body:
I'm sending via ajax a FormData object containing uploads files but when I try to upload large files (> 5M), I receive empty $_POST and $_FILES variables.

Reading so much posts about this issue I applied almost everything but didn't work.

I've tried on php.ini:
- max_execution_time = 300
- max_input_time = 300
- post_max_size = 2048M (large but compulsory)
- upload_max_filesize = 2048M (large but compulsory)
- max_input_vars = 2000 (trying different values)

On HTTP/HTTPS directives (some have no sense but I was trying in a desperately way to see the behaviour):
- FcgidConnectTimeout 300
- FcgidIOTimeout 300
- FcgidIdleTimeout 300
- FcgidBusyTimeout 300
- IPCCommTimeout 9999
- FcgidMaxRequestLen 21474836480

My code looks as follows:

var form = $('form[name="myform"]');
var formData = new FormData(form[0]);

/*
Also tried this:
   var file = $("form[name='myform'] input[name='filename']");
   formData.append("my_upload", (file[0]).files[0]);
*/

$.ajax({
   type: 'post',
   data: formData,
   dataType: 'json',
   async: true,
   url: '/mysite/controllers/Controller.php',
   processData: false,
   contentType: false,
   ...
});

So, for files < 5M everything works perfect in both my local server and production server. For files > 5M only works on my local server but not in the production server (where I receive empty $_POST and $_FILES variables). They have in general some variables configuration although production server is under a WAF on CloudFlare.


问:
Is there a better way to join query in laravel eloquent.?
I have two tables and both have separate models from them. first table is users and other table is users_details table I am writing an eloquent query to join the result but I am getting following error

```<code>Integrity constraint violation: 1052 Column 'gender' in where clause is ambiguous (SQL: select count(*) as aggregate from `users_details` right join `users` on `users_details`.`user_id` = `users`.`id` where `gender` LIKE female and `matrimonial` LIKE 1)
</code>```

my code for the query is following.

```<code> public function bride(){

    $query = app(UserDetail::class)->newQuery();
    $query= $query->where('gender','LIKE','female');
    $query= $query->where('matrimonial','LIKE','1');
    $query = $query->rightJoin('users','users_details.user_id','=','users.id');
    $request = request();
      if(request()->exists('sort')){
        $sorts = explode(',',request()->sort);
        foreach ($sorts as $sort){
            list($sortCol, $sortDir) = explode('|',$sort);
            $query = $query->orderBy($sortCol,$sortDir);
         }
    }
     else {
            $query = $query->orderBy('id','asc');
        }
  if($request->exists('filter')) {
      $query->where(function($q) use($request){
        $value = "%{$request->filter}%";
        $q->where('name','like',$value)
              ->orWhere('father_name','like',$value)
              ->orWhere('city','like',$value)
              ->orWhere('mother_name','like',$value);
      });
  }
  $per_page = request()->has('per_page')?(int) request()->per_page : null;
  $pagination = $query->paginate($per_page);
  $pagination->appends([
      'sort'=>request()->sort,
      'filter'=>request()->filter,
      'per_page'=>request()->per_page
  ]);

    return response()->json(
        $pagination
    )
    ->header('Access-Control-Allow-Origin','*')
    ->header('Access-Control-Allow-Methods','GET');
}
</code>```

What should I do to get the result. Thanks

答:
SQL doesn't know which table you are talking about when you are using Joins - unless you specify table names for each column mentioned in your query.

Replace these lines:

```<code>$query= $query->where('gender','LIKE','female');
$query= $query->where('matrimonial','LIKE','1');
</code>```

with these lines:

```<code>$query= $query->where('users_details.gender','LIKE','female');
$query= $query->where('users_details.matrimonial','LIKE','1');
</code>```

Body:
I have two tables and both have separate models from them. first table is users and other table is users_details table I am writing an eloquent query to join the result but I am getting following error

Integrity constraint violation: 1052 Column 'gender' in where clause is ambiguous (SQL: select count(*) as aggregate from `users_details` right join `users` on `users_details`.`user_id` = `users`.`id` where `gender` LIKE female and `matrimonial` LIKE 1)

my code for the query is following.

 public function bride(){

    $query = app(UserDetail::class)->newQuery();
    $query= $query->where('gender','LIKE','female');
    $query= $query->where('matrimonial','LIKE','1');
    $query = $query->rightJoin('users','users_details.user_id','=','users.id');
    $request = request();
      if(request()->exists('sort')){
        $sorts = explode(',',request()->sort);
        foreach ($sorts as $sort){
            list($sortCol, $sortDir) = explode('|',$sort);
            $query = $query->orderBy($sortCol,$sortDir);
         }
    }
     else {
            $query = $query->orderBy('id','asc');
        }
  if($request->exists('filter')) {
      $query->where(function($q) use($request){
        $value = "%{$request->filter}%";
        $q->where('name','like',$value)
              ->orWhere('father_name','like',$value)
              ->orWhere('city','like',$value)
              ->orWhere('mother_name','like',$value);
      });
  }
  $per_page = request()->has('per_page')?(int) request()->per_page : null;
  $pagination = $query->paginate($per_page);
  $pagination->appends([
      'sort'=>request()->sort,
      'filter'=>request()->filter,
      'per_page'=>request()->per_page
  ]);

    return response()->json(
        $pagination
    )
    ->header('Access-Control-Allow-Origin','*')
    ->header('Access-Control-Allow-Methods','GET');
}

What should I do to get the result. Thanks

Body:
SQL doesn't know which table you are talking about when you are using Joins - unless you specify table names for each column mentioned in your query.

Replace these lines:

$query= $query->where('gender','LIKE','female');
$query= $query->where('matrimonial','LIKE','1');

with these lines:

$query= $query->where('users_details.gender','LIKE','female');
$query= $query->where('users_details.matrimonial','LIKE','1');


问:
decltype() on std::move() of a value capture in a lambda results in an incorrect type
It seems like there either is something wrong with Clang (9.0.0) or my understanding of how decltype() is specified to work in the standard. With reference to the following code,

```<code>#include <utility>
#include <string>

template <typename...> class WhichType;

template <typename T>
std::remove_reference_t<T>&& move_v2(T&& t) {
    WhichType<std::remove_reference_t<T>&&>{};
    return static_cast<std::remove_reference_t<T>&&>(t);
}

int main() {
    auto x = std::string{"a"};
    [v = x]() {
        // move_v2(v);
        // WhichType<decltype(move_v2(v))>{};
        WhichType<decltype(std::move(v))>{};
    }();
}
</code>```

The code above has the compiler output implicit instantiation of undefined template 'WhichType<std::__1::basic_string<char> &&>' instead of the expected const std::__1::basic_string<char> && in the template parameters of WhichType. Using move_v2 or WhichType in move_v2 itself seems to output the correct thing though.

However, Clang also seems to do overload resolution on the std::move(v) expression as I expected https://wandbox.org/permlink/Nv7yXnCbqxjJMVvX. This makes some of my worries go away, but I still don't understand the behavior of decltype() inside the lambda.

GCC does not seem to have this inconsistency in this particular case https://wandbox.org/permlink/5mhrOzLn5XZO8LNB.

Could someone correct me if I'm wrong with my understading of decltype() or point me to the exact places where this bug manifests in clang? Seems a bit scary from first glance.  This can cause problems when used in SFINAE or something similar.

答:
I have done a bit of digging, and it seems to me that the answer is a bit more nuanced than some of the comments makes it seem.

First there is this answer to an earlier question. To quote the important part:

[C++11: 5.1.2/14]: An entity is captured by copy if it is implicitly captured and the capture-default is = or if it is explicitly captured with a capture that does not include an &. For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified. The type of such a data member is the type of the corresponding captured entity if the entity is not a reference to an object, or the referenced type otherwise. [..]

Then there is this answer to another question. Again quote:

5 The closure type for a non-generic lambda-expression has a public
  inline function call operator [...] This function call operator or
  operator template is declared const (9.3.1) if and only if the
  lambda-expression’s parameter-declaration-clause is not followed by
  mutable.

I then put this together in a small test:

```<code>#include <iostream>
using std::cout;
using std::endl;

void foo(const std::string&) {
    cout << "void foo(const std::string&)" << endl;
}

void foo(std::string&) {
    cout << "void (std::string&)" << endl;
}

struct klaf
{
    std::string b;

    void bla() const
    {
        cout << std::boolalpha << std::is_const<decltype(b)>::value << endl;
        foo(b);
    }
};

int main()
{
    klaf k;
    k.bla();

    std::string s;
    const std::string s2;
    auto lam = [=]() {
        cout << std::boolalpha << std::is_const<decltype(s)>::value << endl;
        foo(s);

        cout << std::boolalpha << std::is_const<decltype(s2)>::value << endl;
        foo(s2);
    };
    lam();
}
</code>```

Which outpouts (and the outputs are the same in GCC, Clang, and MSVC):

```<code>false
void foo(const std::string&)
false
void foo(const std::string&)
true
void foo(const std::string&)
</code>```

klaf::b is (obviously) not const, but since the klaf::bla function is const, then klaf::b is treated as const in the call to foo.

The same is true in lam where s is captured by value with a type of std::string. However, s2 has been declared as const std::string and that carries over to the type of the data member in the lambda.

In short: Capture by value in a lambda does not make the captured member itself const, but since operator() for the lambda is const, then the members are promoted to const in that function (unless the lambda is declared mutable).

EDIT:

Inspired by comment from @arnes I found a difference is GCC and Clang:

```<code>int main()
{
    int i = 12;
    auto lam = [=, ic = i]() {
        cout << std::boolalpha << std::is_const<decltype(i)>::value << endl;
        cout << std::boolalpha << std::is_const<decltype(ic)>::value << endl;
    };
    lam();
}
</code>```

This produces false false in Clang, but false true in GCC. In other words, a capture with an initializer becomes const in GCC but not in Clang.

Body:
It seems like there either is something wrong with Clang (9.0.0) or my understanding of how decltype() is specified to work in the standard. With reference to the following code,

#include <utility>
#include <string>

template <typename...> class WhichType;

template <typename T>
std::remove_reference_t<T>&& move_v2(T&& t) {
    WhichType<std::remove_reference_t<T>&&>{};
    return static_cast<std::remove_reference_t<T>&&>(t);
}

int main() {
    auto x = std::string{"a"};
    [v = x]() {
        // move_v2(v);
        // WhichType<decltype(move_v2(v))>{};
        WhichType<decltype(std::move(v))>{};
    }();
}

The code above has the compiler output implicit instantiation of undefined template 'WhichType<std::__1::basic_string<char> &&>' instead of the expected const std::__1::basic_string<char> && in the template parameters of WhichType. Using move_v2 or WhichType in move_v2 itself seems to output the correct thing though.

However, Clang also seems to do overload resolution on the std::move(v) expression as I expected https://wandbox.org/permlink/Nv7yXnCbqxjJMVvX. This makes some of my worries go away, but I still don't understand the behavior of decltype() inside the lambda.

GCC does not seem to have this inconsistency in this particular case https://wandbox.org/permlink/5mhrOzLn5XZO8LNB.

Could someone correct me if I'm wrong with my understading of decltype() or point me to the exact places where this bug manifests in clang? Seems a bit scary from first glance.  This can cause problems when used in SFINAE or something similar.

Body:
I have done a bit of digging, and it seems to me that the answer is a bit more nuanced than some of the comments makes it seem.

First there is this answer to an earlier question. To quote the important part:

[C++11: 5.1.2/14]: An entity is captured by copy if it is implicitly captured and the capture-default is = or if it is explicitly captured with a capture that does not include an &. For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified. The type of such a data member is the type of the corresponding captured entity if the entity is not a reference to an object, or the referenced type otherwise. [..]

Then there is this answer to another question. Again quote:

5 The closure type for a non-generic lambda-expression has a public
  inline function call operator [...] This function call operator or
  operator template is declared const (9.3.1) if and only if the
  lambda-expression’s parameter-declaration-clause is not followed by
  mutable.

I then put this together in a small test:

#include <iostream>
using std::cout;
using std::endl;

void foo(const std::string&) {
    cout << "void foo(const std::string&)" << endl;
}

void foo(std::string&) {
    cout << "void (std::string&)" << endl;
}

struct klaf
{
    std::string b;

    void bla() const
    {
        cout << std::boolalpha << std::is_const<decltype(b)>::value << endl;
        foo(b);
    }
};

int main()
{
    klaf k;
    k.bla();

    std::string s;
    const std::string s2;
    auto lam = [=]() {
        cout << std::boolalpha << std::is_const<decltype(s)>::value << endl;
        foo(s);

        cout << std::boolalpha << std::is_const<decltype(s2)>::value << endl;
        foo(s2);
    };
    lam();
}

Which outpouts (and the outputs are the same in GCC, Clang, and MSVC):

false
void foo(const std::string&)
false
void foo(const std::string&)
true
void foo(const std::string&)

klaf::b is (obviously) not const, but since the klaf::bla function is const, then klaf::b is treated as const in the call to foo.

The same is true in lam where s is captured by value with a type of std::string. However, s2 has been declared as const std::string and that carries over to the type of the data member in the lambda.

In short: Capture by value in a lambda does not make the captured member itself const, but since operator() for the lambda is const, then the members are promoted to const in that function (unless the lambda is declared mutable).

EDIT:

Inspired by comment from @arnes I found a difference is GCC and Clang:

int main()
{
    int i = 12;
    auto lam = [=, ic = i]() {
        cout << std::boolalpha << std::is_const<decltype(i)>::value << endl;
        cout << std::boolalpha << std::is_const<decltype(ic)>::value << endl;
    };
    lam();
}

This produces false false in Clang, but false true in GCC. In other words, a capture with an initializer becomes const in GCC but not in Clang.


问:
Scala 2.13.1 Unable to use macros
I am unable to use macros in scala 2.13.1.

I keep getting the following error:

```<code>object blackbox is not a member of package scala.reflect.macros
</code>```

This obviously isn't true, because scala 2.13.1 actually has these blackbox.
What am I not doing right?

Hello.scala

```<code>package example.core

import example.macros.MacroLibrary

object Hello extends App {
  MacroLibrary.hello()
}
</code>```

MacroLibrary.scala

```<code>package example.macros

// This line throws errors
import scala.reflect.macros.blackbox.Context
import scala.reflect.macros.blackbox

object MacroLibrary {
  def hello_impl(c: blackbox.Context)(): c.Expr[Unit] = {
    import c.universe._
    c.Expr(q"""println("Hello World")""")
  }

  def hello(): Unit = macro hello_impl
}
</code>```

build.sbt

```<code>scalaVersion := "2.13.1"
</code>```

Error

```<code>object blackbox is not a member of package scala.reflect.macros
</code>```

答:
They are not in the standard library, but in separate scala-reflect, which needs to be added as a dependency in build.sbt:

```<code>libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value
</code>```

You can see that from Context documentation having "Scala Reflection Library" in the top left.

Title: Scala 2.13.1 Unable to use macros

Body:
I am unable to use macros in scala 2.13.1.

I keep getting the following error:

object blackbox is not a member of package scala.reflect.macros

This obviously isn't true, because scala 2.13.1 actually has these blackbox.
What am I not doing right?

Hello.scala

package example.core

import example.macros.MacroLibrary

object Hello extends App {
  MacroLibrary.hello()
}

MacroLibrary.scala

package example.macros

// This line throws errors
import scala.reflect.macros.blackbox.Context
import scala.reflect.macros.blackbox

object MacroLibrary {
  def hello_impl(c: blackbox.Context)(): c.Expr[Unit] = {
    import c.universe._
    c.Expr(q"""println("Hello World")""")
  }

  def hello(): Unit = macro hello_impl
}

build.sbt

scalaVersion := "2.13.1"

Error

object blackbox is not a member of package scala.reflect.macros

Body:
They are not in the standard library, but in separate scala-reflect, which needs to be added as a dependency in build.sbt:

libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value

You can see that from Context documentation having "Scala Reflection Library" in the top left.


答:
Try this:</p>

```<code>select STATUSIN,STATUSOUT,case when CAST(STATUSIN as time) > CAST('08:00' as time) then
DATEDIFF(MINUTE,CAST('08:00' as time),CAST(STATUSIN as time))
end as LATECOME from test;
</code>```

Title: Select min date value and calculate date value?

Body:
I have a table called "SUMMARYDATA" which has columns "STATUSIN,STATUSOUT,LATECOME" and I want to select min value on column "STATUSIN". And make a condition: IF MIN(STATUSIN) > "08.00 AM" Then LATECOME = MIN(STATUSIN) - "08.00 AM". How to select min date value? And how to calculate MIN(STATUSIN) - "08.00 AM"?

This is my code to display data from database:

    <asp:Repeater ID="rptrSUMMARYDATA" runat="server">
        <HeaderTemplate>

                        IN
                        OUT
                        LATECOME

        </HeaderTemplate>
        <ItemTemplate>

                <%# Eval("STATUSIN") %>
                <%# Eval("STATUSOUT") %>
                <%# Eval("LATECOME") %>

        </ItemTemplate>
        <FooterTemplate>

        </FooterTemplate>
    </asp:Repeater>

This is my code on backend:

     private void BindSUMMARYDATARptr()
    {
        String CS = ConfigurationManager.ConnectionStrings["MANHOURConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM SUMMARYDATA", con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dtDaily = new DataTable();
                    sda.Fill(dtDaily);

                    rptrSUMMARYDATA.DataSource = dtDaily;
                    rptrSUMMARYDATA.DataBind();
                }

            }

        }
    }

Body:
Try this:

select STATUSIN,STATUSOUT,case when CAST(STATUSIN as time) > CAST('08:00' as time) then
DATEDIFF(MINUTE,CAST('08:00' as time),CAST(STATUSIN as time))
end as LATECOME from test;


问:
CSS change overflow with delay
Hey I have a "spoiler" which should be animated and scrollable. The only problem is that the scrollbar should only be shown after the transition.

Example Code:

#spoiler{
  font-size:50px;
  max-height:0px;
  overflow:hidden;
  transition:3s;
}
input#SpoilerBox:checked ~ #spoiler{
  max-height:200px;
  overflow:auto
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<html>
  <head>
   <title>Spoiler</title>
  </head>

     <body>
       <input type="checkbox" id="SpoilerBox"/><label for="SpoilerBox">Spoiler</label>

       <div id="spoiler">
         Text<br>
         to spoiler
        </div>
      </body>
</html></code>```

答:
A bit tricky - I have added a wrapper element, and use css @keyframes. Also I changed the max-height to 100px, for it fit the snipped area

#spoiler{
  font-size:50px;
  overflow:auto;
  height:0;
  transition: height 3s;
}
#spoiler-wrapper {
  overflow: hidden;
  height:100%;
}
input#SpoilerBox:checked ~ #spoiler {
  height: 100px;
}
input#SpoilerBox:checked ~ #spoiler #spoiler-wrapper{
  height:auto;
  animation: grow 3s;
}
@keyframes grow {
  from {height:0px;}
  to {height: 100px;}
}
@keyframes shrink {
  from {height:100px;}
  to {height: 0px;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="SpoilerBox"/>
<label for="SpoilerBox">Spoiler</label>
<div id="spoiler">
<div id="spoiler-wrapper">
   Text<br>to spoiler
</div>
</div></code>```

Title: CSS change overflow with delay

Body:
Hey I have a "spoiler" which should be animated and scrollable. The only problem is that the scrollbar should only be shown after the transition.

Example Code:

#spoiler{
  font-size:50px;
  max-height:0px;
  overflow:hidden;
  transition:3s;
}
input#SpoilerBox:checked ~ #spoiler{
  max-height:200px;
  overflow:auto
}

<!DOCTYPE html>

   <title>Spoiler</title>

       <input type="checkbox" id="SpoilerBox"/>Spoiler

         Text

         to spoiler

Body:
A bit tricky - I have added a wrapper element, and use css @keyframes. Also I changed the max-height to 100px, for it fit the snipped area

#spoiler{
  font-size:50px;
  overflow:auto;
  height:0;
  transition: height 3s;
}
#spoiler-wrapper {
  overflow: hidden;
  height:100%;
}
input#SpoilerBox:checked ~ #spoiler {
  height: 100px;
}
input#SpoilerBox:checked ~ #spoiler #spoiler-wrapper{
  height:auto;
  animation: grow 3s;
}
@keyframes grow {
  from {height:0px;}
  to {height: 100px;}
}
@keyframes shrink {
  from {height:100px;}
  to {height: 0px;}
}

<input type="checkbox" id="SpoilerBox"/>
<label for="SpoilerBox">Spoiler</label>
<div id="spoiler">
<div id="spoiler-wrapper">
   Text<br>to spoiler
</div>
</div>


问:
Check if the current date is between two dates + mysql select query
I have the following table :

```<code>id     dateStart     dateEnd      active
1      2012-11-12    2012-12-31   0
2      2012-11-12    2012-12-31   0
</code>```

I want to check if today's date is in between dateStart and dateEnd.

The following is my query for this :

```<code>$todaysDate="2012-26-11";
$db = Zend_Registry::get("db");
$result = $db->fetchAll("SELECT * FROM `table` WHERE active=0 AND {$todaysDate} between dateStart and dateEnd");
return $result;
</code>```

But so far it's not working as it returns zero rows.

答:
Try removing the {} as described below.</p>

```<code>$todaysDate="2012-11-26";//changed date
$sql = mysql_query("SELECT * FROM register WHERE '$todaysDate' between reg_start_date and reg_end_date") or die(mysql_error());
</code>```

Body:
I have the following table :

id     dateStart     dateEnd      active
1      2012-11-12    2012-12-31   0
2      2012-11-12    2012-12-31   0

I want to check if today's date is in between dateStart and dateEnd.

The following is my query for this :

$todaysDate="2012-26-11";
$db = Zend_Registry::get("db");
$result = $db->fetchAll("SELECT * FROM `table` WHERE active=0 AND {$todaysDate} between dateStart and dateEnd");
return $result;

But so far it's not working as it returns zero rows.

Body:
Try removing the {} as described below.

$todaysDate="2012-11-26";//changed date
$sql = mysql_query("SELECT * FROM register WHERE '$todaysDate' between reg_start_date and reg_end_date") or die(mysql_error());


问:
Xamarin Forms: How to get the BindableProperty by the property name?

Hi, i need to get the BindableProperty by the property name.

```<code>public BindableProperty GetBindableProperty(BindableObject bindableObj, string propertyName) {
    if(typeof(Entry) == bindableObj.GetType()) {
        if("Text" == propertyName) {
            return (Entry.TextProperty);
        }
        if("TextColor" == propertyName) {
            return (Entry.TextColorProperty);
        }
    }
    return (null);
}
</code>```

But i do not want to use this "if else" style.
  Is there a general way that I don't need to judge the type and name?

答:
Hi, I found the solution now:

```<code>public BindableProperty GetBindableProperty(BindableObject bindableObj, string propertyName) {
    Type type = bindableObj.GetType();
    FieldInfo fieldInfo;
    while(null == (fieldInfo = type.GetField(propertyName + "Property", BindingFlags.Static | BindingFlags.Public))) {
        type = type.BaseType;
    }
    if(null == fieldInfo) {
        throw (new Exception("Can not find the BindableProperty for " + propertyName));
    }
    return ((BindableProperty)(fieldInfo.GetValue(bindableObj)));
}
</code>```

Body:
Hi, i need to get the BindableProperty by the property name.

public BindableProperty GetBindableProperty(BindableObject bindableObj, string propertyName) {
    if(typeof(Entry) == bindableObj.GetType()) {
        if("Text" == propertyName) {
            return (Entry.TextProperty);
        }
        if("TextColor" == propertyName) {
            return (Entry.TextColorProperty);
        }
    }
    return (null);
}

But i do not want to use this "if else" style.
  Is there a general way that I don't need to judge the type and name?

Body:
Hi, I found the solution now:

public BindableProperty GetBindableProperty(BindableObject bindableObj, string propertyName) {
    Type type = bindableObj.GetType();
    FieldInfo fieldInfo;
    while(null == (fieldInfo = type.GetField(propertyName + "Property", BindingFlags.Static | BindingFlags.Public))) {
        type = type.BaseType;
    }
    if(null == fieldInfo) {
        throw (new Exception("Can not find the BindableProperty for " + propertyName));
    }
    return ((BindableProperty)(fieldInfo.GetValue(bindableObj)));
}


问:
Sequelize Upsert is Creating instead of Updating
According to the documentation found here it states as follows

upsert(values, [options]) -> Promise.<created>

Insert or update a single row. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.

So my expectation is that upserting using a unique key should replace the existing value. However when my code runs instead of updating the existing database record, it adds a new one. What am I doing wrong?

here is a sample of my model

'use strict'

module.exports = (db, dataTypes) => {
  const titanJob = db.define('titanJob', {
    titanId: {
      type: dataTypes.STRING,
      allowNull: false,
      unique: true
    },
    name: {
      type: dataTypes.STRING,
      allowNull: false
    }
  }, {
    timestamps: true
  })
  return titanJob
}
```

<p>and here is an example of my upsert</p>

<pre class="lang-js prettyprint-override"><code>await asyncForEach(res.data.hits.hits, async es => {
  const src = es._source
  try {
    await titanJob.upsert({
      name: src.name,
      titanId: src.id,
    }, { titanId: src.id })
    logger.debug(`[${file}] upsert successful`)
  } catch (err) {
    logger.warn(`[${file}] failed to save to database`)
    logger.warn(`[${file}] ${err}`)
  }
})
</code>```

答:
It should work. Here is an example using "sequelize": "^5.21.3":

index.ts:

import { Model, DataTypes } from 'sequelize';
import { sequelize } from '../../db';
import assert from 'assert';

class TitanJob extends Model {}
TitanJob.init(
  {
    titanId: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  },
  { sequelize, modelName: 'titanJob', timestamps: true },
);

(async function test() {
  try {
    await sequelize.sync({ force: true });
    const datas = [
      { titanId: '1', name: 'programmer' },
      { titanId: '2', name: 'teacher' },
    ];
    const jobs = await TitanJob.bulkCreate(datas);
    assert.deepEqual(
      jobs.map((job) => ({ titanId: job.id, name: job.name })),
      datas,
      'Should bulk create programmer and teacher datas',
    );
    const rval = await TitanJob.upsert({ titanId: '1', name: 'driver' }, { returning: true });
    assert.equal(rval[0].titanId, '1', 'Should update the row which titanId is "1"');
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();
```

<p>Execution results:</p>

<pre class="lang-sh prettyprint-override"><code>{ POSTGRES_HOST: '127.0.0.1',
  POSTGRES_PORT: '5430',
  POSTGRES_PASSWORD: 'testpass',
  POSTGRES_USER: 'testuser',
  POSTGRES_DB: 'node-sequelize-examples' }
Executing (default): DROP TABLE IF EXISTS "titanJob" CASCADE;
Executing (default): DROP TABLE IF EXISTS "titanJob" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "titanJob" ("id"   SERIAL , "titanId" VARCHAR(255) NOT NULL UNIQUE, "name" VARCHAR(255) NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'titanJob' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "titanJob" ("id","titanId","name","createdAt","updatedAt") VALUES (DEFAULT,'1','programmer','2020-02-14 08:09:45.506 +00:00','2020-02-14 08:09:45.506 +00:00'),(DEFAULT,'2','teacher','2020-02-14 08:09:45.506 +00:00','2020-02-14 08:09:45.506 +00:00') RETURNING *;
Executing (default): CREATE OR REPLACE FUNCTION pg_temp.sequelize_upsert(OUT created boolean, OUT primary_key text)  AS $func$ BEGIN INSERT INTO "titanJob" ("titanId","name","createdAt","updatedAt") VALUES ('1','driver','2020-02-14 08:09:45.524 +00:00','2020-02-14 08:09:45.524 +00:00') RETURNING "id" INTO primary_key; created := true; EXCEPTION WHEN unique_violation THEN UPDATE "titanJob" SET "titanId"='1',"name"='driver',"updatedAt"='2020-02-14 08:09:45.524 +00:00' WHERE ("id" IS NULL OR "titanId" = '1') RETURNING "id" INTO primary_key; created := false; END; $func$ LANGUAGE plpgsql; SELECT * FROM pg_temp.sequelize_upsert();
Executing (default): SELECT "id", "titanId", "name", "createdAt", "updatedAt" FROM "titanJob" AS "titanJob" WHERE "titanJob"."id" = '1';
</code>```

No assertion fails. It works as expected. Check the data rows in the database:

node-sequelize-examples=# select * from "titanJob";
 id | titanId |  name   |         createdAt          |         updatedAt
----+---------+---------+----------------------------+----------------------------
  2 | 2       | teacher | 2020-02-14 08:09:45.506+00 | 2020-02-14 08:09:45.506+00
  1 | 1       | driver  | 2020-02-14 08:09:45.506+00 | 2020-02-14 08:09:45.524+00
(2 rows)
```

source code: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/59686743

Body:
According to the documentation found here it states as follows

upsert(values, [options]) -> Promise.<created>

Insert or update a single row. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.

So my expectation is that upserting using a unique key should replace the existing value. However when my code runs instead of updating the existing database record, it adds a new one. What am I doing wrong?

here is a sample of my model

'use strict'

module.exports = (db, dataTypes) => {
  const titanJob = db.define('titanJob', {
    titanId: {
      type: dataTypes.STRING,
      allowNull: false,
      unique: true
    },
    name: {
      type: dataTypes.STRING,
      allowNull: false
    }
  }, {
    timestamps: true
  })
  return titanJob
}

and here is an example of my upsert

await asyncForEach(res.data.hits.hits, async es => {
  const src = es._source
  try {
    await titanJob.upsert({
      name: src.name,
      titanId: src.id,
    }, { titanId: src.id })
    logger.debug(`[${file}] upsert successful`)
  } catch (err) {
    logger.warn(`[${file}] failed to save to database`)
    logger.warn(`[${file}] ${err}`)
  }
})

Body:
It should work. Here is an example using "sequelize": "^5.21.3":

index.ts:

import { Model, DataTypes } from 'sequelize';
import { sequelize } from '../../db';
import assert from 'assert';

class TitanJob extends Model {}
TitanJob.init(
  {
    titanId: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  },
  { sequelize, modelName: 'titanJob', timestamps: true },
);

(async function test() {
  try {
    await sequelize.sync({ force: true });
    const datas = [
      { titanId: '1', name: 'programmer' },
      { titanId: '2', name: 'teacher' },
    ];
    const jobs = await TitanJob.bulkCreate(datas);
    assert.deepEqual(
      jobs.map((job) => ({ titanId: job.id, name: job.name })),
      datas,
      'Should bulk create programmer and teacher datas',
    );
    const rval = await TitanJob.upsert({ titanId: '1', name: 'driver' }, { returning: true });
    assert.equal(rval[0].titanId, '1', 'Should update the row which titanId is "1"');
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

Execution results:

{ POSTGRES_HOST: '127.0.0.1',
  POSTGRES_PORT: '5430',
  POSTGRES_PASSWORD: 'testpass',
  POSTGRES_USER: 'testuser',
  POSTGRES_DB: 'node-sequelize-examples' }
Executing (default): DROP TABLE IF EXISTS "titanJob" CASCADE;
Executing (default): DROP TABLE IF EXISTS "titanJob" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "titanJob" ("id"   SERIAL , "titanId" VARCHAR(255) NOT NULL UNIQUE, "name" VARCHAR(255) NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'titanJob' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "titanJob" ("id","titanId","name","createdAt","updatedAt") VALUES (DEFAULT,'1','programmer','2020-02-14 08:09:45.506 +00:00','2020-02-14 08:09:45.506 +00:00'),(DEFAULT,'2','teacher','2020-02-14 08:09:45.506 +00:00','2020-02-14 08:09:45.506 +00:00') RETURNING *;
Executing (default): CREATE OR REPLACE FUNCTION pg_temp.sequelize_upsert(OUT created boolean, OUT primary_key text)  AS $func$ BEGIN INSERT INTO "titanJob" ("titanId","name","createdAt","updatedAt") VALUES ('1','driver','2020-02-14 08:09:45.524 +00:00','2020-02-14 08:09:45.524 +00:00') RETURNING "id" INTO primary_key; created := true; EXCEPTION WHEN unique_violation THEN UPDATE "titanJob" SET "titanId"='1',"name"='driver',"updatedAt"='2020-02-14 08:09:45.524 +00:00' WHERE ("id" IS NULL OR "titanId" = '1') RETURNING "id" INTO primary_key; created := false; END; $func$ LANGUAGE plpgsql; SELECT * FROM pg_temp.sequelize_upsert();
Executing (default): SELECT "id", "titanId", "name", "createdAt", "updatedAt" FROM "titanJob" AS "titanJob" WHERE "titanJob"."id" = '1';

No assertion fails. It works as expected. Check the data rows in the database:

node-sequelize-examples=# select * from "titanJob";
 id | titanId |  name   |         createdAt          |         updatedAt
----+---------+---------+----------------------------+----------------------------
  2 | 2       | teacher | 2020-02-14 08:09:45.506+00 | 2020-02-14 08:09:45.506+00
  1 | 1       | driver  | 2020-02-14 08:09:45.506+00 | 2020-02-14 08:09:45.524+00
(2 rows)

source code: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/59686743


问:
Redshift transformation: json key/value to relation
in the Redshift table I have the tag column, which is varchar storing json with typical key/value pairs. E.g. for record with id = 1 the tag value looks like:  {"env":"test","app-name":"ap123","product-type":"web-app"}.

I would like to transform the key/values to the typical relational table like below:

```<code>+---+-------------+-------+
|id ||key         |value  |
+---+-------------+-------+
|1  |env          |test   |
|1  |app-name     |ap123  |
|1  |product-type |web-app|
|2  |env          |dev    |
|...|...          |...    |
+---+-------------+-------+
</code>```

I had made a fast research already I didn't found any solution. I tried to use the Redshift json functions, but without achieving the desired result (https://docs.aws.amazon.com/redshift/latest/dg/json-functions.html).

Any ideas are highly wellcome.

答: The idea in this situation was to change the json to json_array by adding enclosing brackets ('[' and ']') to the json and replace ',' with the '}, {' to change separate json_array elements. Afther that it's possible to access the json_array element by the json_extract_array_element_text function.</p>

Body:
in the Redshift table I have the tag column, which is varchar storing json with typical key/value pairs. E.g. for record with id = 1 the tag value looks like:  {"env":"test","app-name":"ap123","product-type":"web-app"}.

I would like to transform the key/values to the typical relational table like below:

+---+-------------+-------+
|id ||key         |value  |
+---+-------------+-------+
|1  |env          |test   |
|1  |app-name     |ap123  |
|1  |product-type |web-app|
|2  |env          |dev    |
|...|...          |...    |
+---+-------------+-------+

I had made a fast research already I didn't found any solution. I tried to use the Redshift json functions, but without achieving the desired result (https://docs.aws.amazon.com/redshift/latest/dg/json-functions.html).

Any ideas are highly wellcome.