问:
Assign type level parameter to data structure tree
I have a remote microcontroller that exposes some properties in a tree like view. These properties can all be read and some of them can be written to. A property is just a string where each level of the tree is delimited by a ..

As an example the property tree looks something like this:

```<code>Properties.prop1 = 0
Properties.prop2.foo = 1337
Properties.prop2.bar.baz1 = "hello"
Properties.prop2.bar.baz2 = "world"
</code>```

Where Properties.prop1 and Properties.prop2.foo are readable only. Properties.prop2.bar.baz1 and Properties.prop2.bar.baz2 are readable and writeable. Anyway I want to encode this in Haskell using strong typing.

```<code>data Bar = Baz1 String | Baz2 String
data Prop2 = Foo Int | Bar Bar
data Properties = Prop1 Int | Prop2 Prop2
</code>```

Now you can pretty nicely create a property:

```<code>p = Prop2 $ Bar $ Baz1 "hello"
</code>```

But what I'm missing is how I can associate a single "path" through these constructors as either a readable property or a read/writeable property. Ideally I would like to have a class or type family "ReadableProp" and "WriteableProp" which would allow me to write something like:

```<code>writeProp :: WriteableProp a => a -> IO ()
writeProp = ...

readProp :: ReadableProp a => IO a
readProp = ...
</code>```

I know this doesn't work at all right now. But I'm open to change the data structure or use something else to achieve something like this.

Does anyone have any idea?

Thank you for reading!

答:
As an alternative, instead of representing your property tree path components as a collection of algebraic type "nodes" and constructor "leaves", consider a more uniform representation as a type-level tree that stores the accessibility and type as the tree's (leaf) values:

```<code>{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}

import GHC.TypeLits
import Data.Kind

data Value = RO Type | RW Type
data Tree = Leaf Symbol Value | Node Symbol [Tree]

type Properties
  = [ Leaf "prop1" (RO Int)
    , Node "prop2" [ Leaf "foo" (RO Int)
                   , Node "bar" [ Leaf "baz1" (RW String)
                                , Leaf "baz2" (RW String)
                                ]
                   ]
    ]
</code>```

If you write a type-level lookup function for property paths:

```<code>{-# LANGUAGE TypeOperators #-}

type Lookup path = Lookup1 path Properties
type family Lookup1 path props where
  Lookup1 (p:ps) (Node p props' : props) = Lookup1 ps props'
  Lookup1 '[p]   (Leaf p val : qs) = val
  Lookup1 path   (prop : props) = Lookup1 path props
</code>```

that works like so:

```<code>> :kind! Lookup '["prop1"]
Lookup '["prop1"] :: Value
= 'RO Int
> :kind! Lookup '["prop2", "bar", "baz1"]
Lookup '["prop2", "bar", "baz1"] :: Value
= 'RW String
</code>```

that gives you most of what you need.  With a couple of convenience type-level functions:

```<code>{-# LANGUAGE ConstraintKinds #-}
type TypeOf path = GetType (Lookup path)
type Writeable path = GetAccess (Lookup path) ~ RW
type family GetType (value :: Value) where GetType (access a) = a
type family GetAccess (value :: Value) where GetAccess (access a) = access
</code>```

you can define properties as:

```<code>data Property path = Property { getProperty :: TypeOf path }
</code>```

letting you create new, type-safe property values like so:

```<code>> Property @'["prop1"] 5
Property @'["prop1"] 5 :: Property '["prop1"]
> Property @'["prop2","bar","baz1"] "hello"
Property @'["prop2","bar","baz1"] "hello"
  :: Property '["prop2", "bar", "baz1"]
> Property @'["prop2","bar","baz2"] 123  --- type error
</code>```

With a utility class to get a value-level path from a type-level path:

```<code>{-# LANGUAGE ScopedTypeVariables #-}
import Data.Proxy

class KnownPath (path :: [Symbol]) where
  pathVal :: proxy path -> [String]
instance KnownPath '[] where pathVal _ = []
instance (KnownSymbol p, KnownPath ps) => KnownPath (p:ps) where
  pathVal _ = symbolVal (Proxy @p) : pathVal (Proxy @ps)
</code>```

we can create a fake microcontroller, as a map of path/ioref pairs, where the values in the iorefs are Haskell printable representations that can be marshalled with Read/Show:

```<code>{-# LANGUAGE TupleSections #-}
import Data.Map.Strict (Map, (!))
import qualified Data.Map.Strict as Map
import Data.IORef

type MicroController = Map [String] (IORef String)

newmc :: IO MicroController
newmc
  = Map.fromList <$> mapM (\(k,v) -> (k,) <$> newIORef v) defaults
  where defaults = [ (["prop1"], "0")
                   , (["prop2","foo"], "1337")
                   , (["prop2","bar","baz1"], "\"hello\"")
                   , (["prop2","bar","baz2"], "\"world\"")
                   ]
</code>```

The property read/write functions can be written like so.  Note the use of the Writeable path constraint on writeProp.

```<code>{-# LANGUAGE FlexibleContexts #-}

readProp :: forall path. (KnownPath path, Read (TypeOf path))
         => MicroController -> IO (Property path)
readProp mc = do
  let path = pathVal (Proxy @path)
  Property . read <$> readIORef (mc ! path)

writeProp :: forall path. (KnownPath path, Show (TypeOf path), Writeable path)
          => Property path -> MicroController -> IO ()
writeProp prop mc = do
  let path = pathVal prop
  writeIORef (mc ! path) (show (getProperty prop))
</code>```

We can test it like so:

```<code>{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
deriving instance (Show (TypeOf path)) => (Show (Property path))

main :: IO ()
main = do
  mc <- newmc
  (prop1 :: Property '["prop1"]) <- readProp mc
  print prop1
  -- writeProp prop1 mc  -- type error: couldn't match RO with RW
  (baz1 :: Property '["prop2", "bar", "baz1"]) <- readProp mc
  print baz1
  let baz2' = Property @'["prop2", "bar", "baz2"] "Steve"
  writeProp baz2' mc
  (baz2 :: Property '["prop2", "bar", "baz2"]) <- readProp mc
  print baz2
</code>```

The main advantages of this approach are that the property tree is exposed as as single type-level "structure" with a straightforward tree-like representation, and the KnownPath class provides an automatic mapping to value-level property paths, saving you the trouble of writing a lot of boilerplate to map a network of algebraic types to their property paths.  The disadvantages are somewhat uglier syntax, and the need to get the right mix of type applications, proxies, and optional versus mandatory ticked promoters.

Anyway, the full code is:

```<code>{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}

import GHC.TypeLits
import Data.Kind
import Data.Proxy
import Data.Map.Strict (Map, (!))
import qualified Data.Map.Strict as Map
import Data.IORef

data Value = RO Type | RW Type
data Tree = Leaf Symbol Value | Node Symbol [Tree]

type Properties
  = [ Leaf "prop1" (RO Int)
    , Node "prop2" [ Leaf "foo" (RO Int)
                   , Node "bar" [ Leaf "baz1" (RW String)
                                , Leaf "baz2" (RW String)
                                ]
                   ]
    ]

type Lookup path = Lookup1 path Properties
type family Lookup1 path props where
  Lookup1 (p:ps) (Node p props' : props) = Lookup1 ps props'
  Lookup1 '[p]   (Leaf p val : qs) = val
  Lookup1 path   (prop : props) = Lookup1 path props
type TypeOf path = GetType (Lookup path)
type Writeable path = GetAccess (Lookup path) ~ RW
type family GetType (value :: Value) where GetType (access a) = a
type family GetAccess (value :: Value) where GetAccess (access a) = access

data Property path = Property { getProperty :: TypeOf path }
deriving instance (Show (TypeOf path)) => (Show (Property path))

class KnownPath (path :: [Symbol]) where
  pathVal :: proxy path -> [String]
instance KnownPath '[] where pathVal _ = []
instance (KnownSymbol p, KnownPath ps) => KnownPath (p:ps) where
  pathVal _ = symbolVal (Proxy @p) : pathVal (Proxy @ps)

type MicroController = Map [String] (IORef String)

newmc :: IO MicroController
newmc
  = Map.fromList <$> mapM (\(k,v) -> (k,) <$> newIORef v) defaults
  where defaults = [ (["prop1"], "0")
                   , (["prop2","foo"], "1337")
                   , (["prop2","bar","baz1"], "\"hello\"")
                   , (["prop2","bar","baz2"], "\"world\"")
                   ]

readProp :: forall path. (KnownPath path, Read (TypeOf path))
         => MicroController -> IO (Property path)
readProp mc = do
  let path = pathVal (Proxy @path)
  Property . read <$> readIORef (mc ! path)

writeProp :: forall path. (KnownPath path, Show (TypeOf path), Writeable path)
          => Property path -> MicroController -> IO ()
writeProp prop mc = do
  let path = pathVal prop
  writeIORef (mc ! path) (show (getProperty prop))

main :: IO ()
main = do
  mc <- newmc
  (prop1 :: Property '["prop1"]) <- readProp mc
  print prop1
  -- writeProp prop1 mc  -- type error: couldn't match RO with RW
  (baz1 :: Property '["prop2", "bar", "baz1"]) <- readProp mc
  print baz1
  let baz2' = Property @'["prop2", "bar", "baz2"] "Steve"
  writeProp baz2' mc
  (baz2 :: Property '["prop2", "bar", "baz2"]) <- readProp mc
  print baz2
</code>```

Body:
I have a remote microcontroller that exposes some properties in a tree like view. These properties can all be read and some of them can be written to. A property is just a string where each level of the tree is delimited by a ..

As an example the property tree looks something like this:

Properties.prop1 = 0
Properties.prop2.foo = 1337
Properties.prop2.bar.baz1 = "hello"
Properties.prop2.bar.baz2 = "world"

Where Properties.prop1 and Properties.prop2.foo are readable only. Properties.prop2.bar.baz1 and Properties.prop2.bar.baz2 are readable and writeable. Anyway I want to encode this in Haskell using strong typing.

data Bar = Baz1 String | Baz2 String
data Prop2 = Foo Int | Bar Bar
data Properties = Prop1 Int | Prop2 Prop2

Now you can pretty nicely create a property:

p = Prop2 $ Bar $ Baz1 "hello"

But what I'm missing is how I can associate a single "path" through these constructors as either a readable property or a read/writeable property. Ideally I would like to have a class or type family "ReadableProp" and "WriteableProp" which would allow me to write something like:

writeProp :: WriteableProp a => a -> IO ()
writeProp = ...

readProp :: ReadableProp a => IO a
readProp = ...

I know this doesn't work at all right now. But I'm open to change the data structure or use something else to achieve something like this.

Does anyone have any idea?

Thank you for reading!

Body:
As an alternative, instead of representing your property tree path components as a collection of algebraic type "nodes" and constructor "leaves", consider a more uniform representation as a type-level tree that stores the accessibility and type as the tree's (leaf) values:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}

import GHC.TypeLits
import Data.Kind

data Value = RO Type | RW Type
data Tree = Leaf Symbol Value | Node Symbol [Tree]

type Properties
  = [ Leaf "prop1" (RO Int)
    , Node "prop2" [ Leaf "foo" (RO Int)
                   , Node "bar" [ Leaf "baz1" (RW String)
                                , Leaf "baz2" (RW String)
                                ]
                   ]
    ]

If you write a type-level lookup function for property paths:

{-# LANGUAGE TypeOperators #-}

type Lookup path = Lookup1 path Properties
type family Lookup1 path props where
  Lookup1 (p:ps) (Node p props' : props) = Lookup1 ps props'
  Lookup1 '[p]   (Leaf p val : qs) = val
  Lookup1 path   (prop : props) = Lookup1 path props

that works like so:

> :kind! Lookup '["prop1"]
Lookup '["prop1"] :: Value
= 'RO Int
> :kind! Lookup '["prop2", "bar", "baz1"]
Lookup '["prop2", "bar", "baz1"] :: Value
= 'RW String

that gives you most of what you need.  With a couple of convenience type-level functions:

{-# LANGUAGE ConstraintKinds #-}
type TypeOf path = GetType (Lookup path)
type Writeable path = GetAccess (Lookup path) ~ RW
type family GetType (value :: Value) where GetType (access a) = a
type family GetAccess (value :: Value) where GetAccess (access a) = access

you can define properties as:

data Property path = Property { getProperty :: TypeOf path }

letting you create new, type-safe property values like so:

> Property @'["prop1"] 5
Property @'["prop1"] 5 :: Property '["prop1"]
> Property @'["prop2","bar","baz1"] "hello"
Property @'["prop2","bar","baz1"] "hello"
  :: Property '["prop2", "bar", "baz1"]
> Property @'["prop2","bar","baz2"] 123  --- type error

With a utility class to get a value-level path from a type-level path:

{-# LANGUAGE ScopedTypeVariables #-}
import Data.Proxy

class KnownPath (path :: [Symbol]) where
  pathVal :: proxy path -> [String]
instance KnownPath '[] where pathVal _ = []
instance (KnownSymbol p, KnownPath ps) => KnownPath (p:ps) where
  pathVal _ = symbolVal (Proxy @p) : pathVal (Proxy @ps)

we can create a fake microcontroller, as a map of path/ioref pairs, where the values in the iorefs are Haskell printable representations that can be marshalled with Read/Show:

{-# LANGUAGE TupleSections #-}
import Data.Map.Strict (Map, (!))
import qualified Data.Map.Strict as Map
import Data.IORef

type MicroController = Map [String] (IORef String)

newmc :: IO MicroController
newmc
  = Map.fromList <$> mapM (\(k,v) -> (k,) <$> newIORef v) defaults
  where defaults = [ (["prop1"], "0")
                   , (["prop2","foo"], "1337")
                   , (["prop2","bar","baz1"], "\"hello\"")
                   , (["prop2","bar","baz2"], "\"world\"")
                   ]

The property read/write functions can be written like so.  Note the use of the Writeable path constraint on writeProp.

{-# LANGUAGE FlexibleContexts #-}

readProp :: forall path. (KnownPath path, Read (TypeOf path))
         => MicroController -> IO (Property path)
readProp mc = do
  let path = pathVal (Proxy @path)
  Property . read <$> readIORef (mc ! path)

writeProp :: forall path. (KnownPath path, Show (TypeOf path), Writeable path)
          => Property path -> MicroController -> IO ()
writeProp prop mc = do
  let path = pathVal prop
  writeIORef (mc ! path) (show (getProperty prop))

We can test it like so:

{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
deriving instance (Show (TypeOf path)) => (Show (Property path))

main :: IO ()
main = do
  mc <- newmc
  (prop1 :: Property '["prop1"]) <- readProp mc
  print prop1
  -- writeProp prop1 mc  -- type error: couldn't match RO with RW
  (baz1 :: Property '["prop2", "bar", "baz1"]) <- readProp mc
  print baz1
  let baz2' = Property @'["prop2", "bar", "baz2"] "Steve"
  writeProp baz2' mc
  (baz2 :: Property '["prop2", "bar", "baz2"]) <- readProp mc
  print baz2

The main advantages of this approach are that the property tree is exposed as as single type-level "structure" with a straightforward tree-like representation, and the KnownPath class provides an automatic mapping to value-level property paths, saving you the trouble of writing a lot of boilerplate to map a network of algebraic types to their property paths.  The disadvantages are somewhat uglier syntax, and the need to get the right mix of type applications, proxies, and optional versus mandatory ticked promoters.

Anyway, the full code is:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}

import GHC.TypeLits
import Data.Kind
import Data.Proxy
import Data.Map.Strict (Map, (!))
import qualified Data.Map.Strict as Map
import Data.IORef

data Value = RO Type | RW Type
data Tree = Leaf Symbol Value | Node Symbol [Tree]

type Properties
  = [ Leaf "prop1" (RO Int)
    , Node "prop2" [ Leaf "foo" (RO Int)
                   , Node "bar" [ Leaf "baz1" (RW String)
                                , Leaf "baz2" (RW String)
                                ]
                   ]
    ]

type Lookup path = Lookup1 path Properties
type family Lookup1 path props where
  Lookup1 (p:ps) (Node p props' : props) = Lookup1 ps props'
  Lookup1 '[p]   (Leaf p val : qs) = val
  Lookup1 path   (prop : props) = Lookup1 path props
type TypeOf path = GetType (Lookup path)
type Writeable path = GetAccess (Lookup path) ~ RW
type family GetType (value :: Value) where GetType (access a) = a
type family GetAccess (value :: Value) where GetAccess (access a) = access

data Property path = Property { getProperty :: TypeOf path }
deriving instance (Show (TypeOf path)) => (Show (Property path))

class KnownPath (path :: [Symbol]) where
  pathVal :: proxy path -> [String]
instance KnownPath '[] where pathVal _ = []
instance (KnownSymbol p, KnownPath ps) => KnownPath (p:ps) where
  pathVal _ = symbolVal (Proxy @p) : pathVal (Proxy @ps)

type MicroController = Map [String] (IORef String)

newmc :: IO MicroController
newmc
  = Map.fromList <$> mapM (\(k,v) -> (k,) <$> newIORef v) defaults
  where defaults = [ (["prop1"], "0")
                   , (["prop2","foo"], "1337")
                   , (["prop2","bar","baz1"], "\"hello\"")
                   , (["prop2","bar","baz2"], "\"world\"")
                   ]

readProp :: forall path. (KnownPath path, Read (TypeOf path))
         => MicroController -> IO (Property path)
readProp mc = do
  let path = pathVal (Proxy @path)
  Property . read <$> readIORef (mc ! path)

writeProp :: forall path. (KnownPath path, Show (TypeOf path), Writeable path)
          => Property path -> MicroController -> IO ()
writeProp prop mc = do
  let path = pathVal prop
  writeIORef (mc ! path) (show (getProperty prop))

main :: IO ()
main = do
  mc <- newmc
  (prop1 :: Property '["prop1"]) <- readProp mc
  print prop1
  -- writeProp prop1 mc  -- type error: couldn't match RO with RW
  (baz1 :: Property '["prop2", "bar", "baz1"]) <- readProp mc
  print baz1
  let baz2' = Property @'["prop2", "bar", "baz2"] "Steve"
  writeProp baz2' mc
  (baz2 :: Property '["prop2", "bar", "baz2"]) <- readProp mc
  print baz2


来源: stackexchange

问:
2 Tables 1 Result, a tricky SQL
After many years lurking stackoverflow, I finally have the need to come to you dev gurus in search for a little bit of help.

Context:

I'm a developer that is playing with information that I extract from SAP.
I'm extracting the info and I'm creating two tables in memory using H2 database.

My tables look like this:

```<code>CREATE TABLE USERS
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     BNAME VARCHAR(255),
     GLTGV DATE,
     GLTGB DATE,
     USTYP VARCHAR(2),
     LOCNT VARCHAR(3),
     UFLAG VARCHAR(3),
     TRDAT DATE,
     LTIME VARCHAR(255),
     CLASS VARCHAR(255),
     PWDCHGDATE DATE,
     PROFILE VARCHAR(255)
)

CREATE TABLE ROLES
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     UNAME VARCHAR(255),
     AGR_NAME VARCHAR(255)
)
</code>```

Do not worry about the definitions, I'm just "dummyfing" them for the sake of simplicity.

One user can have none or many roles. How do you tie them together?

Well SYSID, MANDT and BNAME from table USERS have to match the content of the ROLES table, columns SYSID, MANDT and UNAME (all of the same type)

So I have created this query

```<code>SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE")
</code>```

which works well as long as I only query by one ROLE.

To query for more than one role, I do

```<code>SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" OR t2.AGR_NAME = "ZTEST_ROLE2")
</code>```

It also works. You would use this query if you want to get info from all the users that either have ZTEST_ROLE or ZTEST_ROLE2 as roles.

Now, here is my problem, I cannot make it to work if I want to select all the users that have both roles ZTEST_ROLE and ZTEST_ROLE2. my query always return 0 rows

Here is the query that I'm using

```<code>SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" AND t2.AGR_NAME = "ZTEST_ROLE")
</code>```

I have been playing with this for a while and I do not see where my error is

For convenience and in case you want to try this online, I have been using https://sqliteonline.com/

I appreciate your help and my apologies for the long post

答:
You cant have both at the same time

(t2.AGR_NAME = "ZTEST_ROLE" and t2.AGR_NAME = "ZTEST_ROLE2")

here you are saying
t2.AGR_NAME = "ZTEST_ROLE" must be true while also t2.AGR_NAME = "ZTEST_ROLE2" must be true on the same row.

you could do

(t2.AGR_NAME = "ZTEST_ROLE" and  (select AGR_NAME from ROLES where uname = t1.bname and agr_name = "ZTEST_ROLE2") = "ZTEST_ROLE2"))

but i doubt this is the best way to do it. kinda hacky

Here is your example

https://dbfiddle.uk/?rdbms=sqlite_3.27&fiddle=18052895bcd6bea155ef01c957a06ff7

ContentLicense: CC BY-SA 4.0

Title: 2 Tables 1 Result, a tricky SQL

Body:
After many years lurking stackoverflow, I finally have the need to come to you dev gurus in search for a little bit of help.

Context:

I'm a developer that is playing with information that I extract from SAP.
I'm extracting the info and I'm creating two tables in memory using H2 database.

My tables look like this:

CREATE TABLE USERS
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     BNAME VARCHAR(255),
     GLTGV DATE,
     GLTGB DATE,
     USTYP VARCHAR(2),
     LOCNT VARCHAR(3),
     UFLAG VARCHAR(3),
     TRDAT DATE,
     LTIME VARCHAR(255),
     CLASS VARCHAR(255),
     PWDCHGDATE DATE,
     PROFILE VARCHAR(255)
)

CREATE TABLE ROLES
(
     SID VARCHAR(255),
     SYSID VARCHAR(5),
     MANDT VARCHAR(3),
     UNAME VARCHAR(255),
     AGR_NAME VARCHAR(255)
)

Do not worry about the definitions, I'm just "dummyfing" them for the sake of simplicity.

One user can have none or many roles. How do you tie them together?

Well SYSID, MANDT and BNAME from table USERS have to match the content of the ROLES table, columns SYSID, MANDT and UNAME (all of the same type)

So I have created this query

SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE")

which works well as long as I only query by one ROLE.

To query for more than one role, I do

SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" OR t2.AGR_NAME = "ZTEST_ROLE2")

It also works. You would use this query if you want to get info from all the users that either have ZTEST_ROLE or ZTEST_ROLE2 as roles.

Now, here is my problem, I cannot make it to work if I want to select all the users that have both roles ZTEST_ROLE and ZTEST_ROLE2. my query always return 0 rows

Here is the query that I'm using

SELECT DISTINCT
    t1.SID,
    t1.SYSID,
    t1.MANDT,
    t1.BNAME,
    t1.GLTGV,
    t1.GLTGB,
    t1.USTYP,
    t1.LOCNT,
    t1.UFLAG,
    t1.TRDAT,
    t1.LTIME,
    t1.CLASS,
    t1.PWDCHGDATE,
    t1.PROFILE
FROM
    USERS AS t1,
    ROLES AS t2
WHERE
    t1.SYSID = t2.SYSID AND
    t1.MANDT = t2.MANDT AND
    t1.BNAME = t2.UNAME AND
    (t2.AGR_NAME = "ZTEST_ROLE" AND t2.AGR_NAME = "ZTEST_ROLE")

I have been playing with this for a while and I do not see where my error is

For convenience and in case you want to try this online, I have been using https://sqliteonline.com/

I appreciate your help and my apologies for the long post


问:
How to use Cloud Armor with GAE Flex?
I wonder if it is possible to use Cloud Armor with GAE Flex? Because in Cloud Armor's documentation, it says that you have to use an HTTPS Load Balancer. Since GAE Flex doesn't have a load balancer, how can we use Cloud Armor with GAE Flex? We have to use a WAF to prevent DDOS attacks. Is it possible to use Cloud Armor with GAE Flex through HTTPS Load Balancer? If so, can you explain how I can achieve this goal?

Thank you.

答:
For securing app engine apart from applying firewall rules is to apply for IAP if you want to restrict by user mode.[1]

[1]https://cloud.google.com/iap/docs/app-engine-quickstart

Title: How to use Cloud Armor with GAE Flex?


问:
Query using from / to tables
I have one from / to table which has some data like this:

```<code>FROM                 | TO
---------------------+----------------
Apple iPhone SE 64GB | IPHONE SE 64GB
</code>```

And I have two other tables which are populated with data from the FROM and from the TO columns respectively:

Table 1:

```<code>Device               | price
---------------------+--------
Apple iPhone SE 64GB | xxxx
</code>```

Table 2:

```<code>Device         | Price
---------------+--------
IPHONE SE 64GB | XXXX
</code>```

Sometimes, using a web scraper, the tables 1 and two get populated by values which won't exist in the From To table. For example:

Table 1:

```<code>Device         | price
---------------+--------
Samsung Flip Z | xxxx
</code>```

Table 2:

```<code>Device                    | Price
--------------------------+--------
Smartphone Samsung Flip Z | XXXX
</code>```

So, I'd have to insert one record inside the From To table like this:

```<code>FROM           | TO
---------------+----------------------------
Samsung Flip Z | Smartphone Samsung Flip Z
</code>```

So, given these three tables, is it possible to have a query to find out which values are and which values are not in the From To Table? Because we have to fill it periodically.

答:
you can use "where not exists"</p>

```<code>select *
FROM table1
WHERE NOT EXISTS ( SELECT 1 FROM table2 WHERE table1.id = table2.id)
</code>```

Title: Query using from / to tables

Body:
I have one from / to table which has some data like this:

FROM                 | TO
---------------------+----------------
Apple iPhone SE 64GB | IPHONE SE 64GB

And I have two other tables which are populated with data from the FROM and from the TO columns respectively:

Table 1:

Device               | price
---------------------+--------
Apple iPhone SE 64GB | xxxx

Table 2:

Device         | Price
---------------+--------
IPHONE SE 64GB | XXXX

Sometimes, using a web scraper, the tables 1 and two get populated by values which won't exist in the From To table. For example:

Table 1:

Device         | price
---------------+--------
Samsung Flip Z | xxxx

Table 2:

Device                    | Price
--------------------------+--------
Smartphone Samsung Flip Z | XXXX

So, I'd have to insert one record inside the From To table like this:

FROM           | TO
---------------+----------------------------
Samsung Flip Z | Smartphone Samsung Flip Z

So, given these three tables, is it possible to have a query to find out which values are and which values are not in the From To Table? Because we have to fill it periodically.

Body:
you can use "where not exists"

select *
FROM table1
WHERE NOT EXISTS ( SELECT 1 FROM table2 WHERE table1.id = table2.id)


问:
How to send confirmation mail to new email address in Laravel?
I have a form that can change current email address of a user. I want when user changes his current email address to a new email address to automatically sends confirmation mail to this new email address where user would confirm that email. How can that be done? Here is my code. Any help is appreciated.

UserProfileController.php

```<code>public function changeEmailAddress(UpdateEmailRequest $request)
{
    if ($request->new_email != $request->repeat_email)
        return response()->json(['status' => 'Emails do not match.'], 404);

    if ($request->new_email == $request->user()->email)
        return response()->json(['status' => 'Email cannot be the same as old email'], 404);

    if(sizeof(User::where('email','=',$request->new_email)->get()) > 0)
        return response()->json(['status' => 'Email already exists'], 404);

    $request->user()->email = $request->new_email;
    $request->user()->email_verified_at = null;
    $request->user()->save();

    return response()->json(['status' => 'success'], 200);
}
</code>```

index.blade.php

```<code><section data-edit="email" class="editEmail">
    <form action="{{ route('user.update.email') }}" method="POST" class="flex">
        @method('PATCH')
        @csrf
        <div class="form-group">
            <input type="text" placeholder="New Email Adress" name="new_email">
        </div>
        <div class="form-group">
            <input type="text" placeholder="Repeat Email Adress" name="repeat_email">
        </div>
        <div class="form-group">
            <button class="submit">BUTTON</button>
        </div>
    </form>
</section>
</code>```

web.php

```<code>Route::patch('/profile/change-email', 'UserProfileController@changeEmailAddress')-
 >name('user.update.email');
</code>```

UpdateEmailRequest.php

```<code>public function rules()
{
    return [
        'email' => ['string', 'email', 'max:255', 'unique:users,email'],
    ];
 }
</code>```

答:
Short answer:

All you should have to do is call event(new \Illuminate\Auth\Events\Registered($user));

If that doesn't work, there may be a few things you need to set up first (see Longer Answer).

Longer answer:

There are a few things you need in order to add backend support for user email verification.

First step is making sure your User model implements the proper methods:

```<code>// app/User.php:
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail {
    // this provides:
    //  ->markEmailAsVerified(),
    //  ->hasVerifiedEmail(): bool
    //  ->sendEmailVerificationNotification()
    use \Illuminate\Auth\MustVerifyEmail;
</code>```

There's a nice built-in event you can then use to fire off an email to users once they register. You can trigger this manually or as part of a model listener (not discussed here). This needs to be registered in your event listeners first, though. See Laravel's Event guide for more information.

```<code>// app/Providers/EventServiceProvider.php:
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider {

    protected $listen = [
        // ...
        'Illuminate\Auth\Events\Registered' => [
            'Illuminate\Auth\Listeners\SendEmailVerificationNotification',
        ],
</code>```

Once those two things are in place, triggering the verification email can be done anywhere in your application:

```<code>// fire off the Registered event, so that new users get a verification email
event(new \Illuminate\Auth\Events\Registered($user));
</code>```

This will only work if the event listener is in place, and User has the right hierarchy.

The event handler (SendEmailVerificationNotification) checks if $user is a MustVerifyEmail that's not already verified, and if it is, it calls $user->sendEmailVerificationNotification which fires off an instance of \Illuminate\Auth\Notifications\VerifyEmail.

Body:
I have a form that can change current email address of a user. I want when user changes his current email address to a new email address to automatically sends confirmation mail to this new email address where user would confirm that email. How can that be done? Here is my code. Any help is appreciated.

UserProfileController.php

public function changeEmailAddress(UpdateEmailRequest $request)
{
    if ($request->new_email != $request->repeat_email)
        return response()->json(['status' => 'Emails do not match.'], 404);

    if ($request->new_email == $request->user()->email)
        return response()->json(['status' => 'Email cannot be the same as old email'], 404);

    if(sizeof(User::where('email','=',$request->new_email)->get()) > 0)
        return response()->json(['status' => 'Email already exists'], 404);

    $request->user()->email = $request->new_email;
    $request->user()->email_verified_at = null;
    $request->user()->save();

    return response()->json(['status' => 'success'], 200);
}

index.blade.php

    <form action="{{ route('user.update.email') }}" method="POST" class="flex">
        @method('PATCH')
        @csrf

            <input type="text" placeholder="New Email Adress" name="new_email">

            <input type="text" placeholder="Repeat Email Adress" name="repeat_email">

            <button class="submit">BUTTON</button>

    </form>

web.php

Route::patch('/profile/change-email', 'UserProfileController@changeEmailAddress')-
 >name('user.update.email');

UpdateEmailRequest.php

public function rules()
{
    return [
        'email' => ['string', 'email', 'max:255', 'unique:users,email'],
    ];
 }

Body:
Short answer:

All you should have to do is call event(new \Illuminate\Auth\Events\Registered($user));

If that doesn't work, there may be a few things you need to set up first (see Longer Answer).

Longer answer:

There are a few things you need in order to add backend support for user email verification.

First step is making sure your User model implements the proper methods:

// app/User.php:
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail {
    // this provides:
    //  ->markEmailAsVerified(),
    //  ->hasVerifiedEmail(): bool
    //  ->sendEmailVerificationNotification()
    use \Illuminate\Auth\MustVerifyEmail;

There's a nice built-in event you can then use to fire off an email to users once they register. You can trigger this manually or as part of a model listener (not discussed here). This needs to be registered in your event listeners first, though. See Laravel's Event guide for more information.

// app/Providers/EventServiceProvider.php:
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider {

    protected $listen = [
        // ...
        'Illuminate\Auth\Events\Registered' => [
            'Illuminate\Auth\Listeners\SendEmailVerificationNotification',
        ],

Once those two things are in place, triggering the verification email can be done anywhere in your application:

// fire off the Registered event, so that new users get a verification email
event(new \Illuminate\Auth\Events\Registered($user));

This will only work if the event listener is in place, and User has the right hierarchy.

The event handler (SendEmailVerificationNotification) checks if $user is a MustVerifyEmail that's not already verified, and if it is, it calls $user->sendEmailVerificationNotification which fires off an instance of \Illuminate\Auth\Notifications\VerifyEmail.


问:
Scala - ambiguous reference to overloaded definition -- with varargs

Possible Duplicate:

  How do I disambiguate in Scala between methods with vararg and without

I am currently porting part of an application to scala and it uses the Oval library.  The method is question is the Validator.validate method.  It has two signatures:

```<code>List<ConstraintViolation> validate(Object validatedObject)
List<ConstraintViolation> validate(Object validatedObject, String... profiles)
</code>```

The scala code looks generally like this:

```<code>def validate(toValidate: AnyRef) = {
  val validator = createValidator
  validator.validate(toValidate)
}
</code>```

And the error message:

```<code>error: ambiguous reference to overloaded definition,
[INFO] both method validate in class Validator of type (x$1: Any,x$2: <repeated...>[java.lang.String])java.util.List[net.sf.oval.ConstraintViolation]
[INFO] and  method validate in class Validator of type (x$1: Any)java.util.List[net.sf.oval.ConstraintViolation]
[INFO] match argument types (AnyRef)
[INFO]       this.validator.validate(toValidate)
</code>```

How can I get this be be unambiguous?

答:
I think that this could be a duplicate of How do I disambiguate in Scala between methods with vararg and without

Basically, it is a known java-scala-interop problem, and the only workarounds involve extra Java adapters to make accessible in Scala.

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  How do I disambiguate in Scala between methods with vararg and without

I am currently porting part of an application to scala and it uses the Oval library.  The method is question is the Validator.validate method.  It has two signatures:

List<ConstraintViolation> validate(Object validatedObject)
List<ConstraintViolation> validate(Object validatedObject, String... profiles)

The scala code looks generally like this:

def validate(toValidate: AnyRef) = {
  val validator = createValidator
  validator.validate(toValidate)
}

And the error message:

error: ambiguous reference to overloaded definition,
[INFO] both method validate in class Validator of type (x$1: Any,x$2: <repeated...>[java.lang.String])java.util.List[net.sf.oval.ConstraintViolation]
[INFO] and  method validate in class Validator of type (x$1: Any)java.util.List[net.sf.oval.ConstraintViolation]
[INFO] match argument types (AnyRef)
[INFO]       this.validator.validate(toValidate)

How can I get this be be unambiguous?


问:
How and where to store api response data so that i can be used whenever needed in flutter?
Im just trying to store the response i get somewhere but could not figure out where and how. Ive read about shared preferences but was confused about how to store json data there. Can some one please help me and explain me abouth this scenario?</p>

答:
It depends on how much data you have. If it isn't much, you can use SharedPreferences (json is just stored as String).

If you have alot of data, I suggest using sqflite. It is pretty simple to implement, have a look at the docs here: https://pub.dev/packages/sqflite


问:
How do I disable webpack 4 code splitting?
I'm using webpack 4.43.0.

How do I prevent codesplitting from happening in webpack? All these files are created - 0.bundle.js up to 11.bundle.js (alongside the expected bundle.js), when I run webpack. Here's my webpack config:

```<code>/* eslint-env node */

const path = require('path');

module.exports = {
    entry: './media/js/src/main.jsx',
    mode: process.env.WEBPACK_SERVE ? 'development' : 'production',
    output: {
        path: path.resolve(__dirname, 'media/js'),
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['*', '.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                include: path.resolve(__dirname, 'media/js/src'),
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react']
                    }
                }
            }
        ]
    }
};
</code>```

答:
You can use webpack's LimitChunkCountPlugin to limit the chunk count produced by code splitting:

In your webpack.config.js file:

```<code>const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.optimize.LimitChunkCountPlugin({
      maxChunks: 1
    })
  ],
  ...
};
</code>```

You could also pass the --optimize-max-chunks option to the webpack command directly.

So, in your package.json file:

```<code>{
  "scripts": {
    "build": "webpack --optimize-max-chunks 1",
    ...
  },
  ...
}
</code>```

Now, when you run npm run build, webpack will build only one file (or "chunk").

Body:
I'm using webpack 4.43.0.

How do I prevent codesplitting from happening in webpack? All these files are created - 0.bundle.js up to 11.bundle.js (alongside the expected bundle.js), when I run webpack. Here's my webpack config:

/* eslint-env node */

const path = require('path');

module.exports = {
    entry: './media/js/src/main.jsx',
    mode: process.env.WEBPACK_SERVE ? 'development' : 'production',
    output: {
        path: path.resolve(__dirname, 'media/js'),
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['*', '.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                include: path.resolve(__dirname, 'media/js/src'),
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react']
                    }
                }
            }
        ]
    }
};

Body:
You can use webpack's LimitChunkCountPlugin to limit the chunk count produced by code splitting:

In your webpack.config.js file:

const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.optimize.LimitChunkCountPlugin({
      maxChunks: 1
    })
  ],
  ...
};

You could also pass the --optimize-max-chunks option to the webpack command directly.

So, in your package.json file:

{
  "scripts": {
    "build": "webpack --optimize-max-chunks 1",
    ...
  },
  ...
}

Now, when you run npm run build, webpack will build only one file (or "chunk").


问:
Problem getting data from linked server error in SQL
I m working in SQL and I have few tables in Oracle database from which I have to get data, so I m doing so via linked server. If I omit date filter then the query works fine but if I apply date filter then it breaks.

This query works fine.

```<code>select * from openquery([ORCL], 'select sls_value, retailer_cd, tery_cd, inv_dt
from Toc_cust_second_sls_new where cust_cd IN ( ''1-ZUT42P'' )') secSls --- This query works fine
</code>```

This query breaks

```<code>select * from openquery([ORCL], 'select sls_value, retailer_cd, tery_cd, inv_dt from Toc_cust_second_sls_new where cust_cd IN ( ''1-ZUT42P'' )
and to_date(inv_dt, ''dd/mm/yyyy'') between to_date(''01/05/2020'', ''dd/mm/yyyy'') and to_date(''31/05/2020'', ''dd/mm/yyyy'')') secSls
</code>```

I get this error.

OLE DB provider "OraOLEDB.Oracle" for linked server "ORCL" returned message "ORA-01861: literal does not match format string".

To filter date I can use this query as it works fine.

```<code>select * from openquery([ORCL], 'select sls_value, retailer_cd, tery_cd, inv_dt, inv_no, cust_cd from Toc_cust_second_sls_new
where cust_cd IN ( ''1-ZUT42P'' )') secSls
where convert(date,secSls.inv_dt, 101) >= '2020-05-01' and convert(date,secSls.inv_dt, 101) <= '2020-05-31'
</code>```

But the problem in the above query is, it first gets all the data from oracle then it filters so there are hundreds if thousands of records which takes a lot of time.

答:
I solved it.

I removed the conversion of inv_dt in oracle as it's data type was already Date, trying to again convert it was creating problem.

```<code>select * from openquery([ORCL], 'select sls_value, retailer_cd, tery_cd, inv_dt from Toc_cust_second_sls_new where cust_cd IN ( ''1-ZUT42P'' ) and inv_dt between to_date(''01/05/2020'', ''dd/mm/yyyy'') and to_date(''31/05/2020'',''dd/mm/yyyy'')') secSls
</code>```

This query works now. Thanks guys who helped me out on comments section.

Body:
I m working in SQL and I have few tables in Oracle database from which I have to get data, so I m doing so via linked server. If I omit date filter then the query works fine but if I apply date filter then it breaks.

This query works fine.

select * from openquery([ORCL], 'select sls_value, retailer_cd, tery_cd, inv_dt
from Toc_cust_second_sls_new where cust_cd IN ( ''1-ZUT42P'' )') secSls --- This query works fine

This query breaks

select * from openquery([ORCL], 'select sls_value, retailer_cd, tery_cd, inv_dt from Toc_cust_second_sls_new where cust_cd IN ( ''1-ZUT42P'' )
and to_date(inv_dt, ''dd/mm/yyyy'') between to_date(''01/05/2020'', ''dd/mm/yyyy'') and to_date(''31/05/2020'', ''dd/mm/yyyy'')') secSls

I get this error.

OLE DB provider "OraOLEDB.Oracle" for linked server "ORCL" returned message "ORA-01861: literal does not match format string".

To filter date I can use this query as it works fine.

select * from openquery([ORCL], 'select sls_value, retailer_cd, tery_cd, inv_dt, inv_no, cust_cd from Toc_cust_second_sls_new
where cust_cd IN ( ''1-ZUT42P'' )') secSls
where convert(date,secSls.inv_dt, 101) >= '2020-05-01' and convert(date,secSls.inv_dt, 101) <= '2020-05-31'

But the problem in the above query is, it first gets all the data from oracle then it filters so there are hundreds if thousands of records which takes a lot of time.

Body:
I solved it.

I removed the conversion of inv_dt in oracle as it's data type was already Date, trying to again convert it was creating problem.

select * from openquery([ORCL], 'select sls_value, retailer_cd, tery_cd, inv_dt from Toc_cust_second_sls_new where cust_cd IN ( ''1-ZUT42P'' ) and inv_dt between to_date(''01/05/2020'', ''dd/mm/yyyy'') and to_date(''31/05/2020'',''dd/mm/yyyy'')') secSls

This query works now. Thanks guys who helped me out on comments section.


问:
Concatenate a list until a certain character
I have this list:

```<code>Jokes =   ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']
</code>```

I would want to concatenate the list as follow:

```<code>Jokes = ['First joke \n Still first', 'Second joke \n Still second joke \n Still 2nd joke']
</code>```

Is this somehow possible?

Thank you,

答:
Here is an example solution:</p>

```<code>jokes = ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']

groups = [[]]
for part in jokes:
    if part:
        groups[-1].append(part)
    else:
        groups.append([])

result = [' \n '.join(joke) for joke in groups]
print(result)
</code>```

Body:
I have this list:

Jokes =   ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']

I would want to concatenate the list as follow:

Jokes = ['First joke \n Still first', 'Second joke \n Still second joke \n Still 2nd joke']

Is this somehow possible?

Thank you,

Body:
Here is an example solution:

jokes = ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']

groups = [[]]
for part in jokes:
    if part:
        groups[-1].append(part)
    else:
        groups.append([])

result = [' \n '.join(joke) for joke in groups]
print(result)


问:
Arithmetic on a pointer to void error when compile a third party library
I'm trying to compile a third party library, but for some reason I'm getting an error. The library is likely compiled differently. I've read up on the error but I can't seem to figure out what the issue is! :(

```<code>struct sfo_entry {
    char* key;
    size_t size;
    size_t area;
    void* value;
    enum sfo_value_format format;
    struct sfo_entry* next;
    struct sfo_entry* prev;
};

struct sfo {
    struct sfo_entry* entries;
};

bool sfo_load_from_memory(struct sfo* sfo, const void* data, size_t data_size) {
    struct sfo_header* hdr;
    struct sfo_table_entry* entry_table;
    struct sfo_table_entry* entry;

    entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));

    // ...

    return true;
}
</code>```

The error is as follows:

```<code> sfo.cpp:150:47: error: arithmetic on a pointer to void
         entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));
                                                 ~~~~ ^
</code>```

答: We can't do arithmetic operation on void* pointer as it doesn't have information regarding the underlying object type. Cast to appropriate pointer type and do arithmetic on it.

Body:
I'm trying to compile a third party library, but for some reason I'm getting an error. The library is likely compiled differently. I've read up on the error but I can't seem to figure out what the issue is! :(

struct sfo_entry {
    char* key;
    size_t size;
    size_t area;
    void* value;
    enum sfo_value_format format;
    struct sfo_entry* next;
    struct sfo_entry* prev;
};

struct sfo {
    struct sfo_entry* entries;
};

bool sfo_load_from_memory(struct sfo* sfo, const void* data, size_t data_size) {
    struct sfo_header* hdr;
    struct sfo_table_entry* entry_table;
    struct sfo_table_entry* entry;

    entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));

    // ...

    return true;
}

The error is as follows:

 sfo.cpp:150:47: error: arithmetic on a pointer to void
         entry_table = (struct sfo_table_entry*)(data + sizeof(*hdr));
                                                 ~~~~ ^


问:
HTML Validation: Why is it not valid to put an interactive element inside an interactive element?
Disclaimer: I understand that it is not valid HTML. I am trying to understand why is it not allowed?

W3C suggests that an interactive element like button or a mustn't contain another interactive element.

I could find a lot of resources mentioning this rule and some workarounds, also some resources related to how this impacts accessibility and screenreaders, but almost all of those resources talk about the fact that this is a requirement but do not explain why.

https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html

https://codepen.io/vloux/pen/wXGyOv

Nesting  inside <button> doesn't work in Firefox

https://github.com/dequelabs/axe-core/issues/601

I wasn't really able to find an explanation for why is it not allowed? does it lead to any usability problems?

This is a related question:
Why should interactive element not be used within an anchor?

The accepted answer is satisfactory but is not enough to make this rule a requirement. The described situation can be avoided using proper event handling.

Also, if nested interactive content is invalid, how are we supposed to have something like this:

A card which is clickable as a whole, and also has a clickable secondary CTA inside it.
I know a workaround would be to have a primary and secondary CTA inside the card, but shouldn't the above be allowed as well?

Here is a fiddle:
https://jsfiddle.net/t9qbwas5/2/

```<code><button type="button" class="card">
  The card itself is the primary CTA.
  <br/>
  <br/>
  some important content to read through.
  some important content to read through.
  some important content to read through.
  <div class="cta">
   Secondary CTA
  </div>
</button>

.cta {
  padding: 4px;
  background: #00a9a9;
  color: white;
  width: 80px;
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
}

.card {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}
</code>```

In the above example, I am achieving this by using a clickable div inside the button, but that is not semantic (?) and also functionality wise, it is an interactive element inside another one. I am trying to understand that even if I use this workaround, is it fundamentally wrong to have nested interactive elements? is it a bad design/usability practice?

答:
One important problem is related to event-capturing; if you click on a interactive element nested inside another interactive element(e.g. a select inside a clickable button) there would be an interference here and two case might happen depends on the browser;

case 1 is that both element will raise that event (e.g. click) event

case 2 is that parent element will capture the event and the nested element won't raise that event

in fact both cases will result in non-deterministic behavior;

This is not limited to click events actually, but click event is more tangible; Also the screen reader will fail to parse the markup; keyboard-interaction won't work as expected; try it in the snippet below:

del.addEventListener('click', function(){
  console.log('deleting ...')
})

save.addEventListener('click', function(){
  console.log('saving ...')
})

sel.addEventListener('change', function(){
  console.log('changing to', sel.value)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='del'>
delete
<button id='save'> save
<select id='sel'>
  <option>foo</option>
  <option>bar</option>
<select>
<input name='a' type='radio' />
<input name='a' type='radio' />
<input name='a' type='radio' />

</button>
</div></code>```

Body:
Disclaimer: I understand that it is not valid HTML. I am trying to understand why is it not allowed?

W3C suggests that an interactive element like button or a mustn't contain another interactive element.

I could find a lot of resources mentioning this rule and some workarounds, also some resources related to how this impacts accessibility and screenreaders, but almost all of those resources talk about the fact that this is a requirement but do not explain why.

https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html

https://codepen.io/vloux/pen/wXGyOv

Nesting  inside <button> doesn't work in Firefox

https://github.com/dequelabs/axe-core/issues/601

I wasn't really able to find an explanation for why is it not allowed? does it lead to any usability problems?

This is a related question:
Why should interactive element not be used within an anchor?

The accepted answer is satisfactory but is not enough to make this rule a requirement. The described situation can be avoided using proper event handling.

Also, if nested interactive content is invalid, how are we supposed to have something like this:

A card which is clickable as a whole, and also has a clickable secondary CTA inside it.
I know a workaround would be to have a primary and secondary CTA inside the card, but shouldn't the above be allowed as well?

Here is a fiddle:
https://jsfiddle.net/t9qbwas5/2/

<button type="button" class="card">
  The card itself is the primary CTA.

  some important content to read through.
  some important content to read through.
  some important content to read through.

   Secondary CTA

</button>

.cta {
  padding: 4px;
  background: #00a9a9;
  color: white;
  width: 80px;
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
}

.card {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

In the above example, I am achieving this by using a clickable div inside the button, but that is not semantic (?) and also functionality wise, it is an interactive element inside another one. I am trying to understand that even if I use this workaround, is it fundamentally wrong to have nested interactive elements? is it a bad design/usability practice?

Body:
One important problem is related to event-capturing; if you click on a interactive element nested inside another interactive element(e.g. a select inside a clickable button) there would be an interference here and two case might happen depends on the browser;

case 1 is that both element will raise that event (e.g. click) event

case 2 is that parent element will capture the event and the nested element won't raise that event

in fact both cases will result in non-deterministic behavior;

This is not limited to click events actually, but click event is more tangible; Also the screen reader will fail to parse the markup; keyboard-interaction won't work as expected; try it in the snippet below:

del.addEventListener('click', function(){
  console.log('deleting ...')
})

save.addEventListener('click', function(){
  console.log('saving ...')
})

sel.addEventListener('change', function(){
  console.log('changing to', sel.value)
})

<div id='del'>
delete
<button id='save'> save
<select id='sel'>
  <option>foo</option>
  <option>bar</option>
<select>
<input name='a' type='radio' />
<input name='a' type='radio' />
<input name='a' type='radio' />

</button>
</div>


问:
HTML Table Row Height Problem (height="x" vs style="height:x")
Using Chrome on Windows 10, this code "works", in the sense that it creates an empty row that is 100px tall...

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Test</title>
  </head>
  <body>
    <table id="content" style="width:100%;border:1px solid black">
      <tr id="topRow" height="100" style="width:100%;"></tr>
    </table>
  </body>
</html>
</code>```

... but the following doesn't, in that it generates a very short row, certainly not 100 pixels tall ...

```<code><html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Test</title>
  </head>
  <body>
    <table id="content" style="width:100%;border:1px solid black">
      <tr id="topRow" style="width:100%;height=100px"></tr>
    </table>
  </body>
</html>
</code>```

I was trying to use the latter form since the former is deprecated (if not obsolete).

What am I doing wrong or, more likely, misunderstanding?

答:
@BoCoKeith
Please replace = with : in you second code

in

Hope this will work

Body:
Using Chrome on Windows 10, this code "works", in the sense that it creates an empty row that is 100px tall...

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Test</title>

... but the following doesn't, in that it generates a very short row, certainly not 100 pixels tall ...

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Test</title>

I was trying to use the latter form since the former is deprecated (if not obsolete).

What am I doing wrong or, more likely, misunderstanding?

Body:
@BoCoKeith
Please replace = with : in you second code

in <tr style="height **=** changes to **:** ">

Hope this will work


问:
Using Oracle database links without unreadable dynamic SQL
How can I write a neat PL/SQL stored procedure that can execute against a given database link?

It gets really messy, writing stuff like this:

```<code>   PROCEDURE my_proc(aDbLink IN VARCHAR2)
   IS
   BEGIN
       EXECUTE IMMEDIATE '
       SELECT mycolumn, anothercolumn
       FROM MYTABLE@' || aDbLink || '
       WHERE such-and-such...'
   END
</code>```

as the query gets bigger.

What else might I do? I'm stuck using stored procedures, and expect that my procedures will execute against one of several db links.

答:
The simplest way to avoid using dynamic SQL would be to create synonyms.

```<code>CREATE OR REPLACE SYNONYM MyTableRemote
   FOR MyTable@database_link
</code>```

Your stored procedures would then simply refer to the synonym MyTableRemote.  You could then have a separate method that took the database link name as a parameter and changed all the synonyms to point at the database link.

```<code>PROCEDURE replace_synonyms( p_db_link IN VARCHAR2 )
AS
BEGIN
  -- Adjust the query to identify all the synonyms that you want to recreate
  FOR syn IN (SELECT *
                FROM user_synonyms
               WHERE db_link IS NOT NULL)
  LOOP
    EXECUTE IMMEDIATE
      'CREATE OR REPLACE SYNONYM ' || syn.synonym_name ||
      '   FOR ' || syn.table_owner || '.' || syn.table_name || '@' || p_db_link;
  END LOOP;
END;
</code>```

Body:
How can I write a neat PL/SQL stored procedure that can execute against a given database link?

It gets really messy, writing stuff like this:

   PROCEDURE my_proc(aDbLink IN VARCHAR2)
   IS
   BEGIN
       EXECUTE IMMEDIATE '
       SELECT mycolumn, anothercolumn
       FROM MYTABLE@' || aDbLink || '
       WHERE such-and-such...'
   END

as the query gets bigger.

What else might I do? I'm stuck using stored procedures, and expect that my procedures will execute against one of several db links.

Body:
The simplest way to avoid using dynamic SQL would be to create synonyms.

CREATE OR REPLACE SYNONYM MyTableRemote
   FOR MyTable@database_link

Your stored procedures would then simply refer to the synonym MyTableRemote.  You could then have a separate method that took the database link name as a parameter and changed all the synonyms to point at the database link.

PROCEDURE replace_synonyms( p_db_link IN VARCHAR2 )
AS
BEGIN
  -- Adjust the query to identify all the synonyms that you want to recreate
  FOR syn IN (SELECT *
                FROM user_synonyms
               WHERE db_link IS NOT NULL)
  LOOP
    EXECUTE IMMEDIATE
      'CREATE OR REPLACE SYNONYM ' || syn.synonym_name ||
      '   FOR ' || syn.table_owner || '.' || syn.table_name || '@' || p_db_link;
  END LOOP;
END;


问:
Ajax data not passing to controller
I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.

Here my function:

```<code>    function functionA() {
        $.ajax({
            url: URLToApi,
            method: 'POST',
            headers: {
                sessionStorage.getItem('token')
            },
            data: {
                access_token: sessionStorage.getItem('pageToken'),
                message: $('#comment').val(),
                id: sessionStorage.getItem('pageId')
            },
            success: function () {
                $('#success').text('It has been added!"');
            },
        });
    }
</code>```

答:
Check below things in Controller's action that

there should be a matching action in controller

name of parameter should be same as you are passing in data in ajax

Method type should be same the ajax POST of the action in controller.

 function AddPayment(id, amount) {
        var type = $("#paymenttype").val();
        var note = $("#note").val();
        var payingamount = $("#amount").val();
        $('#addPayment').preloader();
        $.ajax({
            type: "POST",
            url: "/Fixed/AddPayment",
            data: {
                id: id,
                amount: payingamount,
                type: type,
                note: note
            },
            success: function (data) {

            }
        });

    }```

Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action

Title: Ajax data not passing to controller

Body:
I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.

Here my function:

    function functionA() {
        $.ajax({
            url: URLToApi,
            method: 'POST',
            headers: {
                sessionStorage.getItem('token')
            },
            data: {
                access_token: sessionStorage.getItem('pageToken'),
                message: $('#comment').val(),
                id: sessionStorage.getItem('pageId')
            },
            success: function () {
                $('#success').text('It has been added!"');
            },
        });
    }

Body:
Check below things in Controller's action that

there should be a matching action in controller

name of parameter should be same as you are passing in data in ajax

Method type should be same the ajax POST of the action in controller.

 function AddPayment(id, amount) {
        var type = $("#paymenttype").val();
        var note = $("#note").val();
        var payingamount = $("#amount").val();
        $('#addPayment').preloader();
        $.ajax({
            type: "POST",
            url: "/Fixed/AddPayment",
            data: {
                id: id,
                amount: payingamount,
                type: type,
                note: note
            },
            success: function (data) {

            }
        });

    }

Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action


问:
PyCharm: msvcrt.kbhit() and msvcrt.getch() not working?
I've tried to read one char from the console in PyCharm (without pressing enter), but to no avail.
The functions msvcrt.getch() stops the code, but does not react to key presses (even enter), and msvcrt.kbhit() always returns 0. For example this code prints nothing:

```<code>import msvcrt
while 1:
    if msvcrt.kbhit():
        print 'reading'
print 'done'
</code>```

I am using Windows 7, PyCharm 3.4 (the same heppens in idle).

What is wrong? Is there any other way to just read input without enter?

答:
You are trying to compare <Class 'Bytes'> to <Class 'string'>.

Cast the key to a string and then compare:

```<code>import msvcrt

while True:
    if msvcrt.kbhit():
        key = str(msvcrt.getch())
        if key == "b'w'":
            print(key)
</code>```

To run the program in the Command Line go to: edit Configurations > Execution > enable "Emulate terminal in output console".

Body:
I've tried to read one char from the console in PyCharm (without pressing enter), but to no avail.
The functions msvcrt.getch() stops the code, but does not react to key presses (even enter), and msvcrt.kbhit() always returns 0. For example this code prints nothing:

import msvcrt
while 1:
    if msvcrt.kbhit():
        print 'reading'
print 'done'

I am using Windows 7, PyCharm 3.4 (the same heppens in idle).

What is wrong? Is there any other way to just read input without enter?

Body:
You are trying to compare <Class 'Bytes'> to <Class 'string'>.

Cast the key to a string and then compare:

import msvcrt

while True:
    if msvcrt.kbhit():
        key = str(msvcrt.getch())
        if key == "b'w'":
            print(key)

To run the program in the Command Line go to: edit Configurations > Execution > enable "Emulate terminal in output console".


问:
List C++ Move to front;
Hello i need to find the earliest note in one-Way listy
Unfortunately i can`t use list container.
Here some code

```<code>Struct

    struct Sterminarz
{
    Sterminarz *next=NULL;
    int year;
    int month;
    int day;
    int hour;
    string note;

};
</code>```

Function which look for earliest note

```<code>  void findEarliest(Sterminarz *head)
{
    Sterminarz *p, *min;
    min = head;
    int counter = 0;

    for(p=head->next;p;p=p->next)
    {
        if (p->hour < min->hour)
        {
            min = p;
            counter++;
            printNote(min, counter);

        }
    }

}
</code>```

And i don't know how to move earliest element to the beginning of the list without list container.

答: To move a node to the front of the list, you can first remove the node from the list, then add it to the head of the list. These are both general list operations. If you haven't written a remove() function for your list, then you should do that now. Similarly, you should write a add_to_head() function or a general add() function.

Title: List C++ Move to front;

Body:
Hello i need to find the earliest note in one-Way listy
Unfortunately i can`t use list container.
Here some code

Struct

    struct Sterminarz
{
    Sterminarz *next=NULL;
    int year;
    int month;
    int day;
    int hour;
    string note;

};

Function which look for earliest note

  void findEarliest(Sterminarz *head)
{
    Sterminarz *p, *min;
    min = head;
    int counter = 0;

    for(p=head->next;p;p=p->next)
    {
        if (p->hour < min->hour)
        {
            min = p;
            counter++;
            printNote(min, counter);

        }
    }

}

And i don't know how to move earliest element to the beginning of the list without list container.


问:
Pretty printing a list in a tabular format
Using Python 2.4, how do I print a list in a nice tabular format?

My list is in the below format.

```<code>mylist=[(('VAL1', 'VAL2', 'VAL3', 'VAL4', 'VAL5', 'VAL6'), AGGREGATE_VALUE)]
</code>```

I have tried pprint, but it does not print the result in a tabular format.

EDIT : I would like to see the output in the below format:

VAL1        VAL2     VAL3    VAL4    VAL5    VAL6        AGGREGATE_VALUE

This table, should account for variable item lengths and still print with proper indentation.

答:
```<code>mylist = [ ( ('12', '47', '4', '574862', '58', '7856'), 'AGGREGATE_VALUE1'),
           ( ('2', '75', '757', '8233', '838', '47775272785'), 'AGGREG2'),
           ( ('4144', '78', '78965', '778', '78578', '2'), 'AGGREGATE_VALUE3')]

longg = dict.fromkeys((0,1,2,3,4,5,6),0)

for tu,x in mylist:
    for i,el in enumerate(tu):
        longg[i] = max(longg[i],len(str(el)))
    longg[6] = max(longg[6],len(str(x)))

fofo = '  '.join('%'+str(longg[i])+'s' for i in xrange(0,7))
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)
</code>```

result

```<code>  12  47      4  574862     58         7856  AGGREGATE_VALUE1
   2  75    757    8233    838  47775272785           AGGREG2
4144  78  78965     778  78578            2  AGGREGATE_VALUE3
</code>```

Don't know if this fills your need

EDIT 1

Using string formatting with modulo operator (%) to print in a constant length, '%6s' right-justifies in a constant length of 6, and '%-6s' left-justifies in a constant length of 6.

You'll find precisions here

But there is no sense to specify a constant length to print something at the end of a string, because it's somewhat naturally-left-justified in this case.
Then :

```<code>longg = dict.fromkeys((0,1,2,3,4,5,),0)

for tu,x in mylist:
    for i,el in enumerate(tu):
        longg[i] = max(longg[i],len(str(el)))

fofo = '  '.join('%'+str(longg[i])+'s' for i in xrange(0,6)) + '  %s'
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)
</code>```

EDIT 2

```<code>mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
           ( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
           ( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

longg = dict.fromkeys((0,1,2,3,4,5),0)

for tu,_ in mylist:
    longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))

fofo = '  '.join('%%%ss' % longg[i] for i in xrange(0,6)) + '  %s'
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)
</code>```

EDIT 3

```<code>mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
           ( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
           ( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

header = ('Price1','Price2','reference','XYD','code','resp','AGGREG values')

longg = dict(zip((0,1,2,3,4,5,6),(len(str(x)) for x in header)))

for tu,x in mylist:
    longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))
    longg[6] = max(longg[6],len(str(x)))
fofo = ' | '.join('%%-%ss' % longg[i] for i in xrange(0,7))

print '\n'.join((fofo % header,
                 '-|-'.join( longg[i]*'-' for i in xrange(7)),
                 '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)))
</code>```

result

```<code>Price1 | Price2 | reference | XYD    | code  | resp        | AGGREG values
-------|--------|-----------|--------|-------|-------------|-----------------
12     | 47     | 4         | 574862 | 58    | 7856        | AGGREGATE_VALUE1
2      | 75     | 757       | 8233   | 838   | 47775272785 | AGGREG2
4144   | 78     | 78965     | 778    | 78578 | 2           | AGGREGATE_VALUE3
</code>```

Note that this kind of formatting would be much easier with the string's method format() introduced in Python 2.6

Body:
Using Python 2.4, how do I print a list in a nice tabular format?

My list is in the below format.

mylist=[(('VAL1', 'VAL2', 'VAL3', 'VAL4', 'VAL5', 'VAL6'), AGGREGATE_VALUE)]

I have tried pprint, but it does not print the result in a tabular format.

EDIT : I would like to see the output in the below format:

VAL1        VAL2     VAL3    VAL4    VAL5    VAL6        AGGREGATE_VALUE

This table, should account for variable item lengths and still print with proper indentation.

Body:
mylist = [ ( ('12', '47', '4', '574862', '58', '7856'), 'AGGREGATE_VALUE1'),
           ( ('2', '75', '757', '8233', '838', '47775272785'), 'AGGREG2'),
           ( ('4144', '78', '78965', '778', '78578', '2'), 'AGGREGATE_VALUE3')]

longg = dict.fromkeys((0,1,2,3,4,5,6),0)

for tu,x in mylist:
    for i,el in enumerate(tu):
        longg[i] = max(longg[i],len(str(el)))
    longg[6] = max(longg[6],len(str(x)))

fofo = '  '.join('%'+str(longg[i])+'s' for i in xrange(0,7))
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

result

  12  47      4  574862     58         7856  AGGREGATE_VALUE1
   2  75    757    8233    838  47775272785           AGGREG2
4144  78  78965     778  78578            2  AGGREGATE_VALUE3

Don't know if this fills your need

EDIT 1

Using string formatting with modulo operator (%) to print in a constant length, '%6s' right-justifies in a constant length of 6, and '%-6s' left-justifies in a constant length of 6.

You'll find precisions here

But there is no sense to specify a constant length to print something at the end of a string, because it's somewhat naturally-left-justified in this case.
Then :

longg = dict.fromkeys((0,1,2,3,4,5,),0)

for tu,x in mylist:
    for i,el in enumerate(tu):
        longg[i] = max(longg[i],len(str(el)))

fofo = '  '.join('%'+str(longg[i])+'s' for i in xrange(0,6)) + '  %s'
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

EDIT 2

mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
           ( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
           ( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

longg = dict.fromkeys((0,1,2,3,4,5),0)

for tu,_ in mylist:
    longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))

fofo = '  '.join('%%%ss' % longg[i] for i in xrange(0,6)) + '  %s'
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

EDIT 3

mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
           ( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
           ( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

header = ('Price1','Price2','reference','XYD','code','resp','AGGREG values')

longg = dict(zip((0,1,2,3,4,5,6),(len(str(x)) for x in header)))

for tu,x in mylist:
    longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))
    longg[6] = max(longg[6],len(str(x)))
fofo = ' | '.join('%%-%ss' % longg[i] for i in xrange(0,7))

print '\n'.join((fofo % header,
                 '-|-'.join( longg[i]*'-' for i in xrange(7)),
                 '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)))

result

Price1 | Price2 | reference | XYD    | code  | resp        | AGGREG values
-------|--------|-----------|--------|-------|-------------|-----------------
12     | 47     | 4         | 574862 | 58    | 7856        | AGGREGATE_VALUE1
2      | 75     | 757       | 8233   | 838   | 47775272785 | AGGREG2
4144   | 78     | 78965     | 778    | 78578 | 2           | AGGREGATE_VALUE3

Note that this kind of formatting would be much easier with the string's method format() introduced in Python 2.6


问:
Django - Restrict Stripe SuccessUrl access
I have just integrated Stripe Checkout with my Django app. However, from their code:

```<code> session = stripe.checkout.Session.create(
        customer_email=customer.email,
        payment_method_types=['card'],
        line_items=line_items,

        mode='payment',
        success_url='http://127.0.0.1:8000/SUCCESS/?session_id={CHECKOUT_SESSION_ID}',
        cancel_url='http://127.0.0.1:8000/cart'
        )
</code>```

It redirects to a Success_url. I would like to display their order info and send an email from the success page but currently, everyone can visit(would cause random emails etc). Is there a way i can limit this for the person that just checked out? Thank you!

答:
The success page should really just be a page to let your users know that their payment went through. I wouldn't personally recommend triggering any app-specific logic when your users land on it. As you've pointed out this could cause accidents with users randomly stumbling on that page and triggering emails. It also offers an opportunity for bad actors to exploit your application.

Instead, I would create a webhook endpoint and listen for the checkout.session.completed event, and trigger your emails from there. Building a webhook endpoint should be no more difficult than building any other endpoint on your server, with there only being some small extra logic to verify incoming requests.

Another option would be to use a tool like Zapier to listen for these events from Stripe and trigger various flows from them: https://stripe.com/partners/zapier

Body:
I have just integrated Stripe Checkout with my Django app. However, from their code:

 session = stripe.checkout.Session.create(
        customer_email=customer.email,
        payment_method_types=['card'],
        line_items=line_items,

        mode='payment',
        success_url='http://127.0.0.1:8000/SUCCESS/?session_id={CHECKOUT_SESSION_ID}',
        cancel_url='http://127.0.0.1:8000/cart'
        )

It redirects to a Success_url. I would like to display their order info and send an email from the success page but currently, everyone can visit(would cause random emails etc). Is there a way i can limit this for the person that just checked out? Thank you!


问:
How to Fixed / Lock Position of Background Image & Divs Containing Images
I have a map image (1080x1080px) I want this to be the the background of the body or a container div. I need the image to stay fixed in its place always, even when resizing the browser window.

I have divs inside of the main div container and these divs have images which are map markers that have been places at specific locations and they are toggled on and off as required.

Both the background image (map) and the markers need to stay in their position permanently.

How can I achieve this? What I have is not working...

body, html {
  height: 100%;
}

#bg {
  background-image: url(treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

  input:checked + .hidable {
    display: none;
  }

  input:not(:checked) + .showable {
    display: none;
  }

  #mark01 {
    position: absolute;
    top: 240px;
    right: 490px;
  }

  #mark02 {
    position: absolute;
    top: 480px;
    left: 460px;
  }

  #mark03 {
    position: absolute;
    bottom: 260px;
    right: 490px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Treasure Map</title>
</head>
<body>

  <div id="bg">
    <div id="menu">
      <input type="checkbox" /> Marker 1
      <div class="showable"><img id="mark01" src="xmark_01.png" alt="X Mark Red"></div>
      <input type="checkbox" /> Marker 2
      <div class="showable"><img id="mark02" src="xmark_02.png" alt="X Mark Green"></div>
      <input type="checkbox" /> Marker 3
      <div class="showable"><img id="mark03" src="xmark_03.png" alt="X Mark Magenta"></div>
    </div>
  </div>

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

答:
I'm only loading the background image in the HTML in the case that you're pulling the image dynamically via PHP. Otherwise, you can create separate classes with background images in the CSS file.

fixed and cover didn't use to play well together, and you would have to put the height property in an outer container, but I tested this code on Chrome, Firefox, Safari, and Opera, and it works fine.

Body:
I have a map image (1080x1080px) I want this to be the the background of the body or a container div. I need the image to stay fixed in its place always, even when resizing the browser window.

I have divs inside of the main div container and these divs have images which are map markers that have been places at specific locations and they are toggled on and off as required.

Both the background image (map) and the markers need to stay in their position permanently.

How can I achieve this? What I have is not working...

body, html {
  height: 100%;
}

#bg {
  background-image: url(treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

  input:checked + .hidable {
    display: none;
  }

  input:not(:checked) + .showable {
    display: none;
  }

  #mark01 {
    position: absolute;
    top: 240px;
    right: 490px;
  }

  #mark02 {
    position: absolute;
    top: 480px;
    left: 460px;
  }

  #mark03 {
    position: absolute;
    bottom: 260px;
    right: 490px;
  }

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Treasure Map</title>

      <input type="checkbox" /> Marker 1

      <input type="checkbox" /> Marker 2

      <input type="checkbox" /> Marker 3


答:
I think you have an issue with the quotations - You have a single set of quotes wrapped around the width and height so the computer thinks you're trying inline CSS. It should be:

```

Title: HTML Table Row Height Problem (height="x" vs style="height:x")

Body:
I think you have an issue with the quotations - You have a single set of quotes wrapped around the width and height so the computer thinks you're trying inline CSS. It should be:

<tr id="topRow" style="width:100%;" height="100px"></tr>


问:
Is an auth token in query string the only solution for a simple get request?
I am using JWT to authenticate and authorize requests made by a Single Page Application.

During the navigation in the application, I use XMLHttpRequest so I am able to set a header and use the token like this:

```<code>headers:
Authorization: Bearer MyJWTToken
</code>```

However, I sometimes need to download a protected file in that application so I have to provide a link like this one where I can't set any header:

```<code><a target="_blank" href="/api/protected-uri?access_token=MyJWTToken">Download Invoice</a>
</code>```

I read that using the token in the query string is not secure at all because it could end in the server logs or in the user browser history.

However, I can't see any other solution. Is this really a bad practice? How to bypass this problem? Should I make use of the browser cookies?

答: What I would do (and have done) is link to an application route that then redirects the user to the appropriate destination. This way you avoid including auth data in the rendered HTML page.</p>

Body:
I am using JWT to authenticate and authorize requests made by a Single Page Application.

During the navigation in the application, I use XMLHttpRequest so I am able to set a header and use the token like this:

headers:
Authorization: Bearer MyJWTToken

However, I sometimes need to download a protected file in that application so I have to provide a link like this one where I can't set any header:

Download Invoice

I read that using the token in the query string is not secure at all because it could end in the server logs or in the user browser history.

However, I can't see any other solution. Is this really a bad practice? How to bypass this problem? Should I make use of the browser cookies?


问:
C++ concept check vs inheritance
What is the relationship between using virtual functions and C++ inheritance mechanisms versus using templates and something like boost concepts?

It seems like there is quite an overlap of what is possible. Namely, it appears to be possible to achieve polymorphic behavior with either approach. So, when does it make sense to favor one over the other?

The reason why I bring this up is because I have a templated container, where the containers themselves have a hierarchical relationship. I would like to write algorithms that use these containers without caring about which specific container it is. Also, some algorithms would benefit from knowing that the template type satisfied certain concepts (Comparable, for example).

So, on one hand, I want containers to behave polymorphicly. On the other, I still have to use concepts if I want to correctly implement some algorithms. What is a junior developer to do?

答: If a decision can be made at compile-time, use templates. Otherwise use inheritance and virtual functions.</p>

OwnerDisplayName: Voltaire

ContentLicense: CC BY-SA 2.5

Title: C++ concept check vs inheritance

OwnerDisplayName: anon


问:
'bitwise_and' not supported for the input types Numpy array
I am trying to calculate F1_Score using numpy array using the code below

```<code>ypred = np.squeeze(imgs_mask_predict[jj,:,:,:])
ytrue = np.squeeze(imgs_test_mask[jj,:,:,:])

def f1_score_single(y_true, y_pred):
    y_true = y_true.flatten('F')
    y_pred = y_pred.flatten('F')
    cross_size = len(y_true & y_pred)
    if cross_size == 0: return 0.
    p = 1. * cross_size / len(y_pred)
    r = 1. * cross_size / len(y_true)
    return (2. * (p * r) / (p + r))
</code>```

I get an error

"ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' "  at this line of code

```<code>    cross_size = len(y_true & y_pred)
</code>```

I tried to search for this error but did not get the reason and solution for this. How should I resolve this?

答:
you can try intersect1d instead of &, for example, the use of np.intersect1d will do the same as you intend to do with &

```<code>import numpy as np
y_true=np.array([1.0,2.0,4.0,1.0,2.0,4.0,1.0,2.0,4.0,1.0])
y_score=np.array([1.0,1.0,2.0,4.0,1.0,2.0,4.0,1.0,2.0,4.0])
x=np.intersect1d(y_true, y_score)
print(x)
</code>```

the result will be [1. 2. 4.]

you can test the program here https://www.programiz.com/python-programming/online-compiler/

Body:
I am trying to calculate F1_Score using numpy array using the code below

ypred = np.squeeze(imgs_mask_predict[jj,:,:,:])
ytrue = np.squeeze(imgs_test_mask[jj,:,:,:])

def f1_score_single(y_true, y_pred):
    y_true = y_true.flatten('F')
    y_pred = y_pred.flatten('F')
    cross_size = len(y_true & y_pred)
    if cross_size == 0: return 0.
    p = 1. * cross_size / len(y_pred)
    r = 1. * cross_size / len(y_true)
    return (2. * (p * r) / (p + r))

I get an error

"ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' "  at this line of code

    cross_size = len(y_true & y_pred)

I tried to search for this error but did not get the reason and solution for this. How should I resolve this?

Body:
you can try intersect1d instead of &, for example, the use of np.intersect1d will do the same as you intend to do with &

import numpy as np
y_true=np.array([1.0,2.0,4.0,1.0,2.0,4.0,1.0,2.0,4.0,1.0])
y_score=np.array([1.0,1.0,2.0,4.0,1.0,2.0,4.0,1.0,2.0,4.0])
x=np.intersect1d(y_true, y_score)
print(x)

the result will be [1. 2. 4.]

you can test the program here https://www.programiz.com/python-programming/online-compiler/


问:
How to delete data from firebase android
I faced an issue when I had to delete that data which user entered in here this photo. If the user entered enrollment number 60 then I have to delete all data from marks where the enrollment number is 60.

It deletes the data which user entered and it verifies that enrollment from marks and delete all data where enrollment is 66 it means delete that document or node.

I tried the following that did not work.

reff.child("Marks").removeValue().equals(et1);

答:
To delete data do the following:

```<code>DatabaseReference data = FirebaseDatabase.getInstance().getReference().child("Marks");
data.orderByChild("enrollment").equalTo("66").addListenerForSingleValueEvent(new ValueEventListener() {
         @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
      for(DataSnapshot data: dataSnapshot.getChildren()){
            data.getRef().removeValue();

                  }

            }
        @Override
       public void onCancelled(DatabaseError databaseError) {

               }
          });
</code>```

Add a reference to child Marks then using the query orderByChild you can get the correct node and delete it

Body:
To delete data do the following:

DatabaseReference data = FirebaseDatabase.getInstance().getReference().child("Marks");
data.orderByChild("enrollment").equalTo("66").addListenerForSingleValueEvent(new ValueEventListener() {
         @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
      for(DataSnapshot data: dataSnapshot.getChildren()){
            data.getRef().removeValue();

                  }

            }
        @Override
       public void onCancelled(DatabaseError databaseError) {

               }
          });

Add a reference to child Marks then using the query orderByChild you can get the correct node and delete it


问:
Can I use kwargs to pass this part of the function?
I am using this autoclean function in the datacleaner library in python.

It does 3 things,

(1)impute missing values with mode (Categorical)

(2) impute missing values with median (continuous)

(3) and then does label encoding

I want the function to 'skip' encoding. I know there is a kwarg in the function that I can use.

How should I go about it?

```<code> from datacleaner import autoclean
  cdf= autoclean(df, encoder=True, encoder_kwargs=None)
</code>```

This is the error message(which also means the underlying code):

```<code>     90         if str(input_dataframe[column].values.dtype) == 'object':
     91             if encoder is not None:
---> 92                 column_encoder = encoder(**encoder_kwargs).fit(input_dataframe[column].values)
     93             else:
     94                 column_encoder = LabelEncoder().fit(input_dataframe[column].values)
</code>```

答:
Python’s ** notation as a prefix expects a dictionary to unpack as kwargs, so it makes sense that it errors when given None as a value.

Try setting encoder_kwargs={} in your call instead, that should fix the immediate error. I don’t know if that will “skip” encoding like you wanted, though.

Body:
I am using this autoclean function in the datacleaner library in python.

It does 3 things,

(1)impute missing values with mode (Categorical)

(2) impute missing values with median (continuous)

(3) and then does label encoding

I want the function to 'skip' encoding. I know there is a kwarg in the function that I can use.

How should I go about it?

 from datacleaner import autoclean
  cdf= autoclean(df, encoder=True, encoder_kwargs=None)

This is the error message(which also means the underlying code):

     90         if str(input_dataframe[column].values.dtype) == 'object':
     91             if encoder is not None:
---> 92                 column_encoder = encoder(**encoder_kwargs).fit(input_dataframe[column].values)
     93             else:
     94                 column_encoder = LabelEncoder().fit(input_dataframe[column].values)